production-taskbar-client / bin / win-control-server.ahk
win-control-server.ahk
Raw
/************************************************************************
 *         Windows window control for taskbar, autohotkey v2
 ************************************************************************/

/************************ Compiler directives ***************************/
VERSION := "2.0.0"
;@Ahk2Exe-Let version = %A_PriorLine~U)^(.+"){1}(.+)".*$~$2%
NAME := "wincontrolserver"
;@Ahk2Exe-Let name = %A_PriorLine~U)^(.+"){1}(.+)".*$~$2%
;@Ahk2Exe-SetName %U_name%
;@Ahk2Exe-SetVersion %U_version%
;@Ahk2Exe-SetMainIcon .\wincontrolicon.ico
;@Ahk2Exe-SetDescription Autohotkey wincontrol for taskbar
;@Ahk2Exe-SetCopyright Mykyta.Nehrych@sebn.com 2023
;@Ahk2Exe-SetCompanyName SEBN.UA CHE
;@Ahk2Exe-Base ..\v2\AutoHotkey32.exe

/************************** Runtime directives ***************************/
#Requires AutoHotkey v2.0
#SingleInstance Force
#Include .\lib\JXON.ahk
Persistent(true)
if A_IsCompiled {
    #NoTrayIcon
    #Warn All, Off
} else {
    #Warn All, StdOut
}
ListLines(false)
SetWorkingDir(A_ScriptDir)
SetWinDelay(50)
SetTitleMatchMode("RegEx")
FileEncoding("UTF-8")

/*************************** Startup checkup *****************************/
if (A_Args.Length < 1) {
    MsgBox("Standalone usage restricted. Taskbar manage this itself.", , "64 T10")
    ExitApp
}

logfile := NAME . ".log"
for (a in A_Args) {
    arr := StrSplit(a, "=")
    if (arr[1] = "logdir")
        if DirExist(arr[2])
            logfile := arr[2] . "\" . logfile

}
LogError(exception, mode) {
    if (FileExist(logfile)) {
        if (FileGetSize(logfile, "M") >= 1) {
            FileDelete(logfile)
        }
    }

    datetime := FormatTime(, "dd.MM.yyyy HH:mm:ss")
    text := "[" . datetime . "] Error on line " exception.Line ": " exception.Message " in " exception.What ". Stack:`n" exception.Stack "`n"
    FileAppend(text, logfile)
    return -1
}
OnError(LogError, -1)
/**************************************************************************/

stdin := FileOpen("*", "r")
stout := FileOpen("*", "w")

GroupAdd("browser", "ahk_exe chrome.exe")
GroupAdd("browser", "ahk_exe msedge.exe")
GroupAdd("browser", "ahk_exe iexplore.exe")
GroupAdd("browser", "ahk_exe firefox.exe")

RunResultToStout(path, pid := 0, err := "") {
    message := Map("path", path, "pid", pid, "err", err ? err.Message : "")
    FileAppend(Jxon_Dump(message), "*")
}

handler(inputStr) {
    if (!inputStr)
        return

    static windows := Map()
    dataStr := RTrim(inputStr, "`n")
    data := Jxon_Load(&dataStr)
    titleFallback := ""

    if (data["event"] = "open") {
        if (data["windowProcess"]) {
            title := "ahk_exe i)" data["windowProcess"]
        } else {
            SplitPath(StrReplace(data["file"], "/", "\"), &filename)
            title := "ahk_exe i)" filename
            if (data["fallback_path"]) {
                SplitPath(StrReplace(data["fallback_path"], "/", "\"),
                    &filenameFallback)
                titleFallback := "ahk_exe i)" filenameFallback
            }
        }
        if (WinExist(title)) {
            WinActivate(title)
        } else if (titleFallback and WinExist(titleFallback)) {
            WinActivate(titleFallback)
        } else {
            if (FileExist(data["file"])) {
                ; setting up workdir prevent lock bin folder with runned apps
                SplitPath(data["file"], , &dir)
                params := data["params"] ? " `"" . data["params"] . "`"" : ""
                try {
                    Run(data["file"] . params, dir, , &pid)
                    RunResultToStout(data["file"], pid)
                } catch Error as err {
                    if (data["fallback_path"]) {
                        SplitPath(data["fallback_path"], , &dir)
                        try {
                            Run(data["fallback_path"] . params, dir, , &pid)
                            RunResultToStout(data["file"], pid)
                        } catch Error as err {
                            RunResultToStout(data["file"], , err)
                        } }
                    RunResultToStout(data["file"], , err)
                }

            } else {
                RunResultToStout(data["file"], , Error("File not exist"))
            }
        }
        return
    }

    if (data["event"] = "open-browser") {
        if (windows.Has(data["url"])) {
            WinActivate("ahk_pid " windows[data["url"]])
            hwnd := WinWaitActive("ahk_pid " windows[data["url"]], , 1)
            if hwnd
                return
        }

        try {
            Run("explorer `"" . data["url"] . "`"", "C:\", , &pid)
            hwnd := WinWaitActive("ahk_group browser", , 6)
            if hwnd {
                windows.Set(data["url"], WinGetPID("A"))
            }
            RunResultToStout(data["url"], pid)
        } catch Error as err {
            RunResultToStout(data["url"], , err)
        }
        return
    }

}

Loop {
    stdinput := stdin.ReadLine()
    handler(stdinput)
}