added handling for remembering file paths, added gui option to disable zenity in GUI

This commit is contained in:
Concedo 2025-04-12 00:42:26 +08:00
parent f6b7fea979
commit a56cc72bd0

View file

@ -110,7 +110,8 @@ start_time = time.time()
last_req_time = time.time() last_req_time = time.time()
last_non_horde_req_time = time.time() last_non_horde_req_time = time.time()
currfinishreason = None currfinishreason = None
zenity_recent_dir = os.getcwd()
zenity_permitted = True
saved_stdout = None saved_stdout = None
saved_stderr = None saved_stderr = None
@ -3456,37 +3457,28 @@ def RunServerMultiThreaded(addr, port, server_handler):
sys.exit(0) sys.exit(0)
# Based on https://github.com/mathgeniuszach/xdialog/blob/main/xdialog/zenity_dialogs.py - MIT license | - Expanded version by Henk717 # Based on https://github.com/mathgeniuszach/xdialog/blob/main/xdialog/zenity_dialogs.py - MIT license | - Expanded version by Henk717
def zenity(filetypes=None, initialdir="", initialfile="", **kwargs) -> Tuple[int, str]:
import shutil
import subprocess
global zenity_recent_dir, zenity_permitted
def zenity_clean(txt: str): if not zenity_permitted:
return txt\ raise Exception("Zenity disabled, attempting to use TK GUI.")
.replace("\\", "\\\\")\ if sys.platform != "linux":
.replace("$", "\\$")\ raise Exception("Zenity GUI is only usable on Linux, attempting to use TK GUI.")
.replace("!", "\\!")\
.replace("*", "\\*")\
.replace("?", "\\?")\
.replace("&", "&")\
.replace("|", "|")\
.replace("<", "&lt;")\
.replace(">", "&gt;")\
.replace("(", "\\(")\
.replace(")", "\\)")\
.replace("[", "\\[")\
.replace("]", "\\]")\
.replace("{", "\\{")\
.replace("}", "\\}")\
def zenity(typ, filetypes=None, initialdir="", initialfile="", **kwargs) -> Tuple[int, str]:
import shutil, subprocess, os, platform
if not platform.system() == "Linux":
raise Exception("This feature should only be used on Linux, if you see this error there is no TK fallback implemented in the code.")
zenity_bin = shutil.which("zenity") zenity_bin = shutil.which("zenity")
if not zenity_bin: if not zenity_bin:
zenity_bin = shutil.which("yad") zenity_bin = shutil.which("yad")
if not zenity_bin: if not zenity_bin:
raise Exception("Zenity not present") raise Exception("Zenity not present, falling back to TK GUI.")
def zenity_clean(txt: str):
return txt.replace("\\", "\\\\").replace("$", "\\$").replace("!", "\\!").replace("*", "\\*")\
.replace("?", "\\?").replace("&", "&amp;").replace("|", "&#124;").replace("<", "&lt;").replace(">", "&gt;")\
.replace("(", "\\(").replace(")", "\\)").replace("[", "\\[").replace("]", "\\]").replace("{", "\\{").replace("}", "\\}")
# Build args based on keywords # Build args based on keywords
args = ['/usr/bin/env', zenity_bin, '--'+typ] args = ['/usr/bin/env', zenity_bin, '--file-selection']
for k, v in kwargs.items(): for k, v in kwargs.items():
if v is True: if v is True:
args.append(f'--{k.replace("_", "-").strip("-")}') args.append(f'--{k.replace("_", "-").strip("-")}')
@ -3503,7 +3495,7 @@ def zenity(typ, filetypes=None, initialdir="", initialfile="", **kwargs) -> Tupl
# Default filename and folder # Default filename and folder
if initialdir is None: if initialdir is None:
initialdir=os.getcwd() initialdir=zenity_recent_dir
if initialfile is None: if initialfile is None:
initialfile="" initialfile=""
initialpath = os.path.join(initialdir, initialfile) initialpath = os.path.join(initialdir, initialfile)
@ -3513,53 +3505,54 @@ def zenity(typ, filetypes=None, initialdir="", initialfile="", **kwargs) -> Tupl
clean_env.pop("LD_LIBRARY_PATH", None) clean_env.pop("LD_LIBRARY_PATH", None)
clean_env["PATH"] = "/usr/bin:/bin" clean_env["PATH"] = "/usr/bin:/bin"
proc = subprocess.Popen( procres = subprocess.run(
args, args,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
shell=False, env=clean_env,
env=clean_env check=False
) )
stdout, _ = proc.communicate() result = procres.stdout.decode('utf-8').strip()
if procres.returncode==0 and result:
return (proc.returncode, stdout.decode('utf-8').strip()) directory = result
if not os.path.isdir(result):
directory = os.path.dirname(result)
zenity_recent_dir = directory
return (procres.returncode, result)
# note: In this section we wrap around file dialogues to allow for zenity # note: In this section we wrap around file dialogues to allow for zenity
def zentk_askopenfilename(**options): def zentk_askopenfilename(**options):
try: try:
from os.path import isfile result = zenity(filetypes=options.get("filetypes"), initialdir=options.get("initialdir"), title=options.get("title"))[1]
result = zenity('file-selection', filetypes=options.get("filetypes"), initialdir=options.get("initialdir"), title=options.get("title"))[1] if result and not os.path.isfile(result):
if result and not isfile(result):
print("A folder was selected while we need a file, ignoring selection.") print("A folder was selected while we need a file, ignoring selection.")
return '' return ''
except: except Exception:
from tkinter.filedialog import askopenfilename from tkinter.filedialog import askopenfilename
result = askopenfilename(**options) result = askopenfilename(**options)
return result return result
def zentk_askopenmultiplefilenames(**options): def zentk_askopenmultiplefilenames(**options):
try: try:
from os.path import isfile files = zenity(filetypes=options.get("filetypes"), initialdir=options.get("initialdir"), title=options.get("title"), multiple=True, separator="\n")[1].splitlines()
files = zenity('file-selection', filetypes=options.get("filetypes"), initialdir=options.get("initialdir"), title=options.get("title"), multiple=True, separator="\n")[1].splitlines() result = tuple(filter(os.path.isfile, files))
result = tuple(filter(isfile, files)) except Exception:
except:
from tkinter.filedialog import askopenfilenames from tkinter.filedialog import askopenfilenames
result = askopenfilenames(**options) result = askopenfilenames(**options)
return result return result
def zentk_askdirectory(**options): def zentk_askdirectory(**options):
try: try:
result = zenity('file-selection', initialdir=options.get("initialdir"), title=options.get("title"), directory=True)[1] result = zenity(initialdir=options.get("initialdir"), title=options.get("title"), directory=True)[1]
except: except Exception:
from tkinter.filedialog import askdirectory from tkinter.filedialog import askdirectory
result = askdirectory(**options) result = askdirectory(**options)
return result return result
def zentk_asksaveasfilename(**options): def zentk_asksaveasfilename(**options):
try: try:
result = zenity('file-selection', filetypes=options.get("filetypes"), initialdir=options.get("initialdir"), initialfile=options.get("initialfile"), title=options.get("title"), save=True)[1] result = zenity(filetypes=options.get("filetypes"), initialdir=options.get("initialdir"), initialfile=options.get("initialfile"), title=options.get("title"), save=True)[1]
except: except Exception:
from tkinter.filedialog import asksaveasfilename from tkinter.filedialog import asksaveasfilename
result = asksaveasfilename(**options) result = asksaveasfilename(**options)
return result return result
@ -3802,6 +3795,8 @@ def show_gui():
admin_dir_var = ctk.StringVar() admin_dir_var = ctk.StringVar()
admin_password_var = ctk.StringVar() admin_password_var = ctk.StringVar()
nozenity_var = ctk.IntVar(value=0)
curr_tab_idx = 0 curr_tab_idx = 0
def tabbuttonaction(name): def tabbuttonaction(name):
@ -4439,6 +4434,12 @@ def show_gui():
ctk.CTkButton(extra_tab , text = "Generate LaunchTemplate", command = kcpp_export_template ).grid(row=5,column=0, stick="w", padx= 8, pady=2) ctk.CTkButton(extra_tab , text = "Generate LaunchTemplate", command = kcpp_export_template ).grid(row=5,column=0, stick="w", padx= 8, pady=2)
makelabel(extra_tab, "Analyze GGUF Metadata", 6, 0,tooltiptxt="Reads the metadata, weight types and tensor names in any GGUF file.") makelabel(extra_tab, "Analyze GGUF Metadata", 6, 0,tooltiptxt="Reads the metadata, weight types and tensor names in any GGUF file.")
ctk.CTkButton(extra_tab , text = "Analyze GGUF", command = analyze_gguf_model_wrapper ).grid(row=7,column=0, stick="w", padx= 8, pady=2) ctk.CTkButton(extra_tab , text = "Analyze GGUF", command = analyze_gguf_model_wrapper ).grid(row=7,column=0, stick="w", padx= 8, pady=2)
if sys.platform == "linux":
def togglezenity(a,b,c):
global zenity_permitted
zenity_permitted = (nozenity_var.get()==0)
makecheckbox(extra_tab, "Use Classic FilePicker", nozenity_var, 20, tooltiptxt="Use the classic TKinter file picker instead.")
nozenity_var.trace("w", togglezenity)
# launch # launch
def guilaunch(): def guilaunch():