11 Commits

Author SHA1 Message Date
Bruce
9ba3b875da Update special thanks. 2026-04-09 14:10:57 +08:00
Bruce
9ae2e886bd Update special thanks. 2026-04-09 14:09:58 +08:00
Bruce
0926da3f27 Update license. 2026-04-09 13:34:09 +08:00
Bruce
4355ce4d13 Update help text. 2026-04-09 12:57:35 +08:00
Bruce
90d16151f4 pkgcli: add the confirm before remove. 2026-04-09 12:30:14 +08:00
Bruce
4bddb96052 Pkgcli: add the confirm before install. 2026-04-09 12:29:46 +08:00
Bruce
368efeb2f0 Update pkgcli. 2026-04-09 12:07:44 +08:00
Bruce
8e8a0453c4 Update PkgCLI. 2026-04-08 23:42:55 +08:00
Bruce
e58b47926c Canceled the settings of console input encoding. 2026-04-08 23:39:09 +08:00
Bruce
6d40668c1a Update version. 2026-04-08 23:35:14 +08:00
Bruce
71c8d76593 Fix bugs.
Update PkgCLI.
2026-04-08 23:32:11 +08:00
20 changed files with 3680 additions and 54 deletions

View File

@@ -348,8 +348,18 @@ namespace AppxPackage
{
get
{
string value;
if (!TryGetValue (key, out value))
string value = null;
var isfind = false;
foreach (var kv in this)
{
if (kv.Key?.Trim ()?.ToLowerInvariant () == key?.Trim ()?.ToLowerInvariant ())
{
value = kv.Value;
isfind = true;
break;
}
}
if (!isfind)
{
value = string.Empty;
base [key] = value;
@@ -370,8 +380,18 @@ namespace AppxPackage
}
public string At (string key)
{
string value;
if (!TryGetValue (key, out value)) throw new KeyNotFoundException ($"PRBaseApplication.At: key \"{key}\" not found");
string value = null;
var isfind = false;
foreach (var kv in this)
{
if (kv.Key?.Trim ()?.ToLowerInvariant () == key?.Trim ()?.ToLowerInvariant ())
{
value = kv.Value;
isfind = true;
break;
}
}
if (!isfind) throw new KeyNotFoundException ($"MRApplication: cannot find key \"{key}\"");
if (!EnablePri ()) return value;
if (PriFileHelper.IsMsResourcePrefix (value))
{
@@ -383,8 +403,18 @@ namespace AppxPackage
}
public string NewAt (string key, bool toPriString)
{
string value;
if (!TryGetValue (key, out value))
string value = null;
var isfind = false;
foreach (var kv in this)
{
if (kv.Key?.Trim ()?.ToLowerInvariant () == key?.Trim ()?.ToLowerInvariant ())
{
value = kv.Value;
isfind = true;
break;
}
}
if (!isfind)
{
value = string.Empty;
base [key] = value;

View File

@@ -741,8 +741,18 @@ namespace AppxPackage
{
get
{
string value;
if (!TryGetValue (key, out value))
string value = null;
var isfind = false;
foreach (var kv in this)
{
if (kv.Key?.Trim ()?.ToLowerInvariant () == key?.Trim ()?.ToLowerInvariant ())
{
value = kv.Value;
isfind = true;
break;
}
}
if (!isfind)
{
value = string.Empty;
base [key] = value;
@@ -763,8 +773,18 @@ namespace AppxPackage
}
public string At (string key)
{
string value;
if (!TryGetValue (key, out value)) throw new KeyNotFoundException ($"PRBaseApplication.At: key \"{key}\" not found");
string value = null;
var isfind = false;
foreach (var kv in this)
{
if (kv.Key?.Trim ()?.ToLowerInvariant () == key?.Trim ()?.ToLowerInvariant ())
{
value = kv.Value;
isfind = true;
break;
}
}
if (!isfind) throw new KeyNotFoundException ($"MRApplication: cannot find key \"{key}\"");
if (!EnablePri ()) return value;
if (PriFileHelper.IsMsResourcePrefix (value))
{
@@ -776,8 +796,18 @@ namespace AppxPackage
}
public string NewAt (string key, bool toPriString)
{
string value;
if (!TryGetValue (key, out value))
string value = null;
var isfind = false;
foreach (var kv in this)
{
if (kv.Key?.Trim ()?.ToLowerInvariant () == key?.Trim ()?.ToLowerInvariant ())
{
value = kv.Value;
isfind = true;
break;
}
}
if (!isfind)
{
value = string.Empty;
base [key] = value;
@@ -1780,6 +1810,753 @@ namespace AppxPackage
UsePri = parsePri;
}
}
public bool SaveJsonFileCS (string savefilepath)
{
try
{
#region
using (var fs = File.Create (savefilepath))
{
using (var zos = new ZipOutputStream (fs))
{
zos.SetLevel (9);
bool parsePri = UsePri;
bool usePri = EnablePri;
try
{
UsePri = false;
EnablePri = false;
object packageInfo = null;
#region file
var typestr = "unknown";
switch (Type)
{
case PackageType.Appx: typestr = "appx"; break;
case PackageType.Bundle: typestr = "bundle"; break;
default:
case PackageType.Unknown: typestr = "unknown"; break;
}
var rolestr = "unknown";
switch (Role)
{
case PackageRole.Application: rolestr = "application"; break;
case PackageRole.Framework: rolestr = "framework"; break;
case PackageRole.Resource: rolestr = "resource"; break;
default:
case PackageRole.Unknown: rolestr = "unknown"; break;
}
var pkgfile = new {
path = FilePath,
valid = IsValid,
type = typestr,
role = rolestr
};
#endregion
#region id
var id = Identity;
var pkgid = new {
name = id.Name,
publisher = id.Publisher,
version = id.Version.ToString (),
realVersion = id.RealVersion.ToString (),
architecture = id.ProcessArchitecture.Select (e => {
switch (e)
{
case Architecture.ARM: return "arm";
case Architecture.ARM64: return "arm64";
case Architecture.Neutral: return "neutral";
case Architecture.x64: return "x64";
case Architecture.x86: return "x86";
default:
case Architecture.Unknown: return "unknown";
}
}).ToList (),
familyName = id.FamilyName,
fullName = id.FullName,
resourceId = id.ResourceId
};
#endregion
#region prerequistes
var preq = Prerequisites;
var pkgpreq = new {
osMinVersion = preq.OSMinVersion.ToString (),
osMaxVersionTested = preq.OSMaxVersionTested.ToString (),
osMinVersionDescription = preq.OSMinVersionDescription,
osMaxVersionTestedDescription = preq.OSMaxVersionDescription
};
#endregion
#region resources
var res = Resources;
var pkgres = new {
languages = res.Languages,
scales = res.Scales,
dxFeatureLevels = res.DXFeatures.Select (d => {
switch (d)
{
case DXFeatureLevel.Level9: return 9;
case DXFeatureLevel.Level10: return 10;
case DXFeatureLevel.Level11: return 11;
case DXFeatureLevel.Level12: return 12;
default:
case DXFeatureLevel.Unspecified: return -1;
}
}).ToList ()
};
#endregion
#region capabilities
var caps = Capabilities;
var pkgcaps = new {
capabilities = caps.Capabilities,
deviceCapabilities = caps.DeviceCapabilities
};
#endregion
#region dependencies
var deps = Dependencies;
var pkgdeps = Dependencies.Select (d => new {
name = d.Name,
publisher = d.Publisher,
minVersion = d.Version.ToString ()
}).ToList ();
#endregion
using (var priAllRes = new PriAllValuesReader (this))
{
priAllRes.Init ();
#region prop
var prop = Properties;
var dispname = prop.DisplayName;
var dispNameDict = new Dictionary<string, string> ();
if (PriFileHelper.IsMsResourcePrefix (dispname))
dispNameDict = priAllRes.LocaleResourceAllValues (dispname);
dispNameDict ["root"] = dispname;
var desc = prop.Description;
var descDict = new Dictionary<string, string> ();
if (PriFileHelper.IsMsResourcePrefix (desc))
descDict = priAllRes.LocaleResourceAllValues (desc);
descDict ["root"] = desc;
var disppub = prop.Publisher;
var dispPubDict = new Dictionary<string, string> ();
if (PriFileHelper.IsMsResourcePrefix (disppub))
dispPubDict = priAllRes.LocaleResourceAllValues (disppub);
dispPubDict ["root"] = disppub;
var logoList = priAllRes.FileResourceAllValues (prop.Logo, zos)
.Select (kv => {
string contrast = "";
switch (kv.Key.Contrast)
{
case PriResourceKey.PriContrast.None: contrast = ""; break;
case PriResourceKey.PriContrast.Black: contrast = "black"; break;
case PriResourceKey.PriContrast.White: contrast = "white"; break;
case PriResourceKey.PriContrast.High: contrast = "high"; break;
case PriResourceKey.PriContrast.Low: contrast = "low"; break;
}
if (kv.Key.IsTargetSize)
{
return new {
targetSize = kv.Key.Value,
contrast = contrast,
name = kv.Value
};
}
else if (kv.Key.IsScale)
{
return new {
scale = kv.Key.Value,
contrast = contrast,
name = kv.Value
};
}
else if (kv.Key.IsString)
{
return new {
language = kv.Key.Value,
name = kv.Value
};
}
else
{
return (dynamic)null; // 不满足条件时返回 null
}
})
.Where (item => item != null) // 过滤掉 null
.ToList ();
var pkgprop = new {
displayName = dispNameDict,
publisherDisplayName = dispPubDict,
description = descDict,
logo = logoList,
framework = prop.Framework,
resourcePackage = prop.ResourcePackage
};
#endregion
#region apps
var apps = Applications;
var pkgapps = new List<object> ();
foreach (var app in apps)
{
dynamic obj = new ExpandoObject ();
var dict = (IDictionary<string, object>)obj;
foreach (var kv in app)
{
if (Utils.AppFileProperties.Contains (kv.Key, StringComparer.OrdinalIgnoreCase))
{
dict [Utils.PascalToCamel (kv.Key)] = priAllRes.FileResourceAllValues (kv.Value, zos)
.Select (skv => {
string contrast = "";
switch (skv.Key.Contrast)
{
case PriResourceKey.PriContrast.None: contrast = ""; break;
case PriResourceKey.PriContrast.Black: contrast = "black"; break;
case PriResourceKey.PriContrast.White: contrast = "white"; break;
case PriResourceKey.PriContrast.High: contrast = "high"; break;
case PriResourceKey.PriContrast.Low: contrast = "low"; break;
}
if (skv.Key.IsTargetSize)
{
return new {
targetSize = skv.Key.Value,
contrast = contrast,
name = skv.Value
};
}
else if (skv.Key.IsScale)
{
return new {
scale = skv.Key.Value,
contrast = contrast,
name = skv.Value
};
}
else if (skv.Key.IsString)
{
return new {
language = skv.Key.Value,
name = skv.Value
};
}
else
{
return (dynamic)null; // 不满足条件时返回 null
}
}).Where (item => item != null).ToList ();
}
else
{
if (PriFileHelper.IsMsResourcePrefix (kv.Value))
{
var itemDict = new Dictionary<string, string> ();
itemDict = priAllRes.LocaleResourceAllValues (kv.Value);
itemDict ["root"] = kv.Value;
dict [Utils.PascalToCamel (kv.Key)] = itemDict;
}
else
{
dict [Utils.PascalToCamel (kv.Key)] = kv.Value;
}
}
}
pkgapps.Add (obj);
}
#endregion
packageInfo = new {
file = pkgfile,
identity = pkgid,
properties = pkgprop,
resources = pkgres,
prerequisites = pkgpreq,
applications = pkgapps,
capabilities = pkgcaps,
dependencies = pkgdeps
};
}
var jsonstr = Newtonsoft.Json.JsonConvert.SerializeObject (packageInfo, Newtonsoft.Json.Formatting.None);
var ze = new ZipEntry ("info.json");
ze.DateTime = DateTime.Now;
zos.PutNextEntry (ze);
var bytes = Encoding.UTF8.GetBytes (jsonstr);
zos.Write (bytes, 0, bytes.Length);
zos.CloseEntry ();
return true;
}
finally
{
EnablePri = usePri;
UsePri = parsePri;
}
}
}
#endregion
}
catch (Exception ex)
{
throw ex;
return false;
}
}
public bool SaveXmlFileCS (string savefilepath)
{
try
{
#region
using (var fs = File.Create (savefilepath))
{
using (var zos = new ZipOutputStream (fs))
{
zos.SetLevel (9);
bool parsePri = UsePri;
bool usePri = EnablePri;
try
{
UsePri = false;
EnablePri = false;
var xml = new XmlDocument ();
var decl = xml.CreateXmlDeclaration ("1.0", "utf-8", "yes");
xml.AppendChild (decl);
var root = xml.CreateElement ("Package");
xml.AppendChild (root);
#region file
var typestr = "unknown";
switch (Type)
{
case PackageType.Appx: typestr = "appx"; break;
case PackageType.Bundle: typestr = "bundle"; break;
default:
case PackageType.Unknown: typestr = "unknown"; break;
}
var rolestr = "unknown";
switch (Role)
{
case PackageRole.Application: rolestr = "application"; break;
case PackageRole.Framework: rolestr = "framework"; break;
case PackageRole.Resource: rolestr = "resource"; break;
default:
case PackageRole.Unknown: rolestr = "unknown"; break;
}
{
var nodefile = xml.CreateElement ("File");
var nodefilepath = xml.CreateElement ("Path");
nodefilepath.InnerText = FilePath;
var nodefilevalid = xml.CreateElement ("Valid");
nodefilevalid.InnerText = IsValid ? "true" : "false";
var nodefiletype = xml.CreateElement ("Type");
nodefiletype.InnerText = typestr;
var nodefilerole = xml.CreateElement ("Role");
nodefilerole.InnerText = rolestr;
nodefile.AppendChild (nodefilepath);
nodefile.AppendChild (nodefilevalid);
nodefile.AppendChild (nodefiletype);
nodefile.AppendChild (nodefilerole);
root.AppendChild (nodefile);
}
#endregion
#region id
var id = Identity;
{
var nodeid = xml.CreateElement ("Identity");
var nodeidname = xml.CreateElement ("Name");
nodeidname.InnerText = id.Name;
var nodeidpub = xml.CreateElement ("Publisher");
nodeidpub.InnerText = id.Publisher;
var nodeidver = xml.CreateElement ("Version");
nodeidver.InnerText = id.Version.ToString ();
var nodeidrealver = xml.CreateElement ("RealVersion");
nodeidrealver.InnerText = id.RealVersion.ToString ();
var nodeidarchs = xml.CreateElement ("ProcessorArchitectures");
foreach (var a in id.ProcessArchitecture)
{
var astr = "";
switch (a)
{
case Architecture.ARM: astr = "arm"; break;
case Architecture.ARM64: astr = "arm64"; break;
case Architecture.Neutral: astr = "neutral"; break;
case Architecture.x64: astr = "x64"; break;
case Architecture.x86: astr = "x86"; break;
default:
case Architecture.Unknown: astr = "unknown"; break;
}
var nodeidarch = xml.CreateElement ("ProcessorArchitecture");
nodeidarch.SetAttribute ("Value", astr);
nodeidarchs.AppendChild (nodeidarch);
}
var nodeidfamily = xml.CreateElement ("FamilyName");
nodeidfamily.InnerText = id.FamilyName;
var nodeidfull = xml.CreateElement ("FullName");
nodeidfull.InnerText = id.FullName;
var nodeidresid = xml.CreateElement ("ResourceId");
nodeidresid.InnerText = id.ResourceId;
nodeid.AppendChild (nodeidname);
nodeid.AppendChild (nodeidpub);
nodeid.AppendChild (nodeidver);
nodeid.AppendChild (nodeidrealver);
nodeid.AppendChild (nodeidarchs);
nodeid.AppendChild (nodeidfamily);
nodeid.AppendChild (nodeidfamily);
nodeid.AppendChild (nodeidresid);
root.AppendChild (nodeid);
}
#endregion
using (var priAllRes = new PriAllValuesReader (this))
{
priAllRes.Init ();
#region prop
var prop = Properties;
var dispname = prop.DisplayName;
var dispNameDict = new Dictionary<string, string> ();
if (PriFileHelper.IsMsResourcePrefix (dispname))
dispNameDict = priAllRes.LocaleResourceAllValues (dispname);
dispNameDict ["root"] = dispname;
var desc = prop.Description;
var descDict = new Dictionary<string, string> ();
if (PriFileHelper.IsMsResourcePrefix (desc))
descDict = priAllRes.LocaleResourceAllValues (desc);
descDict ["root"] = desc;
var disppub = prop.Publisher;
var dispPubDict = new Dictionary<string, string> ();
if (PriFileHelper.IsMsResourcePrefix (disppub))
dispPubDict = priAllRes.LocaleResourceAllValues (disppub);
dispPubDict ["root"] = disppub;
{
var nodeprop = xml.CreateElement ("Properties");
var nodepropname = xml.CreateElement ("DisplayName");
foreach (var kv in dispNameDict)
{
var nodelocale = xml.CreateElement ("LocaleResource");
nodelocale.SetAttribute ("Lang", kv.Key);
nodelocale.InnerText = kv.Value;
nodepropname.AppendChild (nodelocale);
}
var nodeproppub = xml.CreateElement ("PublisherDisplayName");
foreach (var kv in dispPubDict)
{
var nodelocale = xml.CreateElement ("LocaleResource");
nodelocale.SetAttribute ("Lang", kv.Key);
nodelocale.InnerText = kv.Value;
nodeproppub.AppendChild (nodelocale);
}
var nodepropdesc = xml.CreateElement ("Description");
foreach (var kv in descDict)
{
var nodelocale = xml.CreateElement ("LocaleResource");
nodelocale.SetAttribute ("Lang", kv.Key);
nodelocale.InnerText = kv.Value;
nodepropdesc.AppendChild (nodelocale);
}
var nodeproplogo = xml.CreateElement ("Logo");
foreach (var kv in priAllRes.FileResourceAllValues (prop.Logo, zos))
{
#region logo
var key = kv.Key;
var value = kv.Value;
var nodefile = xml.CreateElement ("File");
var attrName = xml.CreateAttribute ("Name");
attrName.Value = value;
nodefile.Attributes.Append (attrName);
if (key.Contrast != PriResourceKey.PriContrast.None)
{
string contrast = "";
switch (key.Contrast)
{
case PriResourceKey.PriContrast.Black: contrast = "black"; break;
case PriResourceKey.PriContrast.White: contrast = "white"; break;
case PriResourceKey.PriContrast.High: contrast = "high"; break;
case PriResourceKey.PriContrast.Low: contrast = "low"; break;
}
var attrContrast = xml.CreateAttribute ("Contrast");
attrContrast.Value = contrast;
nodefile.Attributes.Append (attrContrast);
}
if (key.IsTargetSize)
{
var attr = xml.CreateAttribute ("TargetSize");
attr.Value = key.Value.ToString ();
nodefile.Attributes.Append (attr);
}
else if (key.IsScale)
{
var attr = xml.CreateAttribute ("Scale");
attr.Value = key.Value.ToString ();
nodefile.Attributes.Append (attr);
}
else if (key.IsString)
{
var attr = xml.CreateAttribute ("Language");
attr.Value = key.Value.ToString ();
nodefile.Attributes.Append (attr);
}
nodeproplogo.AppendChild (nodefile);
#endregion
}
var nodepropfrw = xml.CreateElement ("Framework");
nodepropfrw.InnerText = prop.Framework ? "true" : "false";
var nodepropres = xml.CreateElement ("ResourcePackage");
nodepropres.InnerText = prop.ResourcePackage ? "true" : "false";
nodeprop.AppendChild (nodepropname);
nodeprop.AppendChild (nodeproppub);
nodeprop.AppendChild (nodepropdesc);
nodeprop.AppendChild (nodeproplogo);
nodeprop.AppendChild (nodepropfrw);
nodeprop.AppendChild (nodepropres);
root.AppendChild (nodeprop);
}
#endregion
#region apps
// Applications 节点
XmlElement nodeApplications = xml.CreateElement ("Applications");
foreach (var app in Applications)
{
XmlElement nodeApp = xml.CreateElement ("Application");
// AppUserModelId 作为属性
string aumidObj = app ["AppUserModelId"];
if (aumidObj == null || aumidObj.Trim ().Length == 0) aumidObj = app ["AppUserModelID"];
nodeApp.SetAttribute ("AppUserModelId", aumidObj);
foreach (var kv in app)
{
string key = kv.Key;
string value = kv.Value;
// 跳过 AppUserModelId因为已经作为属性
if (string.Equals (key, "AppUserModelId", StringComparison.OrdinalIgnoreCase))
continue;
XmlElement nodeProp = xml.CreateElement (key);
// 文件资源类型
if (Utils.AppFileProperties.Contains (key, StringComparer.OrdinalIgnoreCase))
{
foreach (var skv in priAllRes.FileResourceAllValues (value, zos))
{
var fileKey = skv.Key;
var fileValue = skv.Value;
XmlElement nodeFile = xml.CreateElement ("File");
// Name 必有
XmlAttribute attrName = xml.CreateAttribute ("Name");
attrName.Value = fileValue;
nodeFile.Attributes.Append (attrName);
// Contrast 可选
if (fileKey.Contrast != PriResourceKey.PriContrast.None)
{
string contrast = "";
switch (fileKey.Contrast)
{
case PriResourceKey.PriContrast.Black: contrast = "black"; break;
case PriResourceKey.PriContrast.White: contrast = "white"; break;
case PriResourceKey.PriContrast.High: contrast = "high"; break;
case PriResourceKey.PriContrast.Low: contrast = "low"; break;
}
if (!string.IsNullOrEmpty (contrast))
{
XmlAttribute attrContrast = xml.CreateAttribute ("Contrast");
attrContrast.Value = contrast;
nodeFile.Attributes.Append (attrContrast);
}
}
// TargetSize
if (fileKey.IsTargetSize)
{
XmlAttribute attrTS = xml.CreateAttribute ("TargetSize");
attrTS.Value = fileKey.Value.ToString ();
nodeFile.Attributes.Append (attrTS);
}
// Scale
else if (fileKey.IsScale)
{
XmlAttribute attrS = xml.CreateAttribute ("Scale");
attrS.Value = fileKey.Value.ToString ();
nodeFile.Attributes.Append (attrS);
}
// Language
else if (fileKey.IsString)
{
XmlAttribute attrL = xml.CreateAttribute ("Lang");
attrL.Value = fileKey.Value.ToString ();
nodeFile.Attributes.Append (attrL);
}
nodeProp.AppendChild (nodeFile);
}
}
// 多语言资源
else if (PriFileHelper.IsMsResourcePrefix (value))
{
Dictionary<string, string> localeDict = priAllRes.LocaleResourceAllValues (value);
localeDict ["root"] = value.ToString ();
foreach (KeyValuePair<string, string> lkv in localeDict)
{
XmlElement nodeLocale = xml.CreateElement ("LocaleResource");
nodeLocale.SetAttribute ("Lang", lkv.Key);
nodeLocale.InnerText = lkv.Value;
nodeProp.AppendChild (nodeLocale);
}
}
else
{
nodeProp.InnerText = value.ToString ();
}
nodeApp.AppendChild (nodeProp);
}
nodeApplications.AppendChild (nodeApp);
}
root.AppendChild (nodeApplications);
#endregion
}
#region prerequistes
var preq = Prerequisites;
{
var nodepreq = xml.CreateElement ("Prerequisites");
var nodeosmin = xml.CreateElement ("OSMinVersion");
nodeosmin.InnerText = preq.OSMinVersion.ToString ();
nodeosmin.SetAttribute ("Description", preq.OSMinVersionDescription);
var nodeosmaxt = xml.CreateElement ("OSMaxVersionTested");
nodeosmaxt.InnerText = preq.OSMaxVersionTested.ToString ();
nodeosmaxt.SetAttribute ("Description", preq.OSMaxVersionDescription);
nodepreq.AppendChild (nodeosmin);
nodepreq.AppendChild (nodeosmaxt);
root.AppendChild (nodepreq);
}
#endregion
#region resources
XmlElement nodeResources = xml.CreateElement ("Resources");
var res = Resources;
if (res.Languages != null)
{
foreach (var lang in res.Languages)
{
XmlElement nodeRes = xml.CreateElement ("Resource");
XmlAttribute attrLang = xml.CreateAttribute ("Language");
attrLang.Value = lang;
nodeRes.Attributes.Append (attrLang);
nodeResources.AppendChild (nodeRes);
}
}
if (res.Scales != null)
{
foreach (var scale in res.Scales)
{
XmlElement nodeRes = xml.CreateElement ("Resource");
XmlAttribute attrScale = xml.CreateAttribute ("Scale");
attrScale.Value = scale.ToString ();
nodeRes.Attributes.Append (attrScale);
nodeResources.AppendChild (nodeRes);
}
}
if (res.DXFeatures != null)
{
foreach (var d in res.DXFeatures)
{
int level = -1;
switch (d)
{
case DXFeatureLevel.Level9: level = 9; break;
case DXFeatureLevel.Level10: level = 10; break;
case DXFeatureLevel.Level11: level = 11; break;
case DXFeatureLevel.Level12: level = 12; break;
case DXFeatureLevel.Unspecified:
default: level = -1; break;
}
XmlElement nodeRes = xml.CreateElement ("Resource");
XmlAttribute attrDX = xml.CreateAttribute ("DXFeatureLevel");
attrDX.Value = level.ToString ();
nodeRes.Attributes.Append (attrDX);
nodeResources.AppendChild (nodeRes);
}
}
root.AppendChild (nodeResources);
#endregion
#region capabilities
XmlElement nodeCapabilities = xml.CreateElement ("Capabilities");
var caps = Capabilities;
if (caps.Capabilities != null)
{
foreach (var cap in caps.Capabilities)
{
XmlElement nodeCap = xml.CreateElement ("Capability");
XmlAttribute attrName = xml.CreateAttribute ("Name");
attrName.Value = cap;
nodeCap.Attributes.Append (attrName);
nodeCapabilities.AppendChild (nodeCap);
}
}
if (caps.DeviceCapabilities != null)
{
foreach (var devCap in caps.DeviceCapabilities)
{
XmlElement nodeDevCap = xml.CreateElement ("DeviceCapability");
XmlAttribute attrName = xml.CreateAttribute ("Name");
attrName.Value = devCap;
nodeDevCap.Attributes.Append (attrName);
nodeCapabilities.AppendChild (nodeDevCap);
}
}
root.AppendChild (nodeCapabilities);
#endregion
#region dependencies
XmlElement nodeDependencies = xml.CreateElement ("Dependencies");
var deps = Dependencies;
if (deps != null)
{
foreach (var dep in deps)
{
XmlElement nodeDep = xml.CreateElement ("Dependency");
XmlAttribute attrName = xml.CreateAttribute ("Name");
attrName.Value = dep.Name ?? "";
nodeDep.Attributes.Append (attrName);
XmlAttribute attrPublisher = xml.CreateAttribute ("Publisher");
attrPublisher.Value = dep.Publisher ?? "";
nodeDep.Attributes.Append (attrPublisher);
XmlAttribute attrMinVersion = xml.CreateAttribute ("MinVersion");
attrMinVersion.Value = dep.Version != null ? dep.Version.ToString () : "";
nodeDep.Attributes.Append (attrMinVersion);
nodeDependencies.AppendChild (nodeDep);
}
}
root.AppendChild (nodeDependencies);
#endregion
var ze = new ZipEntry ("info.xml");
ze.DateTime = DateTime.Now;
zos.PutNextEntry (ze);
byte [] bytes;
using (var ms = new MemoryStream ())
{
var settings = new XmlWriterSettings {
Encoding = Encoding.UTF8,
Indent = true,
OmitXmlDeclaration = false
};
using (var writer = XmlWriter.Create (ms, settings))
{
xml.Save (writer);
}
bytes = ms.ToArray ();
}
zos.Write (bytes, 0, bytes.Length);
zos.CloseEntry ();
return true;
}
finally
{
EnablePri = usePri;
UsePri = parsePri;
}
}
}
#endregion
}
catch (Exception ex)
{
throw ex;
return false;
}
}
public void SaveJsonFile (string savefilepath, object resolve, object reject)
{
try
@@ -2060,7 +2837,7 @@ namespace AppxPackage
}
catch (Exception ex)
{
if (reject != null) JSHelper.CallJS (reject, ex);
if (reject != null) JSHelper.CallJS (reject, new DataUtils._I_Exception (ex));
}
}
public void SaveJsonFileAsync (string savefilepath, object resolve, object reject)
@@ -2531,7 +3308,7 @@ namespace AppxPackage
}
catch (Exception ex)
{
if (reject != null) JSHelper.CallJS (reject, ex);
if (reject != null) JSHelper.CallJS (reject, new DataUtils._I_Exception (ex));
}
}
public void SaveXmlFileAsync (string savefilepath, object resolve, object reject)

215
LICENSE
View File

@@ -1,21 +1,202 @@
MIT License
Copyright (c) 2025 Windows Modern
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
1. Definitions.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

13
NOTICE.TXT Normal file
View File

@@ -0,0 +1,13 @@
Copyright (c) 2025-2026 Windows Modern
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

230
PkgCLI/CliParsing.cs Normal file
View File

@@ -0,0 +1,230 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PkgCLI
{
public class NormalizeStringComparer: IEqualityComparer<string>
{
public bool Equals (string x, string y) => Polyfill.NEquals (x, y);
public int GetHashCode (string obj) => obj.NNormalize ().GetHashCode ();
}
public class NormalizeCharacterComparer: IEqualityComparer<char>
{
public bool Equals (char x, char y) => char.ToLowerInvariant (x) == char.ToLowerInvariant (y);
public int GetHashCode (char obj) => char.ToLowerInvariant (obj).GetHashCode ();
}
public class StringNSet: HashSet<string>
{
public StringNSet () : base (new NormalizeStringComparer ()) { }
public StringNSet (IEnumerable<string> list) : base (list, new NormalizeStringComparer ()) { }
}
public class CharNSet: HashSet<char>
{
public CharNSet () : base (new NormalizeCharacterComparer ()) { }
public CharNSet (IEnumerable<char> list) : base (list, new NormalizeCharacterComparer ()) { }
}
public static class CliParsingConst
{
public static readonly char [] defaultPrefixs = new char [] { '/', '-' };
public static readonly char [] defaultPostfixs = new char [] { '=', ':' };
public static readonly string [] emptyStringArray = new string [] { };
}
public class CmdParamName: IEquatable<CmdParamName>, IComparable<CmdParamName>, IDisposable
{
private string _id = "";
private string _name = "";
/// <summary>
/// 命令唯一标识,但不作为命令名,仅用于内部识别。命令 ID 可以作为命令名或别名。
/// </summary>
public string Id { get { return _id.NNormalize (); } set { _id = value; } }
/// <summary>
/// 命令名,唯一。命令名不能与别名重复。首字符不能为前缀中的字符,尾字符不能为后缀中的字符。
/// </summary>
public string Name { get { return _name.NNormalize (); } set { _name = value; } }
/// <summary>
/// 命令别名,唯一。不能与命令名重复。首字符不能为前缀中的字符,尾字符不能为后缀中的字符。
/// </summary>
/// </summary>
public StringNSet Aliases { get; private set; } = new StringNSet ();
/// <summary>
/// 命令前缀,为一个字符,标点符号。不能为命令名或别名的首字符。
/// </summary>
public CharNSet Prefixs { get; set; } = new CharNSet (CliParsingConst.defaultPrefixs);
/// <summary>
/// 命令后缀,为一个字符,标点符号。不能为命令名或别名的尾字符。
/// </summary>
public CharNSet Postfixs { get; set; } = new CharNSet (CliParsingConst.defaultPostfixs);
public bool Equals (CmdParamName other)
{
if (other == null) return false;
if (ReferenceEquals (this, other)) return true;
return string.Equals (this.Id, other.Id, StringComparison.Ordinal);
}
public int CompareTo (CmdParamName other)
{
if (other == null) return 1;
if (ReferenceEquals (this, other)) return 0;
return string.Compare (this.Id, other.Id, StringComparison.Ordinal);
}
public override bool Equals (object obj) => Equals (obj as CmdParamName);
public override int GetHashCode () => this.Id?.GetHashCode () ?? 0;
public bool ParamContains (string param)
{
var ret = Name.NEquals (param);
if (!ret)
{
foreach (var alias in Aliases)
{
if (alias.NEquals (param)) return true;
}
}
return ret;
}
public void Dispose ()
{
Aliases?.Clear ();
Prefixs?.Clear ();
}
public CmdParamName (string id, string name, IEnumerable<string> aliases, IEnumerable<char> prefixs, IEnumerable<char> postfixs)
{
Id = id;
Name = name;
Aliases = new StringNSet (aliases);
Prefixs = new CharNSet (prefixs);
Postfixs = new CharNSet (postfixs);
}
public CmdParamName (string name, IEnumerable<string> aliases) : this (name, name, aliases, CliParsingConst.defaultPrefixs, CliParsingConst.defaultPostfixs) { }
public CmdParamName (string name) : this (name, CliParsingConst.emptyStringArray) { }
public CmdParamName () { }
}
public class CommandParam: IEquatable<string>
{
private string _id = "";
public string Id { get { return _id.NNormalize (); } set { _id = value; } }
public string Value = "";
public bool Equals (string other)
{
return (_id ?? "").NEquals (other);
}
public override bool Equals (object obj)
{
if (obj is string) return Equals (obj as string);
else if (obj is CommandParam) return Equals ((obj as CommandParam).Id);
else return base.Equals (obj);
}
public override int GetHashCode ()
{
return Id.GetHashCode ();
}
}
public class CliParsing: IDisposable
{
public HashSet<CmdParamName> Params { get; set; } = new HashSet<CmdParamName> ();
public void Dispose ()
{
Params = null;
}
public List<CommandParam> Parse (string [] args)
{
var ret = new List<CommandParam> ();
CommandParam last = new CommandParam ();
for (long i = 0; i < args.LongLength; i++)
{
var arg = args [i]?.Trim () ?? "";
var item = args [i]?.NNormalize () ?? "";
if (string.IsNullOrWhiteSpace (item)) continue;
var first = item [0];
bool isfind = false;
foreach (var param in Params)
{
if (param.Prefixs.Contains (first))
{
var minser = param.Postfixs.Select (e => {
var index = item.IndexOf (e);
return index == -1 ? int.MaxValue : index;
}).Min ();
string paramPart, postfixPart;
if (minser == int.MaxValue)
{
paramPart = arg.Substring (1);
postfixPart = "";
}
else
{
paramPart = arg.Substring (1, minser - 1);
postfixPart = arg.Substring (minser + 1);
}
if (param.ParamContains (paramPart))
{
isfind = true;
var cmdParam = new CommandParam ();
cmdParam.Id = param.Id;
if (!string.IsNullOrEmpty (postfixPart))
cmdParam.Value = postfixPart;
last = cmdParam;
ret.Add (cmdParam);
break;
}
}
}
if (!isfind)
{
var valueparam = new CommandParam ();
valueparam.Value = arg;
ret.Add (valueparam);
}
}
return ret;
}
}
public static class CliPasingUtils
{
public static bool ParamContains (this List<CommandParam> cpl, string id)
{
foreach (var i in cpl)
{
if (i.Id.NEquals (id)) return true;
}
return false;
}
public static bool ParamContains (this List<CommandParam> cpl, CmdParamName param)
{
foreach (var i in cpl)
{
if (i.Id.NEquals (param.Id)) return true;
}
return false;
}
public static bool ParamsContainsOr (this List<CommandParam> cpl, params string [] ids)
{
foreach (var i in cpl)
{
foreach (var j in ids)
{
if (i.Id.NEquals (j)) return true;
}
}
return false;
}
public static bool ParamsContainsAnd (this List<CommandParam> cpl, params string [] ids)
{
if (ids == null || ids.Length == 0) return true;
foreach (var id in ids)
{
if (!ParamContains (cpl, id)) return false;
}
return true;
}
public static CommandParam GetFromId (this List <CommandParam> cpl, string id)
{
foreach (var c in cpl)
{
if (c.Id.NEquals (id)) return c;
}
return null;
}
}
}

View File

@@ -50,6 +50,10 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.4\lib\net40\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
@@ -59,19 +63,29 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CliParsing.cs" />
<Compile Include="Polyfill.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Text.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AppxPackage\AppxPackage.csproj">
<Project>{bd681a4f-eb60-4bb8-90b5-65968fc7da59}</Project>
<Name>AppxPackage</Name>
</ProjectReference>
<ProjectReference Include="..\DataUtils\DataUtils.csproj">
<Project>{ffd3fd52-37a8-4f43-883c-de8d996cb0e0}</Project>
<Name>DataUtils</Name>
</ProjectReference>
<ProjectReference Include="..\PrivateInit\PrivateInit.csproj">
<Project>{8e708d9a-6325-4aa9-b5a5-d1b5eca8eef7}</Project>
<Name>PrivateInit</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

979
PkgCLI/Polyfill.cs Normal file
View File

@@ -0,0 +1,979 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using AppxPackage;
using AppxPackage.Info;
using Newtonsoft.Json;
namespace PkgCLI
{
public static class Polyfill
{
static public bool NEquals (this string s1, string s2)
{
if (string.IsNullOrWhiteSpace (s1) && string.IsNullOrWhiteSpace (s2)) return true;
else return s1?.Trim ()?.ToLowerInvariant () == s2?.Trim ()?.ToLowerInvariant ();
}
static public string NNormalize (this string s1)
{
return s1?.Trim ()?.ToLowerInvariant ();
}
static public string Join<T> (this IEnumerable<T> ie, string divide = ", ")
{
var ret = "";
for (var i = 0; i < ie.Count (); i++)
{
if (i != 0) ret += divide;
var item = ie.ElementAt (i);
if (item == null) ret += "(null)";
else ret += item.ToString ();
}
return ret;
}
/// <summary>
/// 将对象通过指定的选择器转换为目标类型。
/// 类似于 LINQ 的 Select但适用于单一对象。
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="obj">源对象</param>
/// <param name="selector">转换委托,输入源对象,输出目标对象</param>
/// <returns>转换后的结果</returns>
public static T ToOther<T> (this object obj, Func<object, T> selector)
{
if (selector == null)
throw new ArgumentNullException (nameof (selector));
return selector (obj);
}
/// <summary>
/// 将字典格式化为对齐的文本,每个键值对一行,分隔符垂直对齐。
/// </summary>
/// <param name="dict">要格式化的字典</param>
/// <param name="separator">分隔符(如 ":", "="),默认为 ":"</param>
/// <param name="indent">每行前的缩进字符串,默认为空</param>
/// <param name="sortKeys">是否按键名排序(不区分大小写),默认为 false</param>
/// <returns>格式化后的字符串,例如:
/// Name : Alice
/// Age : 30
/// </returns>
public static string FormatDictionaryAligned (
this IDictionary<string, string> dict,
string separator = ":",
string indent = "",
bool sortKeys = false)
{
if (dict == null || dict.Count == 0)
return string.Empty;
var keys = sortKeys
? dict.Keys.OrderBy (k => k, StringComparer.OrdinalIgnoreCase).ToList ()
: dict.Keys.ToList ();
int maxKeyLength = keys.Max (k => k.Length);
var sb = new StringBuilder ();
foreach (string key in keys)
{
string value = dict [key] ?? string.Empty;
sb.AppendLine ($"{indent}{key.PadRight (maxKeyLength)} {separator} {value}");
}
return sb.ToString ().TrimEnd (Environment.NewLine.ToCharArray ());
}
}
public static class PackageReaderExt
{
static public object GetJsonObjectForCli (this PackageReader pr)
{
var id = pr.Identity;
var prop = pr.Properties;
var pre = pr.Prerequisites;
var apps = pr.Applications;
var caps = pr.Capabilities;
var deps = pr.Dependencies;
dynamic obj = new {
valid = pr.IsValid,
type = pr.Type.ToOther (e => {
switch ((AppxPackage.Info.PackageType)e)
{
case AppxPackage.Info.PackageType.Appx: return "appx";
case AppxPackage.Info.PackageType.Bundle: return "bundle";
default:
case AppxPackage.Info.PackageType.Unknown: return "unknown";
}
}),
role = pr.Role.ToOther (o => {
switch ((AppxPackage.Info.PackageRole)o)
{
case AppxPackage.Info.PackageRole.Application: return "application";
case AppxPackage.Info.PackageRole.Framework: return "framework";
case AppxPackage.Info.PackageRole.Resource: return "resource";
default:
case AppxPackage.Info.PackageRole.Unknown: return "unknown";
}
}),
identity = new {
name = id.Name,
publisher = id.Publisher,
version = id.Version.Expression,
realVersion = id.RealVersion.Expression,
architecture = id.ProcessArchitecture.Select (e => {
switch (e)
{
case AppxPackage.Info.Architecture.ARM: return "arm";
case AppxPackage.Info.Architecture.ARM64: return "arm64";
case AppxPackage.Info.Architecture.Neutral: return "neutral";
default:
case AppxPackage.Info.Architecture.Unknown: return "unknown";
case AppxPackage.Info.Architecture.x64: return "x64";
case AppxPackage.Info.Architecture.x86: return "x86";
}
}).ToList (),
familyName = id.FamilyName,
fullName = id.FullName,
resourceId = id.ResourceId
},
properties = new {
displayName = prop.DisplayName,
publisherDisplayName = prop.Publisher,
description = prop.Description,
logo = prop.Logo,
framework = prop.Framework,
resourcePackage = prop.ResourcePackage
},
prerequisite = new {
osMinVersion = pre.OSMinVersion.ToString (),
osMaxVersionTested = pre.OSMaxVersionTested.ToString (),
_osMinVersion = pre.OSMinVersionDescription,
_osMaxVersionTested = pre.OSMaxVersionDescription
},
applications = apps.Select (e => {
var dict = new Dictionary<string, string> ();
foreach (var kv in e)
{
if (kv.Key.IndexOf ("Base64") >= 0) continue;
var value = e.NewAt (kv.Key, pr.EnablePri);
if (string.IsNullOrWhiteSpace (value))
value = e.At (kv.Key);
dict [kv.Key] = value;
}
return dict;
}).ToList (),
capabilities = new {
capabilities = caps.Capabilities,
deviceCapabilities = caps.DeviceCapabilities
},
dependencies = deps.Select (e => new {
name = e.Name,
publisher = e.Publisher,
minVersion = e.Version.ToString ()
})
};
return obj;
}
/// <summary>
/// 从 PackageReader 中获取指定路径的值。
/// 支持格式:路径中可使用 '.' 或 ':' 分隔,支持索引器 '[index]',支持 '.length'。
/// 大小写不敏感,自动去除首尾空白。
/// 示例:
/// "Identity" -> 返回 Identity 字典
/// "Identity.Name" -> 返回名称
/// "Properties.Publisher" -> 返回发布者显示名称(别名)
/// "applications[0]" -> 返回第一个应用字典
/// "applications.length" -> 返回应用个数
/// "Applications[0].LogoBase64" -> 返回第一个应用的 LogoBase64
/// </summary>
public static object GetItem (this PackageReader pr, string item)
{
if (pr == null) throw new ArgumentNullException ("pr");
if (string.IsNullOrWhiteSpace (item)) return null;
string path = item.Trim ().Replace (':', '.');
object result = ResolvePath (pr, path);
return SerializeObject (result, pr, false);
}
private static object ResolvePath (object target, string path)
{
if (target == null) return null;
if (string.IsNullOrEmpty (path)) return target;
string [] segments = path.Split ('.');
object current = target;
foreach (string seg in segments)
{
if (current == null) return null;
if (seg.Contains ("[") && seg.Contains ("]"))
{
int bracketStart = seg.IndexOf ('[');
string propName = seg.Substring (0, bracketStart);
string indexStr = seg.Substring (bracketStart + 1, seg.Length - bracketStart - 2);
int index;
if (!int.TryParse (indexStr, out index))
return null;
object collection = GetPropertyValue (current, propName);
if (collection == null) return null;
current = GetIndexedValue (collection, index);
}
else if (string.Equals (seg, "length", StringComparison.OrdinalIgnoreCase) ||
string.Equals (seg, "count", StringComparison.OrdinalIgnoreCase))
{
current = GetLength (current);
}
else
{
current = GetPropertyValue (current, seg);
}
}
return current;
}
private static object GetPropertyValue (object target, string propName)
{
if (target == null) return null;
Type type = target.GetType ();
// 根对象 PackageReader 的属性名映射(不区分大小写)
if (type == typeof (PackageReader))
{
string mapped = null;
string lower = propName.ToLowerInvariant ();
switch (lower)
{
case "pkgid":
case "id":
case "identity": mapped = "Identity"; break;
case "prop":
case "properties": mapped = "Properties"; break;
case "prerequistes":
case "prerequisite":
case "prerequisites": mapped = "Prerequisites"; break;
case "res":
case "resources": mapped = "Resources"; break;
case "apps":
case "applications": mapped = "Applications"; break;
case "caps":
case "capabilities": mapped = "Capabilities"; break;
case "deps":
case "dependencies": mapped = "Dependencies"; break;
case "type": mapped = "Type"; break;
case "role": mapped = "Role"; break;
case "valid":
case "isvalid": mapped = "IsValid"; break;
case "filepath": mapped = "FilePath"; break;
}
if (mapped != null)
propName = mapped;
}
// PRProperties 别名Publisher / PublisherDisplayName 都映射到 Publisher 属性
if (type == typeof (PRProperties))
{
if (string.Equals (propName, "Publisher", StringComparison.OrdinalIgnoreCase) ||
string.Equals (propName, "PublisherDisplayName", StringComparison.OrdinalIgnoreCase))
{
propName = "Publisher";
}
}
// PRApplication 中以 Base64 结尾的属性 -> 调用 NewAtBase64
if (type == typeof (PRApplication) && propName.EndsWith ("Base64", StringComparison.OrdinalIgnoreCase))
{
string baseKey = propName.Substring (0, propName.Length - 6);
PRApplication app = (PRApplication)target;
MethodInfo method = typeof (PRApplication).GetMethod ("NewAtBase64", BindingFlags.Public | BindingFlags.Instance);
if (method != null)
{
return method.Invoke (app, new object [] { baseKey });
}
return null;
}
// PRApplication 普通属性访问(字典键,大小写不敏感)
if (type == typeof (PRApplication))
{
PRApplication app = (PRApplication)target;
// 直接使用索引器,内部已处理资源解析和大小写不敏感
return app [propName];
}
// MRApplication 同理
if (type == typeof (MRApplication))
{
MRApplication app = (MRApplication)target;
return app [propName];
}
// 反射属性(不区分大小写)
PropertyInfo prop = type.GetProperty (propName,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (prop != null)
{
return prop.GetValue (target, null);
}
// 反射字段
FieldInfo field = type.GetField (propName,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (field != null)
{
return field.GetValue (target);
}
return null;
}
private static object GetIndexedValue (object collection, int index)
{
if (collection == null) return null;
// PRApplications
PRApplications apps = collection as PRApplications;
if (apps != null)
{
if (index >= 0 && index < apps.Applications.Count)
return apps.Applications [index];
return null;
}
// IList
IList list = collection as IList;
if (list != null && index >= 0 && index < list.Count)
return list [index];
// 索引器属性
PropertyInfo indexer = collection.GetType ().GetProperty ("Item", new [] { typeof (int) });
if (indexer != null)
return indexer.GetValue (collection, new object [] { index });
return null;
}
private static int? GetLength (object obj)
{
if (obj == null) return null;
PRApplications apps = obj as PRApplications;
if (apps != null) return apps.Applications.Count;
PRDependencies deps = obj as PRDependencies;
if (deps != null) return deps.Dependencies.Count;
IList list = obj as IList;
if (list != null) return list.Count;
ICollection coll = obj as ICollection;
if (coll != null) return coll.Count;
return null;
}
private static object SerializeObject (object obj, PackageReader pr, bool filterBase64)
{
if (obj == null) return null;
Type type = obj.GetType ();
if (type.IsPrimitive || obj is string || obj is decimal || obj is Enum)
return obj;
// PRIdentity
if (type == typeof (PRIdentity))
{
PRIdentity id = (PRIdentity)obj;
return new {
name = id.Name,
publisher = id.Publisher,
version = id.Version.Expression,
realVersion = id.RealVersion.Expression,
architecture = id.ProcessArchitecture.Select (e => {
switch (e)
{
case Architecture.ARM: return "arm";
case Architecture.ARM64: return "arm64";
case Architecture.Neutral: return "neutral";
case Architecture.x64: return "x64";
case Architecture.x86: return "x86";
default: return "unknown";
}
}).ToList (),
familyName = id.FamilyName,
fullName = id.FullName,
resourceId = id.ResourceId
};
}
// PRProperties
if (type == typeof (PRProperties))
{
PRProperties prop = (PRProperties)obj;
return new {
displayName = prop.DisplayName,
publisherDisplayName = prop.Publisher,
description = prop.Description,
logo = prop.Logo,
framework = prop.Framework,
resourcePackage = prop.ResourcePackage
};
}
// PRPrerequisites
if (type == typeof (PRPrerequisites))
{
PRPrerequisites pre = (PRPrerequisites)obj;
return new {
osMinVersion = pre.OSMinVersion,
osMaxVersionTested = pre.OSMaxVersionTested,
_osMinVersion = pre.OSMinVersionDescription,
_osMaxVersionTested = pre.OSMaxVersionDescription
};
}
// PRCapabilities
if (type == typeof (PRCapabilities))
{
PRCapabilities caps = (PRCapabilities)obj;
return new {
capabilities = caps.Capabilities,
deviceCapabilities = caps.DeviceCapabilities
};
}
// PRDependencies
if (type == typeof (PRDependencies))
{
PRDependencies deps = (PRDependencies)obj;
return deps.Select (e => new {
name = e.Name,
publisher = e.Publisher,
minVersion = e.Version.ToString ()
}).ToList ();
}
// PRApplications (集合)
if (type == typeof (PRApplications))
{
PRApplications apps = (PRApplications)obj;
return apps.Select (e => SerializeObject (e, pr, filterBase64)).ToList ();
}
// PRApplication (单个应用)
if (type == typeof (PRApplication))
{
PRApplication app = (PRApplication)obj;
var dict = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase);
foreach (var kv in app)
{
if (kv.Key.IndexOf ("Base64", StringComparison.OrdinalIgnoreCase) >= 0)
continue;
string value = app.NewAt (kv.Key, pr.EnablePri);
if (string.IsNullOrWhiteSpace (value))
value = app.At (kv.Key);
dict [kv.Key] = value;
}
return dict;
}
// IDictionary
IDictionary dictObj = obj as IDictionary;
if (dictObj != null)
{
var result = new Dictionary<string, object> (StringComparer.OrdinalIgnoreCase);
foreach (DictionaryEntry entry in dictObj)
{
string key = entry.Key?.ToString ();
if (string.IsNullOrEmpty (key)) continue;
if (filterBase64 && key.EndsWith ("_Base64", StringComparison.OrdinalIgnoreCase))
continue;
result [key] = SerializeObject (entry.Value, pr, filterBase64);
}
return result;
}
// IEnumerable (非字符串)
if (!(obj is string))
{
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null)
{
var list = new List<object> ();
foreach (var item in enumerable)
list.Add (SerializeObject (item, pr, filterBase64));
return list;
}
}
// 后备:反射属性
var props = type.GetProperties (BindingFlags.Public | BindingFlags.Instance);
var propDict = new Dictionary<string, object> (StringComparer.OrdinalIgnoreCase);
foreach (var prop in props)
{
if (prop.GetIndexParameters ().Length > 0) continue;
string propName = prop.Name;
if (filterBase64 && propName.EndsWith ("Base64", StringComparison.OrdinalIgnoreCase))
continue;
object val = prop.GetValue (obj, null);
propDict [propName] = SerializeObject (val, pr, filterBase64);
}
return propDict;
}
}
public static class ManifestReaderExt
{
/// <summary>
/// 获取用于 CLI 输出的 JSON 对象(与 PackageReaderExt.GetJsonObjectForCli 结构一致)。
/// </summary>
public static object GetJsonObjectForCli (this ManifestReader mr)
{
var id = mr.Identity;
var prop = mr.Properties;
var pre = mr.Prerequisites;
var apps = mr.Applications;
var caps = mr.Capabilities;
var deps = mr.Dependencies;
var res = mr.Resources;
dynamic obj = new {
valid = mr.IsValid,
type = mr.Type.ToOther (e => {
switch ((PackageType)e)
{
case PackageType.Appx: return "appx";
case PackageType.Bundle: return "bundle";
default:
case PackageType.Unknown: return "unknown";
}
}),
role = mr.Role.ToOther (o => {
switch ((PackageRole)o)
{
case PackageRole.Application: return "application";
case PackageRole.Framework: return "framework";
case PackageRole.Resource: return "resource";
default:
case PackageRole.Unknown: return "unknown";
}
}),
identity = new {
name = id.Name,
publisher = id.Publisher,
version = id.Version.Expression,
architecture = id.ProcessArchitecture.Select (e => {
switch (e)
{
case Architecture.ARM: return "arm";
case Architecture.ARM64: return "arm64";
case Architecture.Neutral: return "neutral";
case Architecture.x64: return "x64";
case Architecture.x86: return "x86";
default: return "unknown";
}
}).ToList (),
familyName = id.FamilyName,
fullName = id.FullName,
resourceId = id.ResourceId
},
properties = new {
displayName = prop.DisplayName,
publisherDisplayName = prop.Publisher,
description = prop.Description,
logo = prop.Logo,
framework = prop.Framework,
resourcePackage = prop.ResourcePackage
},
prerequisite = new {
osMinVersion = pre.OSMinVersion.ToString (),
osMaxVersionTested = pre.OSMaxVersionTested.ToString (),
_osMinVersion = pre.OSMinVersionDescription,
_osMaxVersionTested = pre.OSMaxVersionDescription
},
resources = new {
languages = res.Languages,
scales = res.Scales,
dxFeatureLevels = res.DXFeatures.Select (d => {
switch (d)
{
case DXFeatureLevel.Level9: return 9;
case DXFeatureLevel.Level10: return 10;
case DXFeatureLevel.Level11: return 11;
case DXFeatureLevel.Level12: return 12;
default: return -1;
}
}).ToList ()
},
applications = apps.Select (e => {
var dict = new Dictionary<string, string> ();
foreach (var kv in e)
{
if (kv.Key.IndexOf ("Base64", StringComparison.OrdinalIgnoreCase) >= 0)
continue;
string value = e.NewAt (kv.Key, mr.EnablePri);
if (string.IsNullOrWhiteSpace (value))
value = e.At (kv.Key);
dict [kv.Key] = value;
}
return dict;
}).ToList (),
capabilities = new {
capabilities = caps.Capabilities,
deviceCapabilities = caps.DeviceCapabilities
},
dependencies = deps.Select (e => new {
name = e.Name,
publisher = e.Publisher,
minVersion = e.Version.ToString ()
})
};
return obj;
}
/// <summary>
/// 从 ManifestReader 中获取指定路径的值。
/// 支持格式:路径中可使用 '.' 或 ':' 分隔,支持索引器 '[index]',支持 '.length'。
/// 大小写不敏感,自动去除首尾空白。
/// 示例:
/// "Identity" -> 返回 Identity 字典
/// "Identity.Name" -> 返回名称
/// "Properties.Publisher" -> 返回发布者显示名称(别名)
/// "applications[0]" -> 返回第一个应用字典
/// "applications.length" -> 返回应用个数
/// "Applications[0].LogoBase64" -> 返回第一个应用的 LogoBase64
/// </summary>
public static object GetItem (this ManifestReader mr, string item)
{
if (mr == null) throw new ArgumentNullException ("mr");
if (string.IsNullOrWhiteSpace (item)) return null;
string path = item.Trim ().Replace (':', '.');
object result = ResolvePath (mr, path);
return SerializeObject (result, mr, false);
}
private static object ResolvePath (object target, string path)
{
if (target == null) return null;
if (string.IsNullOrEmpty (path)) return target;
string [] segments = path.Split ('.');
object current = target;
foreach (string seg in segments)
{
if (current == null) return null;
if (seg.Contains ("[") && seg.Contains ("]"))
{
int bracketStart = seg.IndexOf ('[');
string propName = seg.Substring (0, bracketStart);
string indexStr = seg.Substring (bracketStart + 1, seg.Length - bracketStart - 2);
int index;
if (!int.TryParse (indexStr, out index))
return null;
object collection = GetPropertyValue (current, propName);
if (collection == null) return null;
current = GetIndexedValue (collection, index);
}
else if (string.Equals (seg, "length", StringComparison.OrdinalIgnoreCase) ||
string.Equals (seg, "count", StringComparison.OrdinalIgnoreCase))
{
current = GetLength (current);
}
else
{
current = GetPropertyValue (current, seg);
}
}
return current;
}
private static object GetPropertyValue (object target, string propName)
{
if (target == null) return null;
Type type = target.GetType ();
// 根对象 ManifestReader 的属性名映射(不区分大小写)
if (type == typeof (ManifestReader))
{
string mapped = null;
string lower = propName.ToLowerInvariant ();
switch (lower)
{
case "pkgid":
case "id":
case "identity": mapped = "Identity"; break;
case "prop":
case "properties": mapped = "Properties"; break;
case "prerequistes":
case "prerequisite":
case "prerequisites": mapped = "Prerequisites"; break;
case "res":
case "resources": mapped = "Resources"; break;
case "apps":
case "applications": mapped = "Applications"; break;
case "caps":
case "capabilities": mapped = "Capabilities"; break;
case "deps":
case "dependencies": mapped = "Dependencies"; break;
case "type": mapped = "Type"; break;
case "role": mapped = "Role"; break;
case "valid":
case "isvalid": mapped = "IsValid"; break;
case "file":
case "filepath": mapped = "FilePath"; break;
case "fileroot": mapped = "FileRoot"; break;
}
if (mapped != null)
propName = mapped;
}
// MRProperties 别名Publisher / PublisherDisplayName 都映射到 Publisher 属性
if (type == typeof (MRProperties))
{
if (string.Equals (propName, "Publisher", StringComparison.OrdinalIgnoreCase) ||
string.Equals (propName, "PublisherDisplayName", StringComparison.OrdinalIgnoreCase))
{
propName = "Publisher";
}
}
// MRApplication 中以 Base64 结尾的属性 -> 调用 NewAtBase64
if (type == typeof (MRApplication) && propName.EndsWith ("Base64", StringComparison.OrdinalIgnoreCase))
{
string baseKey = propName.Substring (0, propName.Length - 6);
MRApplication app = (MRApplication)target;
MethodInfo method = typeof (MRApplication).GetMethod ("NewAtBase64", BindingFlags.Public | BindingFlags.Instance);
if (method != null)
{
return method.Invoke (app, new object [] { baseKey });
}
return null;
}
// MRApplication 普通属性访问(字典键,大小写不敏感)
if (type == typeof (MRApplication))
{
MRApplication app = (MRApplication)target;
return app [propName];
}
// 反射属性(不区分大小写)
PropertyInfo prop = type.GetProperty (propName,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (prop != null)
{
return prop.GetValue (target, null);
}
// 反射字段
FieldInfo field = type.GetField (propName,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (field != null)
{
return field.GetValue (target);
}
return null;
}
private static object GetIndexedValue (object collection, int index)
{
if (collection == null) return null;
MRApplications apps = collection as MRApplications;
if (apps != null)
{
if (index >= 0 && index < apps.Applications.Count)
return apps.Applications [index];
return null;
}
IList list = collection as IList;
if (list != null && index >= 0 && index < list.Count)
return list [index];
PropertyInfo indexer = collection.GetType ().GetProperty ("Item", new [] { typeof (int) });
if (indexer != null)
return indexer.GetValue (collection, new object [] { index });
return null;
}
private static int? GetLength (object obj)
{
if (obj == null) return null;
MRApplications apps = obj as MRApplications;
if (apps != null) return apps.Applications.Count;
MRDependencies deps = obj as MRDependencies;
if (deps != null) return deps.Dependencies.Count;
IList list = obj as IList;
if (list != null) return list.Count;
ICollection coll = obj as ICollection;
if (coll != null) return coll.Count;
return null;
}
private static object SerializeObject (object obj, ManifestReader mr, bool filterBase64)
{
if (obj == null) return null;
Type type = obj.GetType ();
if (type.IsPrimitive || obj is string || obj is decimal || obj is Enum)
return obj;
// MRIdentity
if (type == typeof (MRIdentity))
{
MRIdentity id = (MRIdentity)obj;
return new {
name = id.Name,
publisher = id.Publisher,
version = id.Version.Expression,
architecture = id.ProcessArchitecture.Select (e => {
switch (e)
{
case Architecture.ARM: return "arm";
case Architecture.ARM64: return "arm64";
case Architecture.Neutral: return "neutral";
case Architecture.x64: return "x64";
case Architecture.x86: return "x86";
default: return "unknown";
}
}).ToList (),
familyName = id.FamilyName,
fullName = id.FullName,
resourceId = id.ResourceId
};
}
// MRProperties
if (type == typeof (MRProperties))
{
MRProperties prop = (MRProperties)obj;
return new {
displayName = prop.DisplayName,
publisherDisplayName = prop.Publisher,
description = prop.Description,
logo = prop.Logo,
framework = prop.Framework,
resourcePackage = prop.ResourcePackage
};
}
// MRPrerequisites
if (type == typeof (MRPrerequisites))
{
MRPrerequisites pre = (MRPrerequisites)obj;
return new {
osMinVersion = pre.OSMinVersion,
osMaxVersionTested = pre.OSMaxVersionTested,
_osMinVersion = pre.OSMinVersionDescription,
_osMaxVersionTested = pre.OSMaxVersionDescription
};
}
// MRResources
if (type == typeof (MRResources))
{
MRResources res = (MRResources)obj;
return new {
languages = res.Languages,
scales = res.Scales,
dxFeatureLevels = res.DXFeatures.Select (d => {
switch (d)
{
case DXFeatureLevel.Level9: return 9;
case DXFeatureLevel.Level10: return 10;
case DXFeatureLevel.Level11: return 11;
case DXFeatureLevel.Level12: return 12;
default: return -1;
}
}).ToList ()
};
}
// MRCapabilities
if (type == typeof (MRCapabilities))
{
MRCapabilities caps = (MRCapabilities)obj;
return new {
capabilities = caps.Capabilities,
deviceCapabilities = caps.DeviceCapabilities
};
}
// MRDependencies
if (type == typeof (MRDependencies))
{
MRDependencies deps = (MRDependencies)obj;
return deps.Select (e => new {
name = e.Name,
publisher = e.Publisher,
minVersion = e.Version.ToString ()
}).ToList ();
}
// MRApplications (集合)
if (type == typeof (MRApplications))
{
MRApplications apps = (MRApplications)obj;
return apps.Select (e => SerializeObject (e, mr, filterBase64)).ToList ();
}
// MRApplication (单个应用)
if (type == typeof (MRApplication))
{
MRApplication app = (MRApplication)obj;
var dict = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase);
foreach (var kv in app)
{
if (kv.Key.IndexOf ("Base64", StringComparison.OrdinalIgnoreCase) >= 0)
continue;
string value = app.NewAt (kv.Key, mr.EnablePri);
if (string.IsNullOrWhiteSpace (value))
value = app.At (kv.Key);
dict [kv.Key] = value;
}
return dict;
}
// IDictionary
IDictionary dictObj = obj as IDictionary;
if (dictObj != null)
{
var result = new Dictionary<string, object> (StringComparer.OrdinalIgnoreCase);
foreach (DictionaryEntry entry in dictObj)
{
string key = entry.Key?.ToString ();
if (string.IsNullOrEmpty (key)) continue;
if (filterBase64 && key.EndsWith ("_Base64", StringComparison.OrdinalIgnoreCase))
continue;
result [key] = SerializeObject (entry.Value, mr, filterBase64);
}
return result;
}
// IEnumerable (非字符串)
if (!(obj is string))
{
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null)
{
var list = new List<object> ();
foreach (var item in enumerable)
list.Add (SerializeObject (item, mr, filterBase64));
return list;
}
}
// 后备:反射属性
var props = type.GetProperties (BindingFlags.Public | BindingFlags.Instance);
var propDict = new Dictionary<string, object> (StringComparer.OrdinalIgnoreCase);
foreach (var prop in props)
{
if (prop.GetIndexParameters ().Length > 0) continue;
string propName = prop.Name;
if (filterBase64 && propName.EndsWith ("Base64", StringComparison.OrdinalIgnoreCase))
continue;
object val = prop.GetValue (obj, null);
propDict [propName] = SerializeObject (val, mr, filterBase64);
}
return propDict;
}
}
}

File diff suppressed because it is too large Load Diff

112
PkgCLI/Text.cs Normal file
View File

@@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace System
{
namespace Text
{
public static class Escape
{
/// <summary>按 JSON 规范对字符串进行转义。</summary>
/// <param name="input">原始字符串。</param>
/// <returns>转义后的 JSON 字符串字面量内容(不含外围双引号)。</returns>
public static string ToEscape (string input)
{
if (input == null) throw new ArgumentNullException (nameof (input));
if (input.Length == 0) return string.Empty;
StringBuilder sb = new StringBuilder (input.Length);
foreach (char c in input)
{
switch (c)
{
case '"': sb.Append ("\\\""); break;
case '\\': sb.Append ("\\\\"); break;
case '\b': sb.Append ("\\b"); break;
case '\f': sb.Append ("\\f"); break;
case '\n': sb.Append ("\\n"); break;
case '\r': sb.Append ("\\r"); break;
case '\t': sb.Append ("\\t"); break;
default:
// 控制字符 (U+0000 - U+001F) 需转义为 \uXXXX
if (c <= 0x1F)
{
sb.Append ("\\u");
sb.Append (((int)c).ToString ("X4"));
}
else
{
sb.Append (c);
}
break;
}
}
return sb.ToString ();
}
/// <summary>按 JSON 规范反转义字符串。</summary>
/// <param name="input">转义后的 JSON 字符串内容(不含外围双引号)。</param>
/// <returns>原始字符串。</returns>
/// <exception cref="FormatException">遇到非法转义序列时抛出。</exception>
public static string Unescape (string input)
{
if (input == null) throw new ArgumentNullException (nameof (input));
if (input.Length == 0) return string.Empty;
StringBuilder sb = new StringBuilder (input.Length);
int i = 0;
while (i < input.Length)
{
char c = input [i];
if (c == '\\')
{
i++;
if (i >= input.Length)
throw new FormatException ("字符串末尾包含不完整的转义序列。");
char next = input [i];
switch (next)
{
case '"': sb.Append ('"'); break;
case '\\': sb.Append ('\\'); break;
case '/': sb.Append ('/'); break; // 允许转义斜杠
case 'b': sb.Append ('\b'); break;
case 'f': sb.Append ('\f'); break;
case 'n': sb.Append ('\n'); break;
case 'r': sb.Append ('\r'); break;
case 't': sb.Append ('\t'); break;
case 'u':
i++;
if (i + 4 > input.Length)
throw new FormatException ("\\u 转义后必须跟随 4 位十六进制数字。");
string hex = input.Substring (i, 4);
int codePoint; // 先声明变量,兼容 C# 5/6
if (!int.TryParse (hex,
NumberStyles.HexNumber,
CultureInfo.InvariantCulture,
out codePoint))
{
throw new FormatException (string.Format ("无效的 Unicode 转义序列: \\u{0}", hex));
}
sb.Append ((char)codePoint);
i += 3; // 循环末尾会再加1因此这里只增加3
break;
default:
throw new FormatException (string.Format ("未识别的转义序列: \\{0}", next));
}
}
else
{
sb.Append (c);
}
i++;
}
return sb.ToString ();
}
}
}
}

4
PkgCLI/packages.config Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.4" targetFramework="net40" />
</packages>

View File

@@ -381,6 +381,7 @@ void DestroyPriFileInstance (PCSPRIFILE pFilePri)
if (!pFilePri) return;
try
{
#ifdef ELDER_FUNC
CreateScopedLock (g_threadlock);
auto it = g_tasklist.find (pFilePri);
if (it != g_tasklist.end ())
@@ -388,6 +389,7 @@ void DestroyPriFileInstance (PCSPRIFILE pFilePri)
it->second.bIsRunning = false;
g_tasklist.erase (it);
}
#endif
IntPtr handlePtr = IntPtr (pFilePri);
System::Runtime::InteropServices::GCHandle handle = System::Runtime::InteropServices::GCHandle::FromIntPtr (handlePtr);
PriFileInst ^inst = safe_cast <PriFileInst ^> (handle.Target);

Binary file not shown.

Binary file not shown.

View File

@@ -442,6 +442,8 @@
createShortcutButton.setAttribute("data-app-user-model-id", item.AppUserModelID);
createShortcutButton.textContent = strres.get("MANAGER_APP_SHORTCUTCREATE_TITLE");
createShortcutButton.style.marginRight = "10px";
appItem.setAttribute("title", item.Id);
appItem.setAttribute("aria-label", item.DisplayName || item.ShortName);
Windows.UI.Event.Util.addEvent(launchButton, "click", function(e) {
e.stopPropagation();
Package.manager.active(this.getAttribute("data-app-user-model-id"));

View File

@@ -80,6 +80,9 @@
<p>
<a id="about-eula" data-res-fromfile="publicRes(137)"></a>
</p>
<p>
<a id="about-thanks" data-res-fromfile="publicRes (230)"></a>
</p>
<p data-res-fromfile="publicRes (138)"></p>
<ul>
<li><a href="https://github.com/chausner/PriTools" target="_blank">chausner/PriTools</a></li>
@@ -88,8 +91,8 @@
<li><a href="https://github.com/winjs/winjs" target="_blank">WinJS</a></li>
<li><a href="https://github.com/evilstreak/markdown-js" target="_blank">markdown.js</a></li>
<li><a href="https://codemirror.net/" target="_blank">CodeMirror</a></li>
<li><a href="https://www.newtonsoft.com/json" target="_blank">Newtonsoft.Json</a></li>
<li><a href="https://icsharpcode.github.io/SharpZipLib/" target="_blank">SharpZipLib</a></li>
<li><a href="https://www.newtonsoft.com/json" target="_blank">Newtonsoft.Json</a></li>
<li><a href="https://icsharpcode.github.io/SharpZipLib/" target="_blank">SharpZipLib</a></li>
</ul>
<script>
(function() {
@@ -185,7 +188,6 @@
});
eventutil.addEvent(aboutProjectDescription, "click", function() {
function decodeBase64(base64) {
// GitHub 的 content 有换行,必须清理
base64 = base64.replace(/\s/g, "");
return atob(base64);
}
@@ -300,6 +302,22 @@
body.style.color = "black";
}, 0);
});
var aboutThanks = document.getElementById("about-thanks");
eventutil.addEvent(aboutThanks, "click", function() {
var content = document.createElement("div");
var p = document.createElement("p");
p.textContent = getPublicRes(231);
content.appendChild(p);
var contributes = '<a href="https://github.com/modernw/App-Installer-For-Windows-8.x-Reset/graphs/contributors" target="_blank">\n \x3C!-- Made with [contrib.rocks](https://contrib.rocks). -->\n <img src="https://contrib.rocks/image?repo=modernw/App-Installer-For-Windows-8.x-Reset&columns=10" style="max-width:100%" />\n</a>\n';
content.innerHTML += contributes;
var p1 = document.createElement("p");
p1.textContent = getPublicRes(232);
content.appendChild(p1);
var dlg = new MsgBox();
dlg.text = content;
dlg.title = getPublicRes(230);
dlg.show();
});
})();
</script>
</div>

View File

@@ -1,21 +1,202 @@
MIT License
Copyright (c) 2025 Windows Modern
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
1. Definitions.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

13
shared/license/NOTICE Normal file
View File

@@ -0,0 +1,13 @@
Copyright (c) 2025-2026 Windows Modern
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -65,7 +65,7 @@ text-align: center;
<p>Copyright &#169; 2025 Windows Modern. 本软件及其源码受版权法保护。</p>
<h2>二、许可范围</h2>
<p>本软件遵循 MIT 许可协议。您可以在符合 MIT 许可条件下自由使用、复制、修改、分发本软件及其源码,包括商业用途。</p>
<p>本软件遵循 Apache 2.0 许可。您可以在遵守 Apache 2.0 许可条件下自由使用、复制、修改、分发本软件及其源码,包括商业用途。需保留版权声明和许可证文本。</p>
<h2>三、第三方组件</h2>
<p>本软件包含以下第三方开源组件,使用这些组件受其原始许可证约束:</p>

View File

@@ -67,7 +67,7 @@ text-align: center;
<p>Copyright © 2025 Windows Modern. This software and its source code are protected by copyright law.</p>
<h2>2. License</h2>
<p>This software is licensed under the MIT License. You are free to use, copy, modify, and distribute this software and its source code, including for commercial purposes, subject to the terms of the MIT License.</p>
<p>This software is licensed under the Apache 2.0 License. You are free to use, copy, modify, and distribute this software and its source code, including for commercial purposes, provided you comply with the Apache 2.0 License. You must retain the copyright notice and license text.</p>
<h2>3. Third-Party Components</h2>
<p>This software includes the following third-party open source components, which are subject to their original licenses:</p>

View File

@@ -1 +1 @@
0.3.1.0
0.3.1.5