From 19ca96edc029e221dd51bf85be28e34d02dadf5d Mon Sep 17 00:00:00 2001 From: Klesh Wong Date: Wed, 30 Jun 2021 14:49:50 +0800 Subject: [PATCH 1/3] [feature] remember window positions --- win/JSON.ahk | 374 +++++++++++++++++++++++++++++++++++++++++++++++++++ win/win.ahk | 80 ++++++++++- 2 files changed, 453 insertions(+), 1 deletion(-) create mode 100644 win/JSON.ahk diff --git a/win/JSON.ahk b/win/JSON.ahk new file mode 100644 index 0000000..975c528 --- /dev/null +++ b/win/JSON.ahk @@ -0,0 +1,374 @@ +/** + * Lib: JSON.ahk + * JSON lib for AutoHotkey. + * Version: + * v2.1.3 [updated 04/18/2016 (MM/DD/YYYY)] + * License: + * WTFPL [http://wtfpl.net/] + * Requirements: + * Latest version of AutoHotkey (v1.1+ or v2.0-a+) + * Installation: + * Use #Include JSON.ahk or copy into a function library folder and then + * use #Include + * Links: + * GitHub: - https://github.com/cocobelgica/AutoHotkey-JSON + * Forum Topic - http://goo.gl/r0zI8t + * Email: - cocobelgica gmail com + */ + + +/** + * Class: JSON + * The JSON object contains methods for parsing JSON and converting values + * to JSON. Callable - NO; Instantiable - YES; Subclassable - YES; + * Nestable(via #Include) - NO. + * Methods: + * Load() - see relevant documentation before method definition header + * Dump() - see relevant documentation before method definition header + */ +class JSON +{ + /** + * Method: Load + * Parses a JSON string into an AHK value + * Syntax: + * value := JSON.Load( text [, reviver ] ) + * Parameter(s): + * value [retval] - parsed value + * text [in, ByRef] - JSON formatted string + * reviver [in, opt] - function object, similar to JavaScript's + * JSON.parse() 'reviver' parameter + */ + class Load extends JSON.Functor + { + Call(self, ByRef text, reviver:="") + { + this.rev := IsObject(reviver) ? reviver : false + ; Object keys(and array indices) are temporarily stored in arrays so that + ; we can enumerate them in the order they appear in the document/text instead + ; of alphabetically. Skip if no reviver function is specified. + this.keys := this.rev ? {} : false + + static quot := Chr(34), bashq := "\" . quot + , json_value := quot . "{[01234567890-tfn" + , json_value_or_array_closing := quot . "{[]01234567890-tfn" + , object_key_or_object_closing := quot . "}" + + key := "" + is_key := false + root := {} + stack := [root] + next := json_value + pos := 0 + + while ((ch := SubStr(text, ++pos, 1)) != "") { + if InStr(" `t`r`n", ch) + continue + if !InStr(next, ch, 1) + this.ParseError(next, text, pos) + + holder := stack[1] + is_array := holder.IsArray + + if InStr(",:", ch) { + next := (is_key := !is_array && ch == ",") ? quot : json_value + + } else if InStr("}]", ch) { + ObjRemoveAt(stack, 1) + next := stack[1]==root ? "" : stack[1].IsArray ? ",]" : ",}" + + } else { + if InStr("{[", ch) { + ; Check if Array() is overridden and if its return value has + ; the 'IsArray' property. If so, Array() will be called normally, + ; otherwise, use a custom base object for arrays + static json_array := Func("Array").IsBuiltIn || ![].IsArray ? {IsArray: true} : 0 + + ; sacrifice readability for minor(actually negligible) performance gain + (ch == "{") + ? ( is_key := true + , value := {} + , next := object_key_or_object_closing ) + ; ch == "[" + : ( value := json_array ? new json_array : [] + , next := json_value_or_array_closing ) + + ObjInsertAt(stack, 1, value) + + if (this.keys) + this.keys[value] := [] + + } else { + if (ch == quot) { + i := pos + while (i := InStr(text, quot,, i+1)) { + value := StrReplace(SubStr(text, pos+1, i-pos-1), "\\", "\u005c") + + static tail := A_AhkVersion<"2" ? 0 : -1 + if (SubStr(value, tail) != "\") + break + } + + if (!i) + this.ParseError("'", text, pos) + + value := StrReplace(value, "\/", "/") + , value := StrReplace(value, bashq, quot) + , value := StrReplace(value, "\b", "`b") + , value := StrReplace(value, "\f", "`f") + , value := StrReplace(value, "\n", "`n") + , value := StrReplace(value, "\r", "`r") + , value := StrReplace(value, "\t", "`t") + + pos := i ; update pos + + i := 0 + while (i := InStr(value, "\",, i+1)) { + if !(SubStr(value, i+1, 1) == "u") + this.ParseError("\", text, pos - StrLen(SubStr(value, i+1))) + + uffff := Abs("0x" . SubStr(value, i+2, 4)) + if (A_IsUnicode || uffff < 0x100) + value := SubStr(value, 1, i-1) . Chr(uffff) . SubStr(value, i+6) + } + + if (is_key) { + key := value, next := ":" + continue + } + + } else { + value := SubStr(text, pos, i := RegExMatch(text, "[\]\},\s]|$",, pos)-pos) + + static number := "number", integer :="integer" + if value is %number% + { + if value is %integer% + value += 0 + } + else if (value == "true" || value == "false") + value := %value% + 0 + else if (value == "null") + value := "" + else + ; we can do more here to pinpoint the actual culprit + ; but that's just too much extra work. + this.ParseError(next, text, pos, i) + + pos += i-1 + } + + next := holder==root ? "" : is_array ? ",]" : ",}" + } ; If InStr("{[", ch) { ... } else + + is_array? key := ObjPush(holder, value) : holder[key] := value + + if (this.keys && this.keys.HasKey(holder)) + this.keys[holder].Push(key) + } + + } ; while ( ... ) + + return this.rev ? this.Walk(root, "") : root[""] + } + + ParseError(expect, ByRef text, pos, len:=1) + { + static quot := Chr(34), qurly := quot . "}" + + line := StrSplit(SubStr(text, 1, pos), "`n", "`r").Length() + col := pos - InStr(text, "`n",, -(StrLen(text)-pos+1)) + msg := Format("{1}`n`nLine:`t{2}`nCol:`t{3}`nChar:`t{4}" + , (expect == "") ? "Extra data" + : (expect == "'") ? "Unterminated string starting at" + : (expect == "\") ? "Invalid \escape" + : (expect == ":") ? "Expecting ':' delimiter" + : (expect == quot) ? "Expecting object key enclosed in double quotes" + : (expect == qurly) ? "Expecting object key enclosed in double quotes or object closing '}'" + : (expect == ",}") ? "Expecting ',' delimiter or object closing '}'" + : (expect == ",]") ? "Expecting ',' delimiter or array closing ']'" + : InStr(expect, "]") ? "Expecting JSON value or array closing ']'" + : "Expecting JSON value(string, number, true, false, null, object or array)" + , line, col, pos) + + static offset := A_AhkVersion<"2" ? -3 : -4 + throw Exception(msg, offset, SubStr(text, pos, len)) + } + + Walk(holder, key) + { + value := holder[key] + if IsObject(value) { + for i, k in this.keys[value] { + ; check if ObjHasKey(value, k) ?? + v := this.Walk(value, k) + if (v != JSON.Undefined) + value[k] := v + else + ObjDelete(value, k) + } + } + + return this.rev.Call(holder, key, value) + } + } + + /** + * Method: Dump + * Converts an AHK value into a JSON string + * Syntax: + * str := JSON.Dump( value [, replacer, space ] ) + * Parameter(s): + * str [retval] - JSON representation of an AHK value + * value [in] - any value(object, string, number) + * replacer [in, opt] - function object, similar to JavaScript's + * JSON.stringify() 'replacer' parameter + * space [in, opt] - similar to JavaScript's JSON.stringify() + * 'space' parameter + */ + class Dump extends JSON.Functor + { + Call(self, value, replacer:="", space:="") + { + this.rep := IsObject(replacer) ? replacer : "" + + this.gap := "" + if (space) { + static integer := "integer" + if space is %integer% + Loop, % ((n := Abs(space))>10 ? 10 : n) + this.gap .= " " + else + this.gap := SubStr(space, 1, 10) + + this.indent := "`n" + } + + return this.Str({"": value}, "") + } + + Str(holder, key) + { + value := holder[key] + + if (this.rep) + value := this.rep.Call(holder, key, ObjHasKey(holder, key) ? value : JSON.Undefined) + + if IsObject(value) { + ; Check object type, skip serialization for other object types such as + ; ComObject, Func, BoundFunc, FileObject, RegExMatchObject, Property, etc. + static type := A_AhkVersion<"2" ? "" : Func("Type") + if (type ? type.Call(value) == "Object" : ObjGetCapacity(value) != "") { + if (this.gap) { + stepback := this.indent + this.indent .= this.gap + } + + is_array := value.IsArray + ; Array() is not overridden, rollback to old method of + ; identifying array-like objects. Due to the use of a for-loop + ; sparse arrays such as '[1,,3]' are detected as objects({}). + if (!is_array) { + for i in value + is_array := i == A_Index + until !is_array + } + + str := "" + if (is_array) { + Loop, % value.Length() { + if (this.gap) + str .= this.indent + + v := this.Str(value, A_Index) + str .= (v != "") ? v . "," : "null," + } + } else { + colon := this.gap ? ": " : ":" + for k in value { + v := this.Str(value, k) + if (v != "") { + if (this.gap) + str .= this.indent + + str .= this.Quote(k) . colon . v . "," + } + } + } + + if (str != "") { + str := RTrim(str, ",") + if (this.gap) + str .= stepback + } + + if (this.gap) + this.indent := stepback + + return is_array ? "[" . str . "]" : "{" . str . "}" + } + + } else ; is_number ? value : "value" + return ObjGetCapacity([value], 1)=="" ? value : this.Quote(value) + } + + Quote(string) + { + static quot := Chr(34), bashq := "\" . quot + + if (string != "") { + string := StrReplace(string, "\", "\\") + ; , string := StrReplace(string, "/", "\/") ; optional in ECMAScript + , string := StrReplace(string, quot, bashq) + , string := StrReplace(string, "`b", "\b") + , string := StrReplace(string, "`f", "\f") + , string := StrReplace(string, "`n", "\n") + , string := StrReplace(string, "`r", "\r") + , string := StrReplace(string, "`t", "\t") + + static rx_escapable := A_AhkVersion<"2" ? "O)[^\x20-\x7e]" : "[^\x20-\x7e]" + while RegExMatch(string, rx_escapable, m) + string := StrReplace(string, m.Value, Format("\u{1:04x}", Ord(m.Value))) + } + + return quot . string . quot + } + } + + /** + * Property: Undefined + * Proxy for 'undefined' type + * Syntax: + * undefined := JSON.Undefined + * Remarks: + * For use with reviver and replacer functions since AutoHotkey does not + * have an 'undefined' type. Returning blank("") or 0 won't work since these + * can't be distnguished from actual JSON values. This leaves us with objects. + * Replacer() - the caller may return a non-serializable AHK objects such as + * ComObject, Func, BoundFunc, FileObject, RegExMatchObject, and Property to + * mimic the behavior of returning 'undefined' in JavaScript but for the sake + * of code readability and convenience, it's better to do 'return JSON.Undefined'. + * Internally, the property returns a ComObject with the variant type of VT_EMPTY. + */ + Undefined[] + { + get { + static empty := {}, vt_empty := ComObject(0, &empty, 1) + return vt_empty + } + } + + class Functor + { + __Call(method, ByRef arg, args*) + { + ; When casting to Call(), use a new instance of the "function object" + ; so as to avoid directly storing the properties(used across sub-methods) + ; into the "function object" itself. + if IsObject(method) + return (new this).Call(method, arg, args*) + else if (method == "") + return (new this).Call(arg, args*) + } + } +} \ No newline at end of file diff --git a/win/win.ahk b/win/win.ahk index 9ad4697..81848ae 100644 --- a/win/win.ahk +++ b/win/win.ahk @@ -9,6 +9,11 @@ CoordMode, Mouse, Screen ; mouse coordinates relative to the screen ; ========================= ; global RATIO := 0.618 global RATIO := 0.382 +global ARRANGEMENT := Object() +global ID_SEEN := Object() +global ARRANGEMENT_PATH := A_AppData . "\arrangement.json" +LoadArrangement() +WatchNewWindow() ; ========================= ; BINDINGS ; ========================= @@ -28,6 +33,8 @@ global RATIO := 0.382 #k:: FocusWinByDirection("left") #+j::MoveActiveWinByDirection("right") #+k::MoveActiveWinByDirection("left") +#+r::reload +#t::ShowDebug() ; Ctrl + Alt + v : paste as plain text ^!v:: @@ -102,6 +109,7 @@ Return ; ========================= #Include, WinGetPosEx.ahk +#Include, JSON.ahk ShowGeometry(x, y, w, h) { MsgBox, , Geometry,% Format("x:{}, y:{}, w: {}, h: {}", x, y, w, h) @@ -176,9 +184,69 @@ MoveActiveWinByDirection(direction) { wx := ww ww := w - ww } - WinMove, A,, wx - l, wy - t, ww + l + r, wh + t + b + pos := [wx - l, wy - t, ww + l + r, wh + t + b] + ; store arrangement + global ARRANGEMENT + key := GetActiveWindowClassPath() + ARRANGEMENT[key] := pos + SaveArrangement() + ; end store arrangement + WinMove, A,, pos[1], pos[2], pos[3], pos[4] } + +SaveArrangement() { + global ARRANGEMENT + global ARRANGEMENT_PATH + file := FileOpen(ARRANGEMENT_PATH, "w") + file.Write(JSON.Dump(ARRANGEMENT,, 2)) + file.Close() +} + +LoadArrangement() { + global ARRANGEMENT + global ARRANGEMENT_PATH + try { + FileRead, temp, %ARRANGEMENT_PATH% + ARRANGEMENT := JSON.Load(temp) + ShowObject(ARRANGEMENT) + } catch { + ARRANGEMENT := Object() + } + if not IsObject(ARRANGEMENT) { + ARRANGEMENT := Object() + } +} + +GetActiveWindowClassPath() { + WinGet processPath, ProcessPath, A + WinGetClass windowClass, A + return processPath . ":" . windowClass +} + +IsActiveWindowSeen() { + global ID_SEEN + WinGet winId, ID, A + seen := ID_SEEN.HasKey(winId) + ID_SEEN[winId] := true +} + +WatchNewWindow() { + global ARRANGEMENT + Loop { + WinWaitActive A ; makes the active window to be the Last Found + if not IsActiveWindowSeen() { + classPath := GetActiveWindowClassPath() + if ARRANGEMENT.HasKey(classPath) { + pos := ARRANGEMENT[classPath] + WinMove, A,, pos[1], pos[2], pos[3], pos[4] + } + } + WinWaitNotActive ; waits until the active window changes + } +} + + ToggleActiveWinMaximum() { WinGet, isMax, MinMax, A if (isMax) { @@ -196,4 +264,14 @@ GetSelectedText() { selection = %Clipboard% ; save the content of the clipboard Clipboard = %tmp% ; restore old content of the clipboard return selection +} + +ShowDebug() { + global ARRANGEMENT + ShowObject(ARRANGEMENT) +} + +ShowObject(obj) { + msg := JSON.Dump(obj) + MsgBox, %msg% } \ No newline at end of file From d63ed0e7379e8b1508c4a6ce30c999dabfca2171 Mon Sep 17 00:00:00 2001 From: Klesh Wong Date: Wed, 30 Jun 2021 14:58:05 +0800 Subject: [PATCH 2/3] [bugfix] xodo pdf pos does not match --- win/win.ahk | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/win/win.ahk b/win/win.ahk index 81848ae..e8a3ec4 100644 --- a/win/win.ahk +++ b/win/win.ahk @@ -209,7 +209,6 @@ LoadArrangement() { try { FileRead, temp, %ARRANGEMENT_PATH% ARRANGEMENT := JSON.Load(temp) - ShowObject(ARRANGEMENT) } catch { ARRANGEMENT := Object() } @@ -239,6 +238,7 @@ WatchNewWindow() { classPath := GetActiveWindowClassPath() if ARRANGEMENT.HasKey(classPath) { pos := ARRANGEMENT[classPath] + WinRestore, A WinMove, A,, pos[1], pos[2], pos[3], pos[4] } } @@ -267,8 +267,7 @@ GetSelectedText() { } ShowDebug() { - global ARRANGEMENT - ShowObject(ARRANGEMENT) + ShowActiveWinGeometry() } ShowObject(obj) { From 527a1886f1ed1ef7da183d382d4a8b50b9d3eac8 Mon Sep 17 00:00:00 2001 From: Klesh Wong Date: Thu, 1 Jul 2021 22:16:25 +0800 Subject: [PATCH 3/3] [feature] add padding --- win/win.ahk | 70 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 52 insertions(+), 18 deletions(-) diff --git a/win/win.ahk b/win/win.ahk index e8a3ec4..1cf9852 100644 --- a/win/win.ahk +++ b/win/win.ahk @@ -9,9 +9,10 @@ CoordMode, Mouse, Screen ; mouse coordinates relative to the screen ; ========================= ; global RATIO := 0.618 global RATIO := 0.382 -global ARRANGEMENT := Object() global ID_SEEN := Object() +global ARRANGEMENT := Object() global ARRANGEMENT_PATH := A_AppData . "\arrangement.json" +global PADDING := 10 LoadArrangement() WatchNewWindow() ; ========================= @@ -24,8 +25,9 @@ WatchNewWindow() Send ^a Send {BS} return -#=::SoundSet,+5 -#-::SoundSet,-5 +#=::SoundSet, +5 +#-::SoundSet, -5 +#\::Send {Volume_Mute} #BS::#l #f:: ToggleActiveWinMaximum() ^#p::ShowActiveWinGeometry() @@ -34,6 +36,8 @@ WatchNewWindow() #+j::MoveActiveWinByDirection("right") #+k::MoveActiveWinByDirection("left") #+r::reload +#i::IgnoreArrangementForActiveWindow() +#+i::UnignoreArrangementForActiveWindow() #t::ShowDebug() ; Ctrl + Alt + v : paste as plain text @@ -97,7 +101,7 @@ Return ; Capslock & ,:: Send {PgDn} ; Capslock & .:: Send {End} -; Capslock & Space:: SetCapsLockState % !GetKeyState("CapsLock", "T") +; Capslock & Space:: SetCapsLockState % !GetKeyState("CapsLock", "T") ; +CapsLock:: ; Send {~} ; SetCapsLockState % !GetKeyState("CapsLock", "T") @@ -173,6 +177,7 @@ MoveActiveWinByDirection(direction) { WinRestore, A } global RATIO + global PADDING GetCursorMonGeometry(x, y, w, h) activeWinId := WinExist("A") WinGetPosEx(activeWinId, wx, wy, ww, wh, l, t, r, b) @@ -181,17 +186,16 @@ MoveActiveWinByDirection(direction) { ww := floor(w * RATIO) wh := h if (direction = "right") { - wx := ww + wx := ww + floor(PADDING / 2) ww := w - ww + } else { + wx := wx + PADDING } - pos := [wx - l, wy - t, ww + l + r, wh + t + b] - ; store arrangement - global ARRANGEMENT - key := GetActiveWindowClassPath() - ARRANGEMENT[key] := pos - SaveArrangement() - ; end store arrangement - WinMove, A,, pos[1], pos[2], pos[3], pos[4] + ww := ww - floor(PADDING * 1.5) + wy := wy + PADDING + wh := wh - PADDING * 2 + WinMove, A,, wx - l, wy - t, ww + l + r, wh + t + b + SaveActiveWindowDirection(direction) } @@ -215,6 +219,12 @@ LoadArrangement() { if not IsObject(ARRANGEMENT) { ARRANGEMENT := Object() } + if not IsObject(ARRANGEMENT["windows"]) { + ARRANGEMENT["windows"] := Object() + } + if not IsObject(ARRANGEMENT["ignore"]) { + ARRANGEMENT["ignore"] := Object() + } } GetActiveWindowClassPath() { @@ -228,18 +238,42 @@ IsActiveWindowSeen() { WinGet winId, ID, A seen := ID_SEEN.HasKey(winId) ID_SEEN[winId] := true + return seen +} + +IgnoreArrangementForActiveWindow() { + global ARRANGEMENT + ARRANGEMENT["ignore"][GetActiveWindowClassPath()] := true + SaveArrangement() +} + +UnignoreArrangementForActiveWindow() { + global ARRANGEMENT + ARRANGEMENT["ignore"].Delete(GetActiveWindowClassPath()) + SaveArrangement() +} + +IsActiveWindowIgnore() { + global ARRANGEMENT + WinGetTitle, title, A + return ARRANGEMENT["ignore"].HasKey(GetActiveWindowClassPath()) or title = "" +} + +SaveActiveWindowDirection(direction) { + global ARRANGEMENT + key := GetActiveWindowClassPath() + ARRANGEMENT["windows"][key] := direction + SaveArrangement() } WatchNewWindow() { global ARRANGEMENT Loop { WinWaitActive A ; makes the active window to be the Last Found - if not IsActiveWindowSeen() { + if not IsActiveWindowSeen() and not IsActiveWindowIgnore() { classPath := GetActiveWindowClassPath() - if ARRANGEMENT.HasKey(classPath) { - pos := ARRANGEMENT[classPath] - WinRestore, A - WinMove, A,, pos[1], pos[2], pos[3], pos[4] + if ARRANGEMENT["windows"].HasKey(classPath) { + MoveActiveWinByDirection(ARRANGEMENT["windows"][classPath]) } } WinWaitNotActive ; waits until the active window changes