Repository navigation
Expand file tree
/
Copy pathitems_file.py
More file actions
166 lines (137 loc) · 6.14 KB
/
Copy pathitems_file.py
File metadata and controls
166 lines (137 loc) · 6.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""عناصر خاصة يضيفها المستخدم إلى قائمة الزر الأيمن: imports\\ui-items.nss.
المصدر هو items.json في AppData، ومنه يُولَّد ملف nss كاملًا عند كل حفظ.
كل عنصر واحد من: item (أمر أو برنامج)، sep (فاصل)، menu (قائمة فرعية فيها عناصر).
© 2026 Ali Alhumedi - MIT License
"""
import json
import os
import re
import shutil
import time
import theme_file
from theme_file import AppError
ITEMS_FILE = os.path.join(theme_file.shell_dir(), "imports", "ui-items.nss")
DATA_FILE = os.path.join(theme_file.DATA_DIR, "items.json")
IMPORT_LINE = "import 'imports/ui-items.nss'"
HEADER = "// Generated by Nilesoft Shell UI from items.json - edits here are overwritten on save"
# أين يظهر العنصر: القيمة هي type في Shell
WHERE = {"all": None, "file": "file", "dir": "dir", "folder": "dir|back", "back": "back", "desktop": "desktop"}
# أيقونات Shell المرسومة تُكتب كما هي دون علامات تنصيص: أو icon.copy أو [, #22A7F2]
RAW_IMAGE = re.compile(r"^(\\u[0-9A-Fa-f]{4}|icon\.[a-z_]+|\[\s*\\u[0-9A-Fa-f]{4}\s*(,\s*#[0-9A-Fa-f]{6}\s*)?\])$")
def _image(value, label):
s = str(value or "").strip()
return s if RAW_IMAGE.match(s) else _q(s, label)
def is_linked():
try:
with open(os.path.join(theme_file.shell_dir(), "shell.nss"), encoding="utf-8-sig") as f:
return IMPORT_LINE in f.read()
except OSError:
return False
def load():
try:
with open(DATA_FILE, encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
return []
def _q(value, label):
"""نص بين علامتي تنصيص مفردة؛ Shell لا يقبل ' داخلها."""
s = str(value or "").strip()
if "'" in s or "\n" in s or "\r" in s:
raise AppError(f"لا يمكن استعمال علامة ' في «{label}»: {s}",
f"The ' character can't be used in “{label}”: {s}")
return "'" + s + "'"
def _exts(text):
out = []
for e in re.split(r"[\s,;|]+", str(text or "")):
e = e.strip().lower()
if not e:
continue
if not re.fullmatch(r"\.?[a-z0-9_]+", e):
raise AppError(f"امتداد غير صالح: {e}", f"Invalid extension: {e}")
out.append(e if e.startswith(".") else "." + e)
return out
def _common(it, label):
"""الخصائص المشتركة: المكان والامتدادات وShift."""
parts = []
where = it.get("where", "all")
if where not in WHERE:
raise AppError(f"مكان غير معروف: {where}", f"Unknown place: {where}")
if WHERE[where]:
parts.append(f"type={_q(WHERE[where], label)}")
conds = []
exts = _exts(it.get("exts"))
if exts:
conds.append("str.equals(sel.file.ext, [" + ", ".join(f'"{e}"' for e in exts) + "])")
if it.get("shift"):
conds.append("key.shift()")
if conds:
parts.append("where=" + " && ".join(conds))
if it.get("top"):
parts.append("pos='top'")
return parts
def _item(it, pad):
title = str(it.get("title", "")).strip()
if not title:
raise AppError("لكل عنصر اسم يظهر في القائمة.", "Every item needs a title.")
cmd = str(it.get("cmd", "")).strip()
if not cmd:
raise AppError(f"العنصر «{title}» بلا أمر.", f"Item “{title}” has no command.")
parts = [f"title={_q(title, title)}"] + _common(it, title)
image = str(it.get("image", "")).strip() or (cmd if cmd.lower().endswith(".exe") else "")
if image:
parts.append(f"image={_image(image, title)}")
parts.append(f"cmd={_q(cmd, title)}")
args = str(it.get("args", "")).strip()
if it.get("passPath"):
args = (args + ' "@sel.path"').strip()
if args:
parts.append(f"args={_q(args, title)}")
if it.get("admin"):
parts.append("admin=1")
return f"{pad}item(" + " ".join(parts) + ")"
def _node(it, depth):
pad = "\t" * depth
kind = it.get("type", "item")
if kind == "sep":
return [f"{pad}separator"]
if kind == "item":
return [_item(it, pad)]
if kind == "menu":
title = str(it.get("title", "")).strip()
if not title:
raise AppError("للقائمة الفرعية اسم.", "A submenu needs a title.")
mode = it.get("mode", "multiple")
if mode not in ("single", "multiple"):
raise AppError(f"وضع غير معروف: {mode}", f"Unknown mode: {mode}")
parts = [f'mode="{mode}"', f"title={_q(title, title)}"] + _common(it, title)
if str(it.get("image", "")).strip():
parts.append(f"image={_image(it['image'], title)}")
lines = [f"{pad}menu(" + " ".join(parts) + ")", pad + "{"]
for child in it.get("children", []):
lines += _node(child, depth + 1)
return lines + [pad + "}"]
raise AppError(f"نوع غير معروف: {kind}", f"Unknown type: {kind}")
def _shown(items):
"""العناصر المخفية تبقى في items.json ولا تُكتب في ملف Shell."""
return [dict(it, children=_shown(it["children"])) if it.get("children") else it
for it in items if not it.get("hidden")]
def build(items):
lines = [HEADER]
for it in _shown(items):
lines += _node(it, 0)
return "\n".join(lines) + "\n"
def save(items):
text = build(items) # يتحقق من كل شيء قبل أن نلمس أي ملف
os.makedirs(theme_file.BACKUP_DIR, exist_ok=True)
if os.path.exists(DATA_FILE):
stamp = time.strftime("%Y%m%d-%H%M%S")
shutil.copy2(DATA_FILE, os.path.join(theme_file.BACKUP_DIR, f"items-{stamp}.json"))
try:
with open(ITEMS_FILE, "w", encoding="utf-8-sig", newline="\r\n") as f:
f.write(text)
except PermissionError:
raise AppError("لا توجد صلاحية كتابة على ملف العناصر: " + ITEMS_FILE,
"No write permission on the items file: " + ITEMS_FILE)
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(items, f, ensure_ascii=False, indent=1)
return items