From 37ac4c684ce3904c5ec614362ed99bb9867ca0f3 Mon Sep 17 00:00:00 2001 From: Michael Date: Mon, 29 May 2017 20:08:30 -0400 Subject: It's amazing what talking to Rylan can do to an integer datatype. --- ShiftOS.WinForms/HackerCommands.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ShiftOS.WinForms/HackerCommands.cs') diff --git a/ShiftOS.WinForms/HackerCommands.cs b/ShiftOS.WinForms/HackerCommands.cs index 47b486d..f467eb2 100644 --- a/ShiftOS.WinForms/HackerCommands.cs +++ b/ShiftOS.WinForms/HackerCommands.cs @@ -504,7 +504,7 @@ namespace ShiftOS.WinForms string usr = args["user"].ToString(); string sys = args["sys"].ToString(); string pass = args["pass"].ToString(); - long amount = (long)args["amount"]; + ulong amount = (ulong)args["amount"]; if(amount < 0) { Console.WriteLine("--invalid codepoint amount - halting..."); -- cgit v1.2.3 From 0ca2fffe7a214fb5cc4c6482ca6fb8d1e4d2c4ea Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 30 May 2017 13:18:08 -0400 Subject: storydev.list command --- ShiftOS.WinForms/HackerCommands.cs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'ShiftOS.WinForms/HackerCommands.cs') diff --git a/ShiftOS.WinForms/HackerCommands.cs b/ShiftOS.WinForms/HackerCommands.cs index f467eb2..316b7fc 100644 --- a/ShiftOS.WinForms/HackerCommands.cs +++ b/ShiftOS.WinForms/HackerCommands.cs @@ -2,12 +2,14 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using ShiftOS.Engine; using ShiftOS.Objects; +using ShiftOS.Objects.ShiftFS; using ShiftOS.WinForms.Applications; using static ShiftOS.Objects.ShiftFS.Utils; @@ -674,6 +676,34 @@ namespace ShiftOS.WinForms return true; } + [Command("list", description ="Lists all story IDs.")] + public static bool ListIds() + { + foreach(var exec in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) + { + if(exec.ToLower().EndsWith(".exe") || exec.ToLower().EndsWith(".dll")) + { + try + { + var asm = Assembly.LoadFile(exec); + { + foreach(var type in asm.GetTypes()) + { + foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) + { + var attr = method.GetCustomAttributes(false).FirstOrDefault(x => x is StoryAttribute); + if (attr != null) + Console.WriteLine(" - " + (attr as StoryAttribute).StoryID); + } + } + } + } + catch { } + } + } + return true; + } + [Command("unexperience", description = "Marks a story plot as not-experienced yet.", usage ="id:string")] [RemoteLock] [RequiresArgument("id")] -- cgit v1.2.3 From 107a98686a105468b5f200ebcbd27343c1210ce4 Mon Sep 17 00:00:00 2001 From: RogueAI42 Date: Sun, 11 Jun 2017 17:34:38 +1000 Subject: ReflectMan Saves The Day.............. Refactored every part in the code that used that damn foreach loop. All assemblies are now loaded on startup into an array, and the results of GetType() on each are concatenated into another array. The parts of the code that were loading the assemblies and scanning them themselves now look to ReflectMan.Types, and all disk I/O is limited to the first time ReflectMan is accessed. While I was there I also replaced some other foreach loops with array comprehensions and such to speed things up - there is a noticeable improvement. It doesn't seem to have broken anything, but I'd appreciate if someone could do more stress testing for me. --- ShiftOS.WinForms/Applications/IconManager.cs | 99 ++++++++---------- ShiftOS.WinForms/Applications/Shiftnet.cs | 113 +++++++++------------ .../Applications/ShiftoriumFrontend.cs | 7 +- ShiftOS.WinForms/HackerCommands.cs | 25 +---- ShiftOS.WinForms/Program.cs | 70 +++++-------- ShiftOS.WinForms/ShiftnetSites/AppscapeMain.cs | 30 ++---- ShiftOS.WinForms/ShiftnetSites/MainHomepage.cs | 57 ++++------- ShiftOS.WinForms/ShiftnetSites/ShiftSoft_Ping.cs | 69 +++++-------- ShiftOS.WinForms/WidgetManager.cs | 36 ++----- ShiftOS_TheReturn/AppLauncherDaemon.cs | 53 ++-------- ShiftOS_TheReturn/AppearanceManager.cs | 20 +--- ShiftOS_TheReturn/Commands.cs | 89 +++++----------- ShiftOS_TheReturn/NotificationDaemon.cs | 21 +--- ShiftOS_TheReturn/ReflectMan.cs | 80 +++++++++++++++ ShiftOS_TheReturn/Scripting.cs | 53 ++-------- ShiftOS_TheReturn/ServerManager.cs | 27 ++--- ShiftOS_TheReturn/ShiftOS.Engine.csproj | 1 + ShiftOS_TheReturn/Shiftorium.cs | 22 +--- ShiftOS_TheReturn/Skinning.cs | 34 ++----- ShiftOS_TheReturn/Story.cs | 65 +++++------- ShiftOS_TheReturn/TerminalBackend.cs | 66 +++++------- 21 files changed, 374 insertions(+), 663 deletions(-) create mode 100644 ShiftOS_TheReturn/ReflectMan.cs (limited to 'ShiftOS.WinForms/HackerCommands.cs') diff --git a/ShiftOS.WinForms/Applications/IconManager.cs b/ShiftOS.WinForms/Applications/IconManager.cs index 0c6e119..7bbeb34 100644 --- a/ShiftOS.WinForms/Applications/IconManager.cs +++ b/ShiftOS.WinForms/Applications/IconManager.cs @@ -92,70 +92,51 @@ namespace ShiftOS.WinForms.Applications { flbody.Controls.Clear(); //Clear the icon list. - List types = new List(); + Type[] types = Array.FindAll(ReflectMan.Types, x => x.GetCustomAttributes(false).FirstOrDefault(y => y is DefaultIconAttribute) != null); - foreach(var exe in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - if(exe.ToLower().EndsWith(".exe") || exe.ToLower().EndsWith(".dll")) - { - try - { - var asm = Assembly.LoadFile(exe); + pageCount = types.GetPageCount(pageSize); - var typeList = asm.GetTypes().Where(x => x.GetCustomAttributes(false).FirstOrDefault(y => y is DefaultIconAttribute) != null); - types.AddRange(typeList); - - } - catch { } - } - } - - pageCount = types.ToArray().GetPageCount(pageSize); - - foreach (var type in types.ToArray().GetItemsOnPage(currentPage, pageSize)) + foreach (var type in Array.FindAll(types.GetItemsOnPage(currentPage, pageSize), t => Shiftorium.UpgradeAttributesUnlocked(t))) { - if (Shiftorium.UpgradeAttributesUnlocked(type)) + var pnl = new Panel(); + pnl.Height = 30; + pnl.Width = flbody.Width - 15; + flbody.Controls.Add(pnl); + pnl.Show(); + var pic = new PictureBox(); + pic.SizeMode = PictureBoxSizeMode.StretchImage; + pic.Size = new Size(24, 24); + pic.Image = GetIcon(type.Name); + pnl.Controls.Add(pic); + pic.Left = 5; + pic.Top = (pnl.Height - pic.Height) / 2; + pic.Show(); + var lbl = new Label(); + lbl.Tag = "header3"; + lbl.AutoSize = true; + lbl.Text = NameChangerBackend.GetNameRaw(type); + ControlManager.SetupControl(lbl); + pnl.Controls.Add(lbl); + lbl.CenterParent(); + lbl.Show(); + var btn = new Button(); + btn.Text = "Change..."; + btn.AutoSize = true; + btn.AutoSizeMode = AutoSizeMode.GrowAndShrink; + pnl.Controls.Add(btn); + btn.Left = (pnl.Width - btn.Width) - 5; + btn.Top = (pnl.Height - btn.Height) / 2; + btn.Click += (o, a) => { - var pnl = new Panel(); - pnl.Height = 30; - pnl.Width = flbody.Width - 15; - flbody.Controls.Add(pnl); - pnl.Show(); - var pic = new PictureBox(); - pic.SizeMode = PictureBoxSizeMode.StretchImage; - pic.Size = new Size(24, 24); - pic.Image = GetIcon(type.Name); - pnl.Controls.Add(pic); - pic.Left = 5; - pic.Top = (pnl.Height - pic.Height) / 2; - pic.Show(); - var lbl = new Label(); - lbl.Tag = "header3"; - lbl.AutoSize = true; - lbl.Text = NameChangerBackend.GetNameRaw(type); - ControlManager.SetupControl(lbl); - pnl.Controls.Add(lbl); - lbl.CenterParent(); - lbl.Show(); - var btn = new Button(); - btn.Text = "Change..."; - btn.AutoSize = true; - btn.AutoSizeMode = AutoSizeMode.GrowAndShrink; - pnl.Controls.Add(btn); - btn.Left = (pnl.Width - btn.Width) - 5; - btn.Top = (pnl.Height - btn.Height) / 2; - btn.Click += (o, a) => + var gfp = new GraphicPicker(pic.Image, lbl.Text + " icon", ImageLayout.Stretch, (raw, img, layout) => { - var gfp = new GraphicPicker(pic.Image, lbl.Text + " icon", ImageLayout.Stretch, (raw, img, layout) => - { - pic.Image = img; - SetIcon(type.Name, raw); - }); - AppearanceManager.SetupDialog(gfp); - }; - btn.Show(); - ControlManager.SetupControls(pnl); - } + pic.Image = img; + SetIcon(type.Name, raw); + }); + AppearanceManager.SetupDialog(gfp); + }; + btn.Show(); + ControlManager.SetupControls(pnl); } btnnext.Visible = (currentPage < pageCount - 1); diff --git a/ShiftOS.WinForms/Applications/Shiftnet.cs b/ShiftOS.WinForms/Applications/Shiftnet.cs index 6ccdb19..136f680 100644 --- a/ShiftOS.WinForms/Applications/Shiftnet.cs +++ b/ShiftOS.WinForms/Applications/Shiftnet.cs @@ -150,79 +150,60 @@ namespace ShiftOS.WinForms.Applications { txturl.Text = url; - foreach(var exe in Directory.GetFiles(Environment.CurrentDirectory)) + try { - if(exe.EndsWith(".exe") || exe.EndsWith(".dll")) + foreach (var type in Array.FindAll(ReflectMan.Types, t => t.GetInterfaces().Contains(typeof(IShiftnetSite)) && t.BaseType == typeof(UserControl) && Shiftorium.UpgradeAttributesUnlocked(t))) { - try + var attribute = type.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftnetSiteAttribute && (x as ShiftnetSiteAttribute).Url == url) as ShiftnetSiteAttribute; + if (attribute != null) { - var asm = Assembly.LoadFile(exe); - foreach (var type in asm.GetTypes()) - { - if (type.GetInterfaces().Contains(typeof(IShiftnetSite))) + var obj = (IShiftnetSite)Activator.CreateInstance(type, null); + obj.GoToUrl += (u) => { - if (type.BaseType == typeof(UserControl)) - { - var attribute = type.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftnetSiteAttribute) as ShiftnetSiteAttribute; - if (attribute != null) - { - if (attribute.Url == url) - { - if (Shiftorium.UpgradeAttributesUnlocked(type)) - { - var obj = (IShiftnetSite)Activator.CreateInstance(type, null); - obj.GoToUrl += (u) => - { - History.Push(CurrentUrl); - NavigateToUrl(u); - }; - obj.GoBack += () => - { - string u = History.Pop(); - Future.Push(u); - NavigateToUrl(u); - }; - CurrentPage = obj; - this.pnlcanvas.Controls.Clear(); - this.pnlcanvas.Controls.Add((UserControl)obj); - ((UserControl)obj).Show(); - ((UserControl)obj).Dock = DockStyle.Fill; - obj.OnUpgrade(); - obj.OnSkinLoad(); - obj.Setup(); - AppearanceManager.SetWindowTitle(this, attribute.Name + " - Shiftnet"); - return; - } - } - } - } - } - } - } - catch (Exception ex) - { - pnlcanvas.Controls.Clear(); - var tlbl = new Label(); - tlbl.Text = "Server error in \"" + url + "\" application."; - tlbl.Tag = "header1"; - tlbl.AutoSize = true; - tlbl.Location = new Point(10, 10); - tlbl.Dock = DockStyle.Top; - pnlcanvas.Controls.Add(tlbl); - tlbl.Show(); - - var crash = new Label(); - crash.Dock = DockStyle.Fill; - crash.AutoSize = false; - crash.Text = ex.ToString(); - pnlcanvas.Controls.Add(crash); - crash.Show(); - crash.BringToFront(); - ControlManager.SetupControls(pnlcanvas); - return; + History.Push(CurrentUrl); + NavigateToUrl(u); + }; + obj.GoBack += () => + { + string u = History.Pop(); + Future.Push(u); + NavigateToUrl(u); + }; + CurrentPage = obj; + this.pnlcanvas.Controls.Clear(); + this.pnlcanvas.Controls.Add((UserControl)obj); + ((UserControl)obj).Show(); + ((UserControl)obj).Dock = DockStyle.Fill; + obj.OnUpgrade(); + obj.OnSkinLoad(); + obj.Setup(); + AppearanceManager.SetWindowTitle(this, attribute.Name + " - Shiftnet"); + return; } } } + catch (Exception ex) + { + pnlcanvas.Controls.Clear(); + var tlbl = new Label(); + tlbl.Text = "Server error in \"" + url + "\" application."; + tlbl.Tag = "header1"; + tlbl.AutoSize = true; + tlbl.Location = new Point(10, 10); + tlbl.Dock = DockStyle.Top; + pnlcanvas.Controls.Add(tlbl); + tlbl.Show(); + + var crash = new Label(); + crash.Dock = DockStyle.Fill; + crash.AutoSize = false; + crash.Text = ex.ToString(); + pnlcanvas.Controls.Add(crash); + crash.Show(); + crash.BringToFront(); + ControlManager.SetupControls(pnlcanvas); + return; + } pnlcanvas.Controls.Clear(); var lbl = new Label(); lbl.Text = "Page not found!"; diff --git a/ShiftOS.WinForms/Applications/ShiftoriumFrontend.cs b/ShiftOS.WinForms/Applications/ShiftoriumFrontend.cs index eebd897..6886d98 100644 --- a/ShiftOS.WinForms/Applications/ShiftoriumFrontend.cs +++ b/ShiftOS.WinForms/Applications/ShiftoriumFrontend.cs @@ -114,8 +114,12 @@ namespace ShiftOS.WinForms.Applications private void SetList() { - lbnoupgrades.Hide(); lbupgrades.Items.Clear(); + if (upgrades.Length == 0) + return; + lbnoupgrades.Hide(); + if (CategoryId > upgrades.Length) + CategoryId = 0; try { lbupgrades.Items.AddRange(upgrades[CategoryId].Keys.ToArray()); @@ -250,6 +254,7 @@ namespace ShiftOS.WinForms.Applications private void moveCat(short direction) // direction is -1 to move backwards or 1 to move forwards { + if (cats.Length == 0) return; CategoryId += direction; CategoryId %= cats.Length; if (CategoryId < 0) CategoryId += cats.Length; // fix modulo on negatives diff --git a/ShiftOS.WinForms/HackerCommands.cs b/ShiftOS.WinForms/HackerCommands.cs index 316b7fc..dd8bde8 100644 --- a/ShiftOS.WinForms/HackerCommands.cs +++ b/ShiftOS.WinForms/HackerCommands.cs @@ -679,28 +679,13 @@ namespace ShiftOS.WinForms [Command("list", description ="Lists all story IDs.")] public static bool ListIds() { - foreach(var exec in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - if(exec.ToLower().EndsWith(".exe") || exec.ToLower().EndsWith(".dll")) + foreach(var type in ReflectMan.Types) + foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { - try - { - var asm = Assembly.LoadFile(exec); - { - foreach(var type in asm.GetTypes()) - { - foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) - { - var attr = method.GetCustomAttributes(false).FirstOrDefault(x => x is StoryAttribute); - if (attr != null) - Console.WriteLine(" - " + (attr as StoryAttribute).StoryID); - } - } - } - } - catch { } + var attr = method.GetCustomAttributes(false).FirstOrDefault(x => x is StoryAttribute); + if (attr != null) + Console.WriteLine(" - " + (attr as StoryAttribute).StoryID); } - } return true; } diff --git a/ShiftOS.WinForms/Program.cs b/ShiftOS.WinForms/Program.cs index b5fb731..d3530a0 100644 --- a/ShiftOS.WinForms/Program.cs +++ b/ShiftOS.WinForms/Program.cs @@ -114,53 +114,39 @@ namespace ShiftOS.WinForms { var defaultList = JsonConvert.DeserializeObject>(Properties.Resources.Shiftorium); - foreach(var exe in Directory.GetFiles(Environment.CurrentDirectory)) + foreach (var type in ReflectMan.Types) { - if (exe.EndsWith(".exe") || exe.EndsWith(".dll")) + var attribs = type.GetCustomAttributes(false); + var attrib = attribs.FirstOrDefault(x => x is AppscapeEntryAttribute) as AppscapeEntryAttribute; + if (attrib != null) { - try + var upgrade = new ShiftoriumUpgrade { - var asm = Assembly.LoadFile(exe); - foreach (var type in asm.GetTypes()) - { - var attrib = type.GetCustomAttributes(false).FirstOrDefault(x => x is AppscapeEntryAttribute) as AppscapeEntryAttribute; - if (attrib != null) - { - var upgrade = new ShiftoriumUpgrade - { - Id = attrib.Name.ToLower().Replace(" ", "_"), - Name = attrib.Name, - Description = attrib.Description, - Cost = attrib.Cost, - Category = attrib.Category, - Dependencies = (string.IsNullOrWhiteSpace(attrib.DependencyString)) ? "appscape_handled_nodisplay" : "appscape_handled_nodisplay;" + attrib.DependencyString - }; - defaultList.Add(upgrade); - } - - var sattrib = type.GetCustomAttributes(false).FirstOrDefault(x => x is StpContents) as StpContents; - if (sattrib != null) - { - var upgrade = new ShiftoriumUpgrade - { - Id = sattrib.Upgrade, - Name = sattrib.Name, - Description = "This is a hidden dummy upgrade for the .stp file installation attribute \"" + sattrib.Name + "\".", - Cost = 0, - Category = "If this is shown, there's a bug in the Shiftorium Provider or the user is a supreme Shifter.", - Dependencies = "dummy_nodisplay" - }; - defaultList.Add(upgrade); - } - - } - - - + Id = attrib.Name.ToLower().Replace(" ", "_"), + Name = attrib.Name, + Description = attrib.Description, + Cost = attrib.Cost, + Category = attrib.Category, + Dependencies = (string.IsNullOrWhiteSpace(attrib.DependencyString)) ? "appscape_handled_nodisplay" : "appscape_handled_nodisplay;" + attrib.DependencyString + }; + defaultList.Add(upgrade); + } - } - catch { } + var sattrib = attribs.FirstOrDefault(x => x is StpContents) as StpContents; + if (sattrib != null) + { + var upgrade = new ShiftoriumUpgrade + { + Id = sattrib.Upgrade, + Name = sattrib.Name, + Description = "This is a hidden dummy upgrade for the .stp file installation attribute \"" + sattrib.Name + "\".", + Cost = 0, + Category = "If this is shown, there's a bug in the Shiftorium Provider or the user is a supreme Shifter.", + Dependencies = "dummy_nodisplay" + }; + defaultList.Add(upgrade); } + } return defaultList; } diff --git a/ShiftOS.WinForms/ShiftnetSites/AppscapeMain.cs b/ShiftOS.WinForms/ShiftnetSites/AppscapeMain.cs index c7830d0..c9b6f64 100644 --- a/ShiftOS.WinForms/ShiftnetSites/AppscapeMain.cs +++ b/ShiftOS.WinForms/ShiftnetSites/AppscapeMain.cs @@ -207,33 +207,21 @@ namespace ShiftOS.WinForms.ShiftnetSites if (result == true) { SaveSystem.CurrentSave.Codepoints -= upg.Cost; - foreach (var exe in Directory.GetFiles(Environment.CurrentDirectory)) + foreach (var type in ReflectMan.Types) { - if (exe.EndsWith(".exe") || exe.EndsWith(".dll")) + var attrib = type.GetCustomAttributes(false).FirstOrDefault(x => x is AppscapeEntryAttribute) as AppscapeEntryAttribute; + if (attrib != null) { - try + if (attrib.Name == upg.Name) { - var asm = Assembly.LoadFile(exe); - foreach (var type in asm.GetTypes()) - { - var attrib = type.GetCustomAttributes(false).FirstOrDefault(x => x is AppscapeEntryAttribute) as AppscapeEntryAttribute; - if (attrib != null) - { - if (attrib.Name == upg.Name) - { - var installer = new Applications.Installer(); - var installation = new AppscapeInstallation(upg.Name, attrib.DownloadSize, upg.ID); - AppearanceManager.SetupWindow(installer); - installer.InitiateInstall(installation); - return; - } - } - } + var installer = new Applications.Installer(); + var installation = new AppscapeInstallation(upg.Name, attrib.DownloadSize, upg.ID); + AppearanceManager.SetupWindow(installer); + installer.InitiateInstall(installation); + return; } - catch { } } } - } }); } diff --git a/ShiftOS.WinForms/ShiftnetSites/MainHomepage.cs b/ShiftOS.WinForms/ShiftnetSites/MainHomepage.cs index 6e692a7..10ba809 100644 --- a/ShiftOS.WinForms/ShiftnetSites/MainHomepage.cs +++ b/ShiftOS.WinForms/ShiftnetSites/MainHomepage.cs @@ -39,49 +39,30 @@ namespace ShiftOS.WinForms.ShiftnetSites { //Get the Fundamentals List flfundamentals.Controls.Clear(); - foreach (var exe in Directory.GetFiles(Environment.CurrentDirectory)) + foreach (var type in Array.FindAll(ReflectMan.Types, t => t.GetInterfaces().Contains(typeof(IShiftnetSite)) && t.BaseType == typeof(UserControl) && Shiftorium.UpgradeAttributesUnlocked(t))) { - if (exe.EndsWith(".exe") || exe.EndsWith(".dll")) + var attrs = type.GetCustomAttributes(false); + var attribute = attrs.FirstOrDefault(x => x is ShiftnetSiteAttribute) as ShiftnetSiteAttribute; + if (attribute != null) { - try + if (attrs.OfType().Any()) { - var asm = Assembly.LoadFile(exe); - foreach (var type in asm.GetTypes()) + var dash = new Label(); + dash.Text = " - "; + dash.AutoSize = true; + flfundamentals.Controls.Add(dash); + dash.Show(); + var link = new LinkLabel(); + link.Text = attribute.Name; + link.Click += (o, a) => { - if (type.GetInterfaces().Contains(typeof(IShiftnetSite))) - { - if (type.BaseType == typeof(UserControl)) - { - var attribute = type.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftnetSiteAttribute) as ShiftnetSiteAttribute; - if (attribute != null) - { - if (Shiftorium.UpgradeAttributesUnlocked(type)) - { - if (type.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftnetFundamentalAttribute) != null) - { - var dash = new Label(); - dash.Text = " - "; - dash.AutoSize = true; - flfundamentals.Controls.Add(dash); - dash.Show(); - var link = new LinkLabel(); - link.Text = attribute.Name; - link.Click += (o, a) => - { - GoToUrl?.Invoke(attribute.Url); - }; - flfundamentals.Controls.Add(link); - flfundamentals.SetFlowBreak(link, true); - link.Show(); - link.LinkColor = SkinEngine.LoadedSkin.ControlTextColor; - } - } - } - } - } - } + GoToUrl?.Invoke(attribute.Url); + }; + flfundamentals.Controls.Add(link); + flfundamentals.SetFlowBreak(link, true); + link.Show(); + link.LinkColor = SkinEngine.LoadedSkin.ControlTextColor; } - catch { } } } diff --git a/ShiftOS.WinForms/ShiftnetSites/ShiftSoft_Ping.cs b/ShiftOS.WinForms/ShiftnetSites/ShiftSoft_Ping.cs index 1593117..9b1c3b4 100644 --- a/ShiftOS.WinForms/ShiftnetSites/ShiftSoft_Ping.cs +++ b/ShiftOS.WinForms/ShiftnetSites/ShiftSoft_Ping.cs @@ -34,53 +34,38 @@ namespace ShiftOS.WinForms.ShiftnetSites public void SetupListing() { fllist.Controls.Clear(); - foreach(var exec in Directory.GetFiles(Environment.CurrentDirectory)) + foreach (var type in Array.FindAll(ReflectMan.Types, t => t.GetInterfaces().Contains(typeof(IShiftnetSite)))) { - if(exec.ToLower().EndsWith(".exe") || exec.ToLower().EndsWith(".dll")) + var attr = type.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftnetSiteAttribute) as ShiftnetSiteAttribute; + if (attr != null) { - try + if (attr.Url.StartsWith("shiftnet/")) { - var asm = Assembly.LoadFile(exec); - var types = asm.GetTypes(); - foreach (var type in types) + var lnk = new LinkLabel(); + lnk.LinkColor = SkinEngine.LoadedSkin.ControlTextColor; + lnk.Text = attr.Name; + var desc = new Label(); + desc.AutoSize = true; + lnk.AutoSize = true; + desc.MaximumSize = new Size(this.Width / 3, 0); + desc.Text = attr.Description; + desc.Padding = new Padding { - if (type.GetInterfaces().Contains(typeof(IShiftnetSite))) - { - var attr = type.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftnetSiteAttribute) as ShiftnetSiteAttribute; - if (attr != null) - { - if (attr.Url.StartsWith("shiftnet/")) - { - var lnk = new LinkLabel(); - lnk.LinkColor = SkinEngine.LoadedSkin.ControlTextColor; - lnk.Text = attr.Name; - var desc = new Label(); - desc.AutoSize = true; - lnk.AutoSize = true; - desc.MaximumSize = new Size(this.Width / 3, 0); - desc.Text = attr.Description; - desc.Padding = new Padding - { - Bottom = 25, - Top = 0, - Left = 10, - Right = 10 - }; - lnk.Click += (o, a) => - { - GoToUrl?.Invoke(attr.Url); - }; - fllist.Controls.Add(lnk); - fllist.Controls.Add(desc); - ControlManager.SetupControls(lnk); - lnk.Show(); - desc.Show(); - } - } - } - } + Bottom = 25, + Top = 0, + Left = 10, + Right = 10 + }; + lnk.Click += (o, a) => + { + GoToUrl?.Invoke(attr.Url); + }; + fllist.Controls.Add(lnk); + fllist.Controls.Add(desc); + ControlManager.SetupControls(lnk); + lnk.Show(); + desc.Show(); } - catch { } } } } diff --git a/ShiftOS.WinForms/WidgetManager.cs b/ShiftOS.WinForms/WidgetManager.cs index fec09f9..81a97af 100644 --- a/ShiftOS.WinForms/WidgetManager.cs +++ b/ShiftOS.WinForms/WidgetManager.cs @@ -16,36 +16,12 @@ namespace ShiftOS.WinForms { public static Dictionary GetAllWidgetTypes() { - Dictionary types = new Dictionary(); - foreach(var exe in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - if(exe.EndsWith(".exe") || exe.EndsWith(".dll")) - { - try - { - var asm = Assembly.LoadFile(exe); - foreach(var type in asm.GetTypes()) - { - if (type.GetInterfaces().Contains(typeof(IDesktopWidget))) - { - if (Shiftorium.UpgradeAttributesUnlocked(type)) - { - foreach (var attrib in type.GetCustomAttributes(false)) - { - if (attrib is DesktopWidgetAttribute) - { - var dw = attrib as DesktopWidgetAttribute; - types.Add(dw, type); - } - } - } - } - } - } - catch { } - } - } - return types; + var ret = new Dictionary(); + var types = Array.FindAll(ReflectMan.Types, t => t.GetInterfaces().Contains(typeof(IDesktopWidget)) && Shiftorium.UpgradeAttributesUnlocked(t)); + foreach (var type in types) + foreach (var attrib in Array.FindAll(type.GetCustomAttributes(false), a => a is DesktopWidgetAttribute)) + ret.Add(attrib as DesktopWidgetAttribute, type); + return ret; } internal static void SaveDetails(Type type, WidgetDetails location) diff --git a/ShiftOS_TheReturn/AppLauncherDaemon.cs b/ShiftOS_TheReturn/AppLauncherDaemon.cs index 716a6a3..c259556 100644 --- a/ShiftOS_TheReturn/AppLauncherDaemon.cs +++ b/ShiftOS_TheReturn/AppLauncherDaemon.cs @@ -63,55 +63,16 @@ namespace ShiftOS.Engine { List win = new List(); - foreach (var asmExec in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) + foreach (var type in Array.FindAll(ReflectMan.Types, t => t.GetInterfaces().Contains(typeof(IShiftOSWindow)) && Shiftorium.UpgradeAttributesUnlocked(t))) { - if (asmExec.EndsWith(".dll") | asmExec.EndsWith(".exe")) - { - try - { - var asm = Assembly.LoadFrom(asmExec); - - if (asm.GetReferencedAssemblies().Contains("ShiftOS.Engine") || asm.FullName.Contains("ShiftOS.Engine")) + foreach (var attr in type.GetCustomAttributes(false)) + if (!(attr is MultiplayerOnlyAttribute && !KernelWatchdog.MudConnected)) + if (attr is LauncherAttribute) { - foreach (var type in asm.GetTypes()) - { - if (type.GetInterfaces().Contains(typeof(IShiftOSWindow))) - { - bool isAllowed = true; - foreach (var attr in type.GetCustomAttributes(false)) - { - if(attr is MultiplayerOnlyAttribute) - { - if(KernelWatchdog.MudConnected == false) - { - isAllowed = false; - - } - } - if (isAllowed == true) - { - if (attr is LauncherAttribute) - { - if (Shiftorium.UpgradeAttributesUnlocked(type)) - { - var launch = attr as LauncherAttribute; - if (launch.UpgradeInstalled) - { - win.Add(new LauncherItem { DisplayData = launch, LaunchType = type }); - } - } - } - } - } - } - } + var launch = attr as LauncherAttribute; + if (launch.UpgradeInstalled) + win.Add(new LauncherItem { DisplayData = launch, LaunchType = type }); } - } - catch - { - - } - } } foreach(var file in Utils.GetFiles(Paths.GetPath("applauncher"))) diff --git a/ShiftOS_TheReturn/AppearanceManager.cs b/ShiftOS_TheReturn/AppearanceManager.cs index e244b77..76060dd 100644 --- a/ShiftOS_TheReturn/AppearanceManager.cs +++ b/ShiftOS_TheReturn/AppearanceManager.cs @@ -58,25 +58,7 @@ namespace ShiftOS.Engine //HEY LETS FIND THE WINDOWS public static IEnumerable GetAllWindowTypes() { - List types = new List(); - foreach(var file in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - // hey if a thing is an exe or a dll show up plz kthx - if(file.EndsWith(".exe") || file.EndsWith(".dll")) - { - try - { - var asm = Assembly.LoadFile(file); - foreach(var type in asm.GetTypes()) - { - if (type.GetInterfaces().Contains(typeof(IShiftOSWindow))) - types.Add(type); - } - } - catch { } - } - } - return types; + return Array.FindAll(ReflectMan.Types, t => t.GetInterfaces().Contains(typeof(IShiftOSWindow))); } // hey you know that window we just made appear? well give it its title diff --git a/ShiftOS_TheReturn/Commands.cs b/ShiftOS_TheReturn/Commands.cs index f37bcb3..da4fb29 100644 --- a/ShiftOS_TheReturn/Commands.cs +++ b/ShiftOS_TheReturn/Commands.cs @@ -771,84 +771,41 @@ shiftorium.buy{{upgrade:""{upg.ID}""}}"); { var app = args["app"] as string; //ANNND now we start reflecting... - foreach (var asmExec in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) + foreach (var type in Array.FindAll(ReflectMan.Types, t => t.BaseType == typeof(UserControl))) { - if (asmExec.EndsWith(".exe") || asmExec.EndsWith(".dll")) + var attr = type.GetCustomAttributes(false).FirstOrDefault(a => a is WinOpenAttribute && app == (a as WinOpenAttribute).ID); + if (attr != null) { - var asm = Assembly.LoadFile(asmExec); - try + if (SaveSystem.CurrentSave.Upgrades.ContainsKey(app)) { - foreach (var type in asm.GetTypes()) + if (Shiftorium.UpgradeInstalled(app)) { - if (type.BaseType == typeof(UserControl)) - { - foreach (var attr in type.GetCustomAttributes(false)) - { - if (attr is WinOpenAttribute) - { - if (app == (attr as WinOpenAttribute).ID) - { - if (SaveSystem.CurrentSave.Upgrades.ContainsKey(app)) - { - if (Shiftorium.UpgradeInstalled(app)) - { - IShiftOSWindow frm = Activator.CreateInstance(type) as IShiftOSWindow; - AppearanceManager.SetupWindow(frm); - return true; - } - else - { - throw new Exception($"{app} was not found on your system! Try looking in the shiftorium..."); - } - } - else - { - IShiftOSWindow frm = Activator.CreateInstance(type) as IShiftOSWindow; - AppearanceManager.SetupWindow(frm); - return true; - } - } - } - } - } + IShiftOSWindow frm = Activator.CreateInstance(type) as IShiftOSWindow; + AppearanceManager.SetupWindow(frm); + return true; + } + else + { + throw new Exception($"{app} was not found on your system! Try looking in the shiftorium..."); } } - catch { } - + else + { + IShiftOSWindow frm = Activator.CreateInstance(type) as IShiftOSWindow; + AppearanceManager.SetupWindow(frm); + return true; + } } } } else { - foreach (var asmExec in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - if (asmExec.EndsWith(".exe") || asmExec.EndsWith(".dll")) - { - try - { - var asm = Assembly.LoadFile(asmExec); - - foreach (var type in asm.GetTypes()) - { - if (type.GetInterfaces().Contains(typeof(IShiftOSWindow))) - { - foreach (var attr in type.GetCustomAttributes(false)) - { - if (attr is WinOpenAttribute) - { - if (Shiftorium.UpgradeAttributesUnlocked(type)) - { - Console.WriteLine("win.open{app:\"" + (attr as WinOpenAttribute).ID + "\"}"); - } - } - } - } - } - } - catch { } - } - } + + foreach (var type in Array.FindAll(ReflectMan.Types, t => t.GetInterfaces().Contains(typeof(IShiftOSWindow)) && Shiftorium.UpgradeAttributesUnlocked(t))) + foreach (var attr in Array.FindAll(type.GetCustomAttributes(false), a => a is WinOpenAttribute)) + if (Shiftorium.UpgradeAttributesUnlocked(type)) + Console.WriteLine("win.open{app:\"" + (attr as WinOpenAttribute).ID + "\"}"); return true; diff --git a/ShiftOS_TheReturn/NotificationDaemon.cs b/ShiftOS_TheReturn/NotificationDaemon.cs index 0725782..a532466 100644 --- a/ShiftOS_TheReturn/NotificationDaemon.cs +++ b/ShiftOS_TheReturn/NotificationDaemon.cs @@ -41,26 +41,7 @@ namespace ShiftOS.Engine /// An array of s containing the found objects. public static Type[] GetAllStatusIcons() { - List lst = new List(); - foreach(var exec in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - if(exec.ToLower().EndsWith(".exe") || exec.ToLower().EndsWith(".dll")) - { - try - { - var asm = Assembly.LoadFile(exec); - foreach(var type in asm.GetTypes().Where(x => x.GetInterfaces().Contains(typeof(IStatusIcon)))) - { - if (Shiftorium.UpgradeAttributesUnlocked(type)) - { - lst.Add(type); - } - } - } - catch { } - } - } - return lst.ToArray(); + return Array.FindAll(ReflectMan.Types, x => x.GetInterfaces().Contains(typeof(IStatusIcon)) && Shiftorium.UpgradeAttributesUnlocked(x)); } diff --git a/ShiftOS_TheReturn/ReflectMan.cs b/ShiftOS_TheReturn/ReflectMan.cs new file mode 100644 index 0000000..a0ead60 --- /dev/null +++ b/ShiftOS_TheReturn/ReflectMan.cs @@ -0,0 +1,80 @@ +/* + * MIT License + * + * Copyright (c) 2017 Michael VanOverbeek and ShiftOS devs + * + * 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: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * 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. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace ShiftOS.Engine +{ + public static class ReflectMan + { + private static Assembly[] asms = null; + public static Assembly[] Asms + { + get + { + if (asms == null) + LoadAssemblies(); + return asms; + } + } + + private static Type[] types = null; + public static Type[] Types + { + get + { + if (types == null) + FindTypes(); + return types; + } + } + + private static void LoadAssemblies() + { + var ret = new List(); + foreach (var exe in Array.FindAll(System.IO.Directory.GetFiles(Environment.CurrentDirectory), n => n.EndsWith(".exe") || n.EndsWith(".dll"))) + try + { + var asm = Assembly.LoadFile(exe); + if (asm.GetReferencedAssemblies().Contains("ShiftOS.Engine") || asm.FullName.Contains("ShiftOS.Engine")) + ret.Add(asm); + } + catch { } // probably not a managed assembly + asms = ret.ToArray(); + } + + private static void FindTypes() + { + var ret = new List(); + foreach (var asm in Asms) + ret.AddRange(asm.GetTypes()); + types = ret.ToArray(); + } + } +} diff --git a/ShiftOS_TheReturn/Scripting.cs b/ShiftOS_TheReturn/Scripting.cs index 5021f50..081a6ae 100644 --- a/ShiftOS_TheReturn/Scripting.cs +++ b/ShiftOS_TheReturn/Scripting.cs @@ -205,55 +205,14 @@ end"); //This temporary proxy() method will be used by the API prober. Lua.proxy = new Func((objName) => { - foreach (var f in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - if (f.EndsWith(".exe") || f.EndsWith(".dll")) - { - try - { - - var asm = Assembly.LoadFile(f); - foreach (var type in asm.GetTypes()) - { - if (type.Name == objName) - { - dynamic dynObj = Activator.CreateInstance(type); - return dynObj; - } - - } - } - catch { } - } - } + dynamic dynObj = ReflectMan.Types.FirstOrDefault(t => t.Name == objName); + if (dynObj != null) + return dynObj; throw new Exception("{CLASS_NOT_FOUND}"); }); - - foreach (var f in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - if (f.EndsWith(".exe") || f.EndsWith(".dll")) - { - try - { - var thisasm = Assembly.LoadFile(f); - foreach (var type in thisasm.GetTypes()) - { - foreach (var attr in type.GetCustomAttributes(false)) - { - if (attr is ExposedAttribute) - { - var eattr = attr as ExposedAttribute; - Lua($"{eattr.Name} = proxy(\"{type.Name}\")"); - } - } - } - } - catch - { - - } - } - } + foreach (var type in ReflectMan.Types) + foreach (var attr in Array.FindAll(type.GetCustomAttributes(false), a => a is ExposedAttribute)) + Lua($"{(attr as ExposedAttribute).Name} = proxy(\"{type.Name}\")"); //Now we can null out the proxy() method as it can cause security risks. Lua.isRunning = new Func(() => { return this.Running; }); Lua.proxy = null; diff --git a/ShiftOS_TheReturn/ServerManager.cs b/ShiftOS_TheReturn/ServerManager.cs index be4f086..e6baa9a 100644 --- a/ShiftOS_TheReturn/ServerManager.cs +++ b/ShiftOS_TheReturn/ServerManager.cs @@ -110,32 +110,19 @@ Ping: {ServerManager.DigitalSocietyPing} ms { string[] split = msg.GUID.Split('|'); bool finished = false; - foreach (var exec in Directory.GetFiles(Environment.CurrentDirectory)) - { - if(exec.ToLower().EndsWith(".exe") || exec.ToLower().EndsWith(".dll")) + if (split[0] == SaveSystem.CurrentSave.SystemName) + foreach(var type in Array.FindAll(ReflectMan.Types, x => x.GetInterfaces().Contains(typeof(Server)) && Shiftorium.UpgradeAttributesUnlocked(x))) { - try + var attrib = type.GetCustomAttributes().FirstOrDefault(x => x is ServerAttribute) as ServerAttribute; + if(attrib != null) { - var asm = Assembly.LoadFile(exec); - foreach(var type in asm.GetTypes().Where(x => x.GetInterfaces().Contains(typeof(Server)))) + if(split[1] == attrib.Port.ToString()) { - var attrib = type.GetCustomAttributes().FirstOrDefault(x => x is ServerAttribute) as ServerAttribute; - if(attrib != null) - { - if(split[0] == SaveSystem.CurrentSave.SystemName && split[1] == attrib.Port.ToString()) - { - if (Shiftorium.UpgradeAttributesUnlocked(type)) - { - type.GetMethods(BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(x => x.Name == "MessageReceived")?.Invoke(Activator.CreateInstance(type), null); - finished = true; - } - } - } + type.GetMethods(BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(x => x.Name == "MessageReceived")?.Invoke(Activator.CreateInstance(type), null); + finished = true; } } - catch { } } - } if (finished == false) { Forward(split[2], "Error", $"{split[0]}:{split[1]}: connection refused"); diff --git a/ShiftOS_TheReturn/ShiftOS.Engine.csproj b/ShiftOS_TheReturn/ShiftOS.Engine.csproj index f70c41e..39299fd 100644 --- a/ShiftOS_TheReturn/ShiftOS.Engine.csproj +++ b/ShiftOS_TheReturn/ShiftOS.Engine.csproj @@ -123,6 +123,7 @@ True Resources.resx + diff --git a/ShiftOS_TheReturn/Shiftorium.cs b/ShiftOS_TheReturn/Shiftorium.cs index 7faf336..0362566 100644 --- a/ShiftOS_TheReturn/Shiftorium.cs +++ b/ShiftOS_TheReturn/Shiftorium.cs @@ -214,23 +214,11 @@ namespace ShiftOS.Engine { upgDb = new List(); //Now we probe for ShiftoriumUpgradeAttributes for mods. - foreach (var file in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) - { - if (file.EndsWith(".exe") || file.EndsWith(".dll")) - { - try - { - var asm = Assembly.LoadFile(file); - foreach (var type in asm.GetTypes()) + foreach (var type in ReflectMan.Types) { if (type.GetInterfaces().Contains(typeof(IShiftoriumProvider))) - { - if (type.GetCustomAttributes().FirstOrDefault(x => x is ShiftoriumProviderAttribute) != null) - { - var _p = Activator.CreateInstance(type, null) as IShiftoriumProvider; - upgDb.AddRange(_p.GetDefaults()); - } - } + if (type.GetCustomAttributes().Any(x => x is ShiftoriumProviderAttribute)) + upgDb.AddRange((Activator.CreateInstance(type, null) as IShiftoriumProvider).GetDefaults()); ShiftoriumUpgradeAttribute attrib = type.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftoriumUpgradeAttribute) as ShiftoriumUpgradeAttribute; @@ -310,10 +298,6 @@ namespace ShiftOS.Engine } } - } - catch { } - } - } diff --git a/ShiftOS_TheReturn/Skinning.cs b/ShiftOS_TheReturn/Skinning.cs index d5114c5..ab2d6b1 100644 --- a/ShiftOS_TheReturn/Skinning.cs +++ b/ShiftOS_TheReturn/Skinning.cs @@ -242,38 +242,16 @@ namespace ShiftOS.Engine /// The resulting icon image. public static Image GetDefaultIcon(string id) { - if (_iconProber == null) + if (_iconProber != null) { - return new Bitmap(16, 16); - } - else - { - foreach (var f in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) + foreach (var type in Array.FindAll(ReflectMan.Types, t => t.Name == id)) { - if (f.EndsWith(".exe") || f.EndsWith(".dll")) - { - try - { - var asm = Assembly.LoadFile(f); - foreach (var type in asm.GetTypes()) - { - if (type.Name == id) - { - foreach (var attr in type.GetCustomAttributes(true)) - { - if (attr is DefaultIconAttribute) - { - return _iconProber.GetIcon(attr as DefaultIconAttribute); - } - } - } - } - } - catch { } - } + var attr = Array.Find(type.GetCustomAttributes(true), a => a is DefaultIconAttribute); + if (attr != null) + return _iconProber.GetIcon(attr as DefaultIconAttribute); } - return new Bitmap(16, 16); } + return new Bitmap(16, 16); } /// diff --git a/ShiftOS_TheReturn/Story.cs b/ShiftOS_TheReturn/Story.cs index e44d2be..c01c055 100644 --- a/ShiftOS_TheReturn/Story.cs +++ b/ShiftOS_TheReturn/Story.cs @@ -134,55 +134,42 @@ namespace ShiftOS.Engine /// The storyline ID to start. public static void Start(string stid) { - foreach (var exec in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) + if (SaveSystem.CurrentSave.StoriesExperienced == null) + SaveSystem.CurrentSave.StoriesExperienced = new List(); + foreach (var type in ReflectMan.Types) { - if(exec.EndsWith(".exe") || exec.EndsWith(".dll")) + foreach (var mth in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { - try + foreach (var attrib in Array.FindAll(mth.GetCustomAttributes(false), a => a is StoryAttribute)) { - if (SaveSystem.CurrentSave.StoriesExperienced == null) - SaveSystem.CurrentSave.StoriesExperienced = new List(); - var asm = Assembly.LoadFile(exec); - foreach(var type in asm.GetTypes()) + var story = attrib as StoryAttribute; + if (story.StoryID == stid) { - foreach(var mth in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) + new Thread(() => { - foreach(var attrib in mth.GetCustomAttributes(false)) + Context = new Engine.StoryContext { - if(attrib is StoryAttribute) - { - var story = attrib as StoryAttribute; - if(story.StoryID == stid) - { - new Thread(() => - { - Context = new Engine.StoryContext - { - Id = stid, - Method = mth, - AutoComplete = true, - }; - SaveSystem.CurrentSave.PickupPoint = Context.Id; - Context.OnComplete += () => - { - StoryComplete?.Invoke(stid); - SaveSystem.CurrentSave.PickupPoint = null; - }; - mth.Invoke(null, null); - if (Context.AutoComplete) - { - Context.MarkComplete(); - } - }).Start(); - return; - } - } + Id = stid, + Method = mth, + AutoComplete = true, + }; + SaveSystem.CurrentSave.PickupPoint = Context.Id; + Context.OnComplete += () => + { + StoryComplete?.Invoke(stid); + SaveSystem.CurrentSave.PickupPoint = null; + }; + mth.Invoke(null, null); + if (Context.AutoComplete) + { + Context.MarkComplete(); } - } + }).Start(); + return; } } - catch (Exception ex) { throw ex; } } + } #if DEBUG throw new ArgumentException("Story ID not found: " + stid + " - Talk to Michael. NOW."); diff --git a/ShiftOS_TheReturn/TerminalBackend.cs b/ShiftOS_TheReturn/TerminalBackend.cs index 09ef3d6..81ea971 100644 --- a/ShiftOS_TheReturn/TerminalBackend.cs +++ b/ShiftOS_TheReturn/TerminalBackend.cs @@ -295,54 +295,40 @@ namespace ShiftOS.Engine public static void PopulateTerminalCommands() { Commands = new List(); - foreach(var exec in System.IO.Directory.GetFiles(Environment.CurrentDirectory)) + foreach(var type in ReflectMan.Types) { - if(exec.ToLower().EndsWith(".exe") || exec.ToLower().EndsWith(".dll")) + var ns = type.GetCustomAttributes(false).FirstOrDefault(x => x is Namespace) as Namespace; + if(ns != null) { - try + foreach(var mth in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { - var asm = Assembly.LoadFile(exec); - foreach(var type in asm.GetTypes()) + var cmd = mth.GetCustomAttributes(false).FirstOrDefault(x => x is Command); + if(cmd != null) { - var ns = type.GetCustomAttributes(false).FirstOrDefault(x => x is Namespace) as Namespace; - if(ns != null) + var tc = new TerminalCommand(); + tc.RequiresElevation = !(type.GetCustomAttributes(false).FirstOrDefault(x => x is KernelModeAttribute) == null); + + tc.NamespaceInfo = ns; + + tc.CommandInfo = cmd as Command; + tc.RequiresElevation = tc.RequiresElevation || !(mth.GetCustomAttributes(false).FirstOrDefault(x => x is KernelModeAttribute) == null); + tc.RequiredArguments = new List(); + foreach (var arg in mth.GetCustomAttributes(false).Where(x=>x is RequiresArgument)) { - foreach(var mth in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) - { - var cmd = mth.GetCustomAttributes(false).FirstOrDefault(x => x is Command); - if(cmd != null) - { - var tc = new TerminalCommand(); - tc.RequiresElevation = !(type.GetCustomAttributes(false).FirstOrDefault(x => x is KernelModeAttribute) == null); - - tc.NamespaceInfo = ns; - - tc.CommandInfo = cmd as Command; - tc.RequiresElevation = tc.RequiresElevation || !(mth.GetCustomAttributes(false).FirstOrDefault(x => x is KernelModeAttribute) == null); - tc.RequiredArguments = new List(); - foreach (var arg in mth.GetCustomAttributes(false).Where(x=>x is RequiresArgument)) - { - var rarg = arg as RequiresArgument; - tc.RequiredArguments.Add(rarg.argument); - } - var rupg = mth.GetCustomAttributes(false).FirstOrDefault(x => x is RequiresUpgradeAttribute) as RequiresUpgradeAttribute; - if (rupg != null) - tc.Dependencies = rupg.Upgrade; - else - tc.Dependencies = ""; - tc.CommandType = type; - tc.CommandHandler = mth; - if (!Commands.Contains(tc)) - Commands.Add(tc); - } - } + var rarg = arg as RequiresArgument; + tc.RequiredArguments.Add(rarg.argument); } + var rupg = mth.GetCustomAttributes(false).FirstOrDefault(x => x is RequiresUpgradeAttribute) as RequiresUpgradeAttribute; + if (rupg != null) + tc.Dependencies = rupg.Upgrade; + else + tc.Dependencies = ""; + tc.CommandType = type; + tc.CommandHandler = mth; + if (!Commands.Contains(tc)) + Commands.Add(tc); } } - catch(Exception e) - { - Console.WriteLine("[termdb] Error: " + e.ToString()); - } } } Console.WriteLine("[termdb] " + Commands.Count + " commands found."); -- cgit v1.2.3 From 79fe2101aef62b744b150203dee6953b0d17f5aa Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 16 Jun 2017 20:36:43 -0400 Subject: Get rid of namespaces in commands. --- ModLauncher/Program.cs | 11 - ShiftOS.Modding.VB.LegacySkinConverter/Module1.vb | 1 - ShiftOS.Modding.VirtualMachine/Form1.cs | 1 - .../Applications/CoherenceOverlay.Designer.cs | 61 -- ShiftOS.WinForms/Applications/CoherenceOverlay.cs | 123 ---- ShiftOS.WinForms/Applications/Downloader.cs | 1 - ShiftOS.WinForms/Applications/Pong.cs | 25 +- ShiftOS.WinForms/Commands.cs | 299 --------- ShiftOS.WinForms/HackerCommands.cs | 723 +-------------------- ShiftOS.WinForms/OobeStory.cs | 1 - ShiftOS.WinForms/Servers/RemoteTerminalServer.cs | 1 - ShiftOS.WinForms/ShiftOS.WinForms.csproj | 6 - ShiftOS.WinForms/SkinCommands.cs | 1 - ShiftOS.WinForms/TestCommandsForUpgrades.cs | 22 +- ShiftOS.WinForms/TrailerCommands.cs | 48 -- ShiftOS.WinForms/WinformsDesktop.cs | 1 - ShiftOS_TheReturn/Command.cs | 36 - ShiftOS_TheReturn/Commands.cs | 274 +------- ShiftOS_TheReturn/PythonAPI.cs | 1 - ShiftOS_TheReturn/ReflectMan.cs | 1 - ShiftOS_TheReturn/TerminalBackend.cs | 66 +- ShiftOS_TheReturn/UserManagementCommands.cs | 2 - 22 files changed, 66 insertions(+), 1639 deletions(-) delete mode 100644 ShiftOS.WinForms/Applications/CoherenceOverlay.Designer.cs delete mode 100644 ShiftOS.WinForms/Applications/CoherenceOverlay.cs (limited to 'ShiftOS.WinForms/HackerCommands.cs') diff --git a/ModLauncher/Program.cs b/ModLauncher/Program.cs index 4b99cf5..4637b4e 100644 --- a/ModLauncher/Program.cs +++ b/ModLauncher/Program.cs @@ -32,7 +32,6 @@ using ShiftOS.Engine; namespace ModLauncher { - [Namespace("modlauncher")] public static class Program { /// @@ -43,15 +42,5 @@ namespace ModLauncher { ShiftOS.WinForms.Program.Main(); } - - [Command("throwcrash")] - public static bool ThrowCrash() - { - new Thread(() => - { - throw new Exception("User triggered crash using modlauncher.throwcrash command."); - }).Start(); - return true; - } } } diff --git a/ShiftOS.Modding.VB.LegacySkinConverter/Module1.vb b/ShiftOS.Modding.VB.LegacySkinConverter/Module1.vb index 161012d..3a2e106 100644 --- a/ShiftOS.Modding.VB.LegacySkinConverter/Module1.vb +++ b/ShiftOS.Modding.VB.LegacySkinConverter/Module1.vb @@ -14,7 +14,6 @@ Module Module1 End Module - Public Class SkinConverterCommands diff --git a/ShiftOS.Modding.VirtualMachine/Form1.cs b/ShiftOS.Modding.VirtualMachine/Form1.cs index 5b6b047..1615091 100644 --- a/ShiftOS.Modding.VirtualMachine/Form1.cs +++ b/ShiftOS.Modding.VirtualMachine/Form1.cs @@ -154,7 +154,6 @@ namespace ShiftOS.Modding.VirtualMachine } } - [Namespace("svm")] public static class Compiler { public static byte[] Compile(string prg) diff --git a/ShiftOS.WinForms/Applications/CoherenceOverlay.Designer.cs b/ShiftOS.WinForms/Applications/CoherenceOverlay.Designer.cs deleted file mode 100644 index 0764059..0000000 --- a/ShiftOS.WinForms/Applications/CoherenceOverlay.Designer.cs +++ /dev/null @@ -1,61 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2017 Michael VanOverbeek and ShiftOS devs - * - * 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: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * 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. - */ - -namespace ShiftOS.WinForms.Applications -{ - partial class CoherenceOverlay - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - } - - #endregion - } -} diff --git a/ShiftOS.WinForms/Applications/CoherenceOverlay.cs b/ShiftOS.WinForms/Applications/CoherenceOverlay.cs deleted file mode 100644 index 1bfc8e8..0000000 --- a/ShiftOS.WinForms/Applications/CoherenceOverlay.cs +++ /dev/null @@ -1,123 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2017 Michael VanOverbeek and ShiftOS devs - * - * 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: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * 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. - */ - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using ShiftOS.Engine; -using System.Threading; - -namespace ShiftOS.WinForms.Applications -{ - public partial class CoherenceOverlay : UserControl, IShiftOSWindow - { - public CoherenceOverlay(IntPtr handle, CoherenceCommands.RECT rect) - { - InitializeComponent(); - this.Load += (o, a) => - { - try - { - int left = this.ParentForm.Left; - int top = this.ParentForm.Top; - int oldwidth = this.ParentForm.Width; - int oldheight = this.ParentForm.Height; - - var t = new Thread(new ThreadStart(() => - { - while (CoherenceCommands.GetWindowRect(handle, ref rect)) - { - - if (left != rect.Left - SkinEngine.LoadedSkin.LeftBorderWidth) - { - this.Invoke(new Action(() => - { - this.ParentForm.Left = rect.Left - SkinEngine.LoadedSkin.LeftBorderWidth; - left = rect.Left - SkinEngine.LoadedSkin.LeftBorderWidth; - })); - } - if (top != rect.Top - SkinEngine.LoadedSkin.TitlebarHeight) - { - this.Invoke(new Action(() => - { - - this.ParentForm.Top = rect.Top - SkinEngine.LoadedSkin.TitlebarHeight; - top = rect.Top - SkinEngine.LoadedSkin.TitlebarHeight; - })); - } - int width = (rect.Right - rect.Left) + 1; - int height = (rect.Bottom - rect.Top) + 1; - - if (oldheight != SkinEngine.LoadedSkin.TitlebarHeight + height + SkinEngine.LoadedSkin.BottomBorderWidth) - { - this.Invoke(new Action(() => - { - this.ParentForm.Height = SkinEngine.LoadedSkin.TitlebarHeight + height + SkinEngine.LoadedSkin.BottomBorderWidth; - oldheight = SkinEngine.LoadedSkin.TitlebarHeight + height + SkinEngine.LoadedSkin.BottomBorderWidth; - })); - } - if (oldwidth != SkinEngine.LoadedSkin.LeftBorderWidth + width + SkinEngine.LoadedSkin.RightBorderWidth) - { - this.Invoke(new Action(() => - { - this.ParentForm.Width = SkinEngine.LoadedSkin.LeftBorderWidth + width + SkinEngine.LoadedSkin.RightBorderWidth; - oldwidth = SkinEngine.LoadedSkin.LeftBorderWidth + width + SkinEngine.LoadedSkin.RightBorderWidth; - })); - } - } - })); - t.IsBackground = true; - t.Start(); - } - catch - { - - } - }; - } - - public void OnLoad() - { - } - - public void OnSkinLoad() - { - } - - public bool OnUnload() - { - return true; - } - - public void OnUpgrade() - { - } - } -} diff --git a/ShiftOS.WinForms/Applications/Downloader.cs b/ShiftOS.WinForms/Applications/Downloader.cs index b3d2cea..bcad56a 100644 --- a/ShiftOS.WinForms/Applications/Downloader.cs +++ b/ShiftOS.WinForms/Applications/Downloader.cs @@ -216,7 +216,6 @@ namespace ShiftOS.WinForms.Applications public int Progress { get; set; } } - [Namespace("dev")] public static class DownloaderDebugCommands { [Command("setsubscription", description ="Use to set the current shiftnet subscription.", usage ="{value:int32}")] diff --git a/ShiftOS.WinForms/Applications/Pong.cs b/ShiftOS.WinForms/Applications/Pong.cs index 87b7a93..3f06676 100644 --- a/ShiftOS.WinForms/Applications/Pong.cs +++ b/ShiftOS.WinForms/Applications/Pong.cs @@ -42,6 +42,15 @@ namespace ShiftOS.WinForms.Applications LevelComplete(); } }; +#if DEBUG + this.KeyDown += (o, a) => + { + if(a.KeyCode == Keys.D) + { + drawAiBall = !drawAiBall; + } + }; +#endif } private double ballX = 0.0f; @@ -266,11 +275,14 @@ namespace ShiftOS.WinForms.Applications ballX = 0; ballY = 0; opponentY = 0; + xVel = 1; aiBallX = 0; aiBallY = 0; doAi = true; } + private bool drawAiBall = false; + private void pnlcanvas_Paint(object sender, PaintEventArgs e) { @@ -281,11 +293,22 @@ namespace ShiftOS.WinForms.Applications ballXLocal -= ((double)paddleWidth / 2); ballYLocal -= ((double)paddleWidth / 2); + double aiballXLocal = linear(aiBallX, -1.0, 1.0, 0, pnlcanvas.Width); + double aiballYLocal = linear(aiBallY, -1.0, 1.0, 0, pnlcanvas.Height); + + aiballXLocal -= ((double)paddleWidth / 2); + aiballYLocal -= ((double)paddleWidth / 2); + e.Graphics.Clear(pnlcanvas.BackColor); + //draw the ai ball + if (drawAiBall) + e.Graphics.FillEllipse(new SolidBrush(Color.Gray), new RectangleF((float)aiballXLocal, (float)aiballYLocal, (float)paddleWidth, (float)paddleWidth)); + + //draw the ball - if(doBallCalc) + if (doBallCalc) e.Graphics.FillEllipse(new SolidBrush(pnlcanvas.ForeColor), new RectangleF((float)ballXLocal, (float)ballYLocal, (float)paddleWidth, (float)paddleWidth)); double playerYLocal = linear(playerY, -1.0, 1.0, 0, pnlcanvas.Height); diff --git a/ShiftOS.WinForms/Commands.cs b/ShiftOS.WinForms/Commands.cs index b04ffe7..e69de29 100644 --- a/ShiftOS.WinForms/Commands.cs +++ b/ShiftOS.WinForms/Commands.cs @@ -1,299 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2017 Michael VanOverbeek and ShiftOS devs - * - * 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: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * 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. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ShiftOS.Engine; -using System.IO; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Threading; -using Newtonsoft.Json; - -/// -/// Coherence commands. -/// -namespace ShiftOS.WinForms -{ - [Namespace("trm")] - public static class TerminalExtensions - { - [Command("exit")] - public static bool StopRemoting() - { - if(TerminalBackend.IsForwardingConsoleWrites == true) - { - ServerManager.SendMessage("trm_handshake_stop", $@"{{ - guid: ""{TerminalBackend.ForwardGUID}"" -}}"); - Console.WriteLine("Goodbye!"); - } - else - { - return false; - } - - return true; - } - - - [Command("setpass", true)] - [RequiresArgument("pass")] - public static bool setPass(Dictionary args) - { - SaveSystem.CurrentSave.Password = args["pass"] as string; - return true; - } - - [Command("remote", "username:,sysname:,password:", "Allows you to control a remote system on the multi-user domain given a username, password and system name.")] - [RequiresArgument("username")] - [RequiresArgument("sysname")] - [RequiresArgument("password")] - public static bool RemoteControl(Dictionary args) - { - ServerManager.SendMessage("trm_handshake_request", JsonConvert.SerializeObject(args)); - return true; - } - } - - [Namespace("coherence")] - [RequiresUpgrade("kernel_coherence")] - public static class CoherenceCommands - { - /// - /// Sets the window position. - /// - /// The window position. - /// H window. - /// H window insert after. - /// X. - /// Y. - /// Cx. - /// Cy. - /// U flags. - [DllImport("user32.dll")] - static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); - - /// - /// The HWN d TOPMOS. - /// - static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); - - /// - /// The SW p SHOWWINDO. - /// - const UInt32 SWP_SHOWWINDOW = 0x0040; - - - [DllImport("user32.dll")] - /// - /// Gets the window rect. - /// - /// The window rect. - /// H window. - /// Lp rect. - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect); - - /// - /// REC. - /// - [StructLayout(LayoutKind.Sequential)] - public struct RECT - { - public int Left; // x position of upper-left corner - public int Top; // y position of upper-left corner - public int Right; // x position of lower-right corner - public int Bottom; // y position of lower-right corner - } - - [Command("launch", "process: \"C:\\path\\to\\process\" - The process path to launch.", "Launch a process inside kernel coherence.")] - [RequiresArgument("process")] - /// - /// Launchs the app. - /// - /// The app. - /// Arguments. - public static bool LaunchApp(Dictionary args) - { - string process = args["process"].ToString(); - var prc = Process.Start(process); - StartCoherence(prc); - return true; - } - - /// - /// Starts the coherence. - /// - /// The coherence. - /// Prc. - private static void StartCoherence(Process prc) - { - RECT rct = new RECT(); - - - while (!GetWindowRect(prc.MainWindowHandle, ref rct)) - { - } - - - - AppearanceManager.Invoke(new Action(() => - { - IShiftOSWindow coherenceWindow = new Applications.CoherenceOverlay(prc.MainWindowHandle, rct); - - AppearanceManager.SetupWindow(coherenceWindow); - SetWindowPos(prc.MainWindowHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); - - //MakeExternalWindowBorderless(prc.MainWindowHandle); - })); - - } - - /// - /// The W s BORDE. - /// - const int WS_BORDER = 8388608; - - /// - /// The W s DLGFRAM. - /// - const int WS_DLGFRAME = 4194304; - - /// - /// The W s CAPTIO. - /// - const int WS_CAPTION = WS_BORDER | WS_DLGFRAME; - - /// - /// The W s SYSMEN. - /// - const int WS_SYSMENU = 524288; - - /// - /// The W s THICKFRAM. - /// - const int WS_THICKFRAME = 262144; - - /// - /// The W s MINIMIZ. - /// - const int WS_MINIMIZE = 536870912; - - /// - /// The W s MAXIMIZEBO. - /// - const int WS_MAXIMIZEBOX = 65536; - - /// - /// The GW l STYL. - /// - const int GWL_STYLE = -16; - - /// - /// The GW l EXSTYL. - /// - const int GWL_EXSTYLE = -20; - - /// - /// The W s E x DLGMODALFRAM. - /// - const int WS_EX_DLGMODALFRAME = 0x1; - - /// - /// The SW p NOMOV. - /// - const int SWP_NOMOVE = 0x2; - - /// - /// The SW p NOSIZ. - /// - const int SWP_NOSIZE = 0x1; - - /// - /// The SW p FRAMECHANGE. - /// - const int SWP_FRAMECHANGED = 0x20; - - /// - /// The M f BYPOSITIO. - /// - const uint MF_BYPOSITION = 0x400; - - /// - /// The M f REMOV. - /// - const uint MF_REMOVE = 0x1000; - - /// - /// Gets the window long. - /// - /// The window long. - /// H window. - /// N index. - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] - public static extern int GetWindowLong(IntPtr hWnd, int nIndex); - - /// - /// Sets the window long. - /// - /// The window long. - /// H window. - /// N index. - /// Dw new long. - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] - public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); - - /// - /// Sets the window position. - /// - /// The window position. - /// H window. - /// H window insert after. - /// X. - /// Y. - /// Cx. - /// Cy. - /// U flags. - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] - public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags); - public static void MakeExternalWindowBorderless(IntPtr MainWindowHandle) - { - int Style = 0; - Style = GetWindowLong(MainWindowHandle, GWL_STYLE); - Style = Style & ~WS_CAPTION; - Style = Style & ~WS_SYSMENU; - Style = Style & ~WS_THICKFRAME; - Style = Style & ~WS_MINIMIZE; - Style = Style & ~WS_MAXIMIZEBOX; - SetWindowLong(MainWindowHandle, GWL_STYLE, Style); - Style = GetWindowLong(MainWindowHandle, GWL_EXSTYLE); - SetWindowLong(MainWindowHandle, GWL_EXSTYLE, Style | WS_EX_DLGMODALFRAME); - SetWindowPos(MainWindowHandle, new IntPtr(0), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED); - } - } -} diff --git a/ShiftOS.WinForms/HackerCommands.cs b/ShiftOS.WinForms/HackerCommands.cs index dd8bde8..5f28270 100644 --- a/ShiftOS.WinForms/HackerCommands.cs +++ b/ShiftOS.WinForms/HackerCommands.cs @@ -1,722 +1 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json; -using ShiftOS.Engine; -using ShiftOS.Objects; -using ShiftOS.Objects.ShiftFS; -using ShiftOS.WinForms.Applications; -using static ShiftOS.Objects.ShiftFS.Utils; - -namespace ShiftOS.WinForms -{ - [Namespace("puppy")] - [RequiresUpgrade("hacker101_deadaccts")] - [KernelMode] - public static class KernelPuppyCommands - { - [Command("clear", true)] - public static bool ClearLogs() - { - WriteAllText("0:/system/data/kernel.log", ""); - Console.WriteLine(" logs cleared successfully."); - return true; - } - } - - [Namespace("krnl")] - public static class KernelCommands - { - [Command("control", true)] - [RequiresArgument("pass")] - public static bool Control(Dictionary args) - { - if(args["pass"].ToString() == ServerManager.thisGuid.ToString()) - { - KernelWatchdog.Log("warn", "User has breached the kernel."); - KernelWatchdog.EnterKernelMode(); - TerminalBackend.PrintPrompt(); - } - return true; - } - - [Command("lock_session")] - [KernelMode] - public static bool LeaveControl() - { - KernelWatchdog.Log("inf", "User has left the kernel-mode session."); - KernelWatchdog.LeaveKernelMode(); - KernelWatchdog.MudConnected = true; - return true; - } - } - - [Namespace("hacker101")] - [RequiresUpgrade("hacker101_deadaccts")] - public static class HackerCommands - { - private static void writeSlow(string text) - { - ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow; - ConsoleEx.Bold = false; - ConsoleEx.Italic = false; - Console.Write("["); - ConsoleEx.ForegroundColor = ConsoleColor.Magenta; - ConsoleEx.Bold = true; - Console.Write("hacker101"); - ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow; - ConsoleEx.Italic = true; - Console.Write("@"); - ConsoleEx.ForegroundColor = ConsoleColor.White; - Console.Write("undisclosed"); - ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow; - ConsoleEx.Bold = false; - ConsoleEx.Italic = false; - Console.Write("]: "); - Thread.Sleep(850); - Console.WriteLine(text); - Thread.Sleep(4000); - } - - [Story("hacker101_deadaccts")] - public static void DeadAccountsStory() - { - if (!terminalIsOpen()) - { - AppearanceManager.SetupWindow(new Terminal()); - } - - var t = new Thread(() => - { - Console.WriteLine("[sys@mud]: Warning: User connecting to system..."); - Thread.Sleep(75); - Console.WriteLine("[sys@mud]: UBROADCAST: Username: hacker101 - Sysname: undisclosed"); - Thread.Sleep(50); - Console.Write("--locking mud connection resources..."); - Thread.Sleep(50); - Console.WriteLine("...done."); - Console.Write("--locking user input... "); - Thread.Sleep(75); - TerminalBackend.PrefixEnabled = false; - TerminalBackend.InStory = true; - Console.WriteLine("...done."); - - Thread.Sleep(2000); - writeSlow($"Hello there, fellow multi-user domain user."); - writeSlow("My name, as you can tell, is hacker101."); - writeSlow("And yours must be... don't say it... it's " + SaveSystem.CurrentUser.Username + "@" + SaveSystem.CurrentSave.SystemName + ", right?"); - writeSlow("Of course it is."); - writeSlow("And I bet you 10,000 Codepoints that you have... " + SaveSystem.CurrentSave.Codepoints.ToString() + " Codepoints."); - writeSlow("Oh, and how much upgrades have you installed since you first started using ShiftOS?"); - writeSlow("That would be... uhh... " + SaveSystem.CurrentSave.CountUpgrades().ToString() + "."); - writeSlow("I'm probably freaking you out right now. You are probably thinking that you're unsafe and need to lock yourself down."); - writeSlow("But, don't worry, I mean no harm."); - writeSlow("In fact, I am a multi-user domain safety activist and security professional."); - writeSlow("I need your help with something."); - writeSlow("Inside the multi-user domain, every now and then these 'dead' user accounts pop up."); - writeSlow("They're infesting everything. They're in every legion, they infest chatrooms, and they take up precious hard drive space."); - writeSlow("Eventually there's going to be tons of them just sitting there taking over the MUD. We can't have that."); - writeSlow("It sounds like a conspiracy theory indeed, but it's true, in fact, these dead accounts hold some valuable treasures."); - writeSlow("I'm talking Codepoints, skins, documents, the possibilities are endless."); - writeSlow("I'm going to execute a quick sys-script that will show you how you can help get rid of these accounts, and also gain some valuable resources to help you on your digital frontier."); - writeSlow("This script will also show you the fundamentals of security exploitation and theft of resources - which if you want to survive in the multi-user domain is paramount."); - writeSlow("Good luck."); - Thread.Sleep(1000); - Console.WriteLine("--user disconnected"); - Thread.Sleep(75); - Console.WriteLine("--commands unlocked - check sos.help."); - Thread.Sleep(45); - SaveSystem.SaveGame(); - Console.Write("--unlocking user input..."); - Thread.Sleep(75); - Console.Write(" ..done"); - TerminalBackend.InStory = false; - TerminalBackend.PrefixEnabled = true; - Console.Write($"{SaveSystem.CurrentUser.Username}@{SaveSystem.CurrentSave.SystemName}:~$ "); - StartHackerTutorial(); - TerminalBackend.PrefixEnabled = true; - TerminalBackend.PrintPrompt(); - }); - t.IsBackground = true; - t.Start(); - TerminalBackend.PrefixEnabled = false; - } - - internal static void StartHackerTutorial() - { - Desktop.InvokeOnWorkerThread(() => - { - var tut = new TutorialBox(); - AppearanceManager.SetupWindow(tut); - - new Thread(() => - { - - - int tutPos = 0; - Action ondec = () => - { - tutPos++; - }; - TerminalBackend.CommandProcessed += (o, a) => - { - switch (tutPos) - { - - case 0: - case 10: - if (o.ToLower().StartsWith("mud.disconnect")) - { - tutPos++; - } - break; - case 11: - if (o.ToLower().StartsWith("krnl.lock_session")) - tutPos++; - break; - case 1: - if (o.ToLower().StartsWith("hacker101.brute_decrypt")) - { - if (a.Contains("0:/system/data/kernel.log")) - { - tutPos++; - } - } - break; - case 3: - if (o.ToLower().StartsWith("krnl.control")) - { - tutPos++; - } - break; - case 4: - if (o.ToLower().StartsWith("puppy.clear")) - tutPos++; - break; - case 5: - if (o.ToLower().StartsWith("mud.reconnect")) - tutPos++; - break; - case 6: - if (o.ToLower().StartsWith("mud.sendmsg")) - { - var msg = JsonConvert.DeserializeObject(a); - try - { - if (msg.header == "getusers" && msg.body == "dead") - tutPos++; - } - catch - { - - } - } - break; - case 7: - if (o.ToLower().StartsWith("hacker101.breach_user_password")) - tutPos++; - break; - case 8: - if (o.ToLower().StartsWith("hacker101.print_user_info")) - tutPos++; - break; - case 9: - if (o.ToLower().StartsWith("hacker101.steal_codepoints")) - tutPos++; - break; - } - }; - tut.SetObjective("Welcome to the dead account exploitation tutorial. In this tutorial you will learn the basics of hacking within the multi-user domain."); - Thread.Sleep(1000); - tut.SetObjective("We will start with a simple system exploit - gaining kernel-level access to ShiftOS. This can help you perform actions not ever possible in the user level."); - Thread.Sleep(1000); - tut.SetObjective("To gain root access, you will first need to breach the system watchdog to keep it from dialing home to DevX."); - Thread.Sleep(1000); - tut.SetObjective("The watchdog can only function when it has a successful connection to the multi-user domain. You will need to use the MUD Control Centre to disconnect yourself from the MUD. This will lock you out of most features. To disconnect from the multi-user domain, simply run the 'mud.disconnect' command."); - while(tutPos == 0) - { - - } - tut.SetObjective("As you can see, the kernel watchdog has shut down temporarily, however before the disconnect it was able to tell DevX that it has gone offline."); - Thread.Sleep(1000); - tut.SetObjective("You'll also notice that commands like the shiftorium, MUD control centre and various applications that utilize these system components no longer function."); - Thread.Sleep(1000); - tut.SetObjective("The watchdog, however, is still watching. DevX was smart and programmed the kernel to log all events to a local file in 0:/system/data/kernel.log."); - Thread.Sleep(1000); - tut.SetObjective("You will need to empty out this file before you can connect to the multi-user domain, as the watchdog will send the contents of this file straight to DevX."); - Thread.Sleep(1000); - tut.SetObjective("Or, you can do what we're about to do and attempt to decrypt the log and sniff out the kernel-mode access password."); - Thread.Sleep(1000); - tut.SetObjective("This will allow us to gain kernel-level access to our system using the krnl.control{pass:} command."); - Thread.Sleep(1000); - tut.SetObjective("Let's start decrypting the log file using the hacker101.brute_decrypt{file:} script. The file: argument is a string and should point to a .log file. When the script succeeds, you will see a TextPad open with the decrypted contents."); - while(tutPos == 1) - { - - } - onCompleteDecrypt += ondec; - tut.SetObjective("This script isn't the most agile script ever, but it'll get the job done."); - tutPos = 3; // For some reason, it refuses to go to part 3. - while(tutPos == 2) - { - - } - onCompleteDecrypt -= ondec; - tut.SetObjective("Alright - it's done. Here's how it's laid out. In each log entry, you have the timestamp, then the event name, then the event description."); - Thread.Sleep(1000); - tut.SetObjective("Look for the most recent 'mudhandshake' event. This contains the kernel access code."); - Thread.Sleep(1000); - tut.SetObjective("Once you have it, run 'krnl.control{pass:\"the-kernel-code-here\"}. This will allow you to gain access to the kernel."); - while(tutPos == 3) - { - - } - tut.SetObjective("You are now in kernel mode. Every command you enter will run on the kernel. Now, let's clear the watchdog's logfile and reconnect to the multi-user domain."); - Thread.Sleep(1000); - tut.SetObjective("To clear the log, simply run 'puppy.clear'."); - while(tutPos == 4) - { - - } - tut.SetObjective("Who's a good dog... You are, ShiftOS. Now, we can connect back to the MUD using 'mud.reconnect'."); - Thread.Sleep(1000); - while(tutPos == 5) - { - - } - tut.SetObjective("We have now snuck by the watchdog and DevX has no idea. With kernel-level access, everything you do is not logged, however if you perform too much in one shot, you'll get kicked off and locked out of the multi-user domain temporarily."); - Thread.Sleep(1000); - tut.SetObjective("So, let's focus on the job. You want to get into one of those fancy dead accounts, don't ya? Well, first, we need to talk with the MUD to get a list of these accounts."); - Thread.Sleep(1000); - tut.SetObjective("Simply run the `mud.sendmsg` command, specifying a 'header' of \"getusers\", and a body of \"dead\"."); - while(tutPos == 6) - { - - } - tut.SetObjective("Great. We now have the usernames and sysnames of all dead accounts on the MUD. Now let's use the hacker101.breach_user_password{user:,sys:} command to breach one of these accounts' passwords."); - while(tutPos == 7) - { - - } - tut.SetObjective("There - you now have access to that account. Use its password, username and sysname and run the hacker101.print_user_info{user:,pass:,sys:} command to print the entirety of this user's information."); - while(tutPos == 8) - { - - } - tut.SetObjective("Now you can see a list of the user's Codepoints among other things. Now you can steal their codepoints by using the hacker101.steal_codepoints{user:,pass:,sys;,amount:} command. Be careful. This may alert DevX."); - while(tutPos == 9) - { - - } - if(devx_alerted == true) - { - tut.SetObjective("Alright... enough fun and games. DevX just found out we were doing this."); - Thread.Sleep(500); - tut.SetObjective("Quick! Disconnect from the MUD!!"); - while(tutPos == 10) - { - - } - tut.SetObjective("Now, get out of kernel mode! To do that, run krnl.lock_session."); - while(tutPos == 11) - { - - } - - } - else - { - tut.SetObjective("OK, that was risky, but we pulled it off. Treat yourself! But first, let's get you out of kernel mode."); - Thread.Sleep(500); - tut.SetObjective("First we need to get you off the MUD. Simply run mud.disconnect again."); - while (tutPos == 10) - { - - } - tut.SetObjective("Now, let's run krnl.lock_session. This will lock you back into the user mode, and reconnect you to the MUD."); - while (tutPos == 11) - { - - } - tut.SetObjective("If, for some reason, DevX DOES find out, you have to be QUICK to get off of kernel mode. You don't want to make him mad."); - } - - Thread.Sleep(1000); - tut.SetObjective("So that's all for now. Whenever you're in kernel mode again, and you have access to a user account, try breaching their filesystem next time. You can use sos.help{ns:} to show commands from a specific namespace to help you find more commands easily."); - Thread.Sleep(1000); - tut.SetObjective("You can now close this window."); - tut.IsComplete = true; - - }).Start(); - }); - } - - private static bool devx_alerted = false; - - private static event Action onCompleteDecrypt; - - private static bool terminalIsOpen() - { - foreach(var win in AppearanceManager.OpenForms) - { - if (win.ParentWindow is Terminal) - return true; - } - return false; - } - - const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-_"; - - [MultiplayerOnly] - [Command("breach_user_password")] - [KernelMode] - [RequiresArgument("user")] - [RequiresArgument("sys")] - [RequiresUpgrade("hacker101_deadaccts")] - public static bool BreachUserPassword(Dictionary args) - { - string usr = args["user"].ToString(); - string sys = args["sys"].ToString(); - ServerMessageReceived msgReceived = null; - - Console.WriteLine("--hooking system thread..."); - - msgReceived = (msg) => - { - if(msg.Name == "user_data") - { - var sve = JsonConvert.DeserializeObject(msg.Contents); - var rnd = new Random(); - var sw = new Stopwatch(); - sw.Start(); - Thread.Sleep(2000); - if(rnd.Next(0, 100) >= 75) - { - Console.WriteLine("--operation took too long - failed."); - ServerManager.SendMessage("mud_save_allow_dead", JsonConvert.SerializeObject(sve)); - ServerManager.MessageReceived -= msgReceived; - TerminalBackend.PrefixEnabled = true; - return; - } - sw.Stop(); - Console.WriteLine(sve.Password); - Console.WriteLine(); - Console.WriteLine("--password breached. Operation took " + sw.ElapsedMilliseconds + " milliseconds."); - ServerManager.MessageReceived -= msgReceived; - TerminalBackend.PrintPrompt(); - } - else if(msg.Name == "user_data_not_found") - { - Console.WriteLine("--access denied."); - ServerManager.MessageReceived -= msgReceived; - TerminalBackend.PrintPrompt(); - } - TerminalBackend.PrefixEnabled = true; - }; - - Console.WriteLine("--beginning brute-force attack on " + usr + "@" + sys + "..."); - ServerManager.MessageReceived += msgReceived; - - ServerManager.SendMessage("get_user_data", JsonConvert.SerializeObject(new - { - user = usr, - sysname = sys - })); - TerminalBackend.PrefixEnabled = false; - Thread.Sleep(500); - return true; - } - - - [MultiplayerOnly] - [Command("print_user_info")] - [KernelMode] - [RequiresArgument("pass")] - [RequiresArgument("user")] - [RequiresArgument("sys")] - [RequiresUpgrade("hacker101_deadaccts")] - public static bool PrintUserInfo(Dictionary args) - { - string usr = args["user"].ToString(); - string sys = args["sys"].ToString(); - string pass = args["pass"].ToString(); - ServerMessageReceived msgReceived = null; - - Console.WriteLine("--hooking multi-user domain response call..."); - - msgReceived = (msg) => - { - if (msg.Name == "user_data") - { - var sve = JsonConvert.DeserializeObject(msg.Contents); - if(sve.Password == pass) - { - Console.WriteLine("Username: " + SaveSystem.CurrentUser.Username); - Console.WriteLine("Password: " + sve.Password); - Console.WriteLine("System name: " + sve.SystemName); - Console.WriteLine(); - Console.WriteLine("Codepoints: " + sve.Codepoints.ToString()); - - } - else - { - Console.WriteLine("--access denied."); - } - ServerManager.MessageReceived -= msgReceived; - TerminalBackend.PrintPrompt(); - - } - else if (msg.Name == "user_data_not_found") - { - Console.WriteLine("--access denied."); - ServerManager.MessageReceived -= msgReceived; - TerminalBackend.PrintPrompt(); - } - TerminalBackend.PrefixEnabled = true; - }; - - Console.WriteLine("--contacting multi-user domain..."); - ServerManager.MessageReceived += msgReceived; - - ServerManager.SendMessage("get_user_data", JsonConvert.SerializeObject(new - { - user = usr, - sysname = sys - })); - Thread.Sleep(500); - TerminalBackend.PrefixEnabled = false; - return true; - } - - [MultiplayerOnly] - [Command("steal_codepoints")] - [KernelMode] - [RequiresArgument("amount")] - [RequiresArgument("pass")] - [RequiresArgument("user")] - [RequiresArgument("sys")] - [RequiresUpgrade("hacker101_deadaccts")] - public static bool StealCodepoints(Dictionary args) - { - string usr = args["user"].ToString(); - string sys = args["sys"].ToString(); - string pass = args["pass"].ToString(); - ulong amount = (ulong)args["amount"]; - if(amount < 0) - { - Console.WriteLine("--invalid codepoint amount - halting..."); - return true; - } - - ServerMessageReceived msgReceived = null; - - Console.WriteLine("--hooking multi-user domain response call..."); - - msgReceived = (msg) => - { - if (msg.Name == "user_data") - { - var sve = JsonConvert.DeserializeObject(msg.Contents); - if (sve.Password == pass) - { - if(amount > sve.Codepoints) - { - Console.WriteLine("--can't steal this many codepoints from user."); - ServerManager.SendMessage("mud_save_allow_dead", JsonConvert.SerializeObject(sve)); - TerminalBackend.PrefixEnabled = true; - return; - } - - sve.Codepoints -= amount; - SaveSystem.TransferCodepointsFrom(SaveSystem.CurrentUser.Username, amount); - ServerManager.SendMessage("mud_save_allow_dead", JsonConvert.SerializeObject(sve)); - SaveSystem.SaveGame(); - } - else - { - Console.WriteLine("--access denied."); - } - ServerManager.MessageReceived -= msgReceived; - TerminalBackend.PrintPrompt(); - } - else if (msg.Name == "user_data_not_found") - { - Console.WriteLine("--access denied."); - ServerManager.MessageReceived -= msgReceived; - TerminalBackend.PrintPrompt(); - } - TerminalBackend.PrefixEnabled = true; - }; - - Console.WriteLine("--contacting multi-user domain..."); - Thread.Sleep(500); - ServerManager.MessageReceived += msgReceived; - - ServerManager.SendMessage("get_user_data", JsonConvert.SerializeObject(new - { - user = usr, - sysname = sys - })); - Thread.Sleep(500); - TerminalBackend.PrefixEnabled = false; - return true; - } - - [MultiplayerOnly] - [Command("purge_user")] - [KernelMode] - [RequiresArgument("pass")] - [RequiresArgument("user")] - [RequiresArgument("sys")] - [RequiresUpgrade("hacker101_deadaccts")] - public static bool PurgeUser(Dictionary args) - { - string usr = args["user"].ToString(); - string sys = args["sys"].ToString(); - string pass = args["pass"].ToString(); - ServerMessageReceived msgReceived = null; - - Console.WriteLine("--hooking multi-user domain response call..."); - - msgReceived = (msg) => - { - if (msg.Name == "user_data") - { - var sve = JsonConvert.DeserializeObject(msg.Contents); - if (sve.Password == pass) - { - ServerManager.SendMessage("delete_dead_save", JsonConvert.SerializeObject(sve)); - Console.WriteLine(" User purged successfully."); - } - else - { - Console.WriteLine("--access denied."); - } - ServerManager.MessageReceived -= msgReceived; - } - else if (msg.Name == "user_data_not_found") - { - Console.WriteLine("--access denied."); - ServerManager.MessageReceived -= msgReceived; - } - TerminalBackend.PrintPrompt(); - TerminalBackend.PrefixEnabled = true; - }; - - Console.WriteLine("--contacting multi-user domain..."); - Thread.Sleep(500); - ServerManager.MessageReceived += msgReceived; - - ServerManager.SendMessage("get_user_data", JsonConvert.SerializeObject(new - { - user = usr, - sysname = sys - })); - Thread.Sleep(500); - TerminalBackend.PrefixEnabled = false; - return true; - } - - - [Command("brute_decrypt", true)] - [RequiresArgument("file")] - public static bool BruteDecrypt(Dictionary args) - { - if (FileExists(args["file"].ToString())) - { - string pass = new Random().Next(1000, 10000).ToString(); - string fake = ""; - Console.WriteLine("Beginning brute-force attack on password."); - var s = new Stopwatch(); - s.Start(); - for(int i = 0; i < pass.Length; i++) - { - for(int num = 0; num < 10; num++) - { - if(pass[i].ToString() == num.ToString()) - { - fake += num.ToString(); - Console.Write(num); - } - } - } - s.Stop(); - - Console.WriteLine("...password cracked - operation took " + s.ElapsedMilliseconds + " milliseconds."); - var tp = new TextPad(); - AppearanceManager.SetupWindow(tp); - WriteAllText("0:/temp.txt", ReadAllText(args["file"].ToString())); - tp.LoadFile("0:/temp.txt"); - Delete("0:/temp.txt"); - onCompleteDecrypt?.Invoke(); - } - else - { - Console.WriteLine("brute_decrypt: file not found"); - } - return true; - } - } - - [MultiplayerOnly] - [Namespace("storydev")] - public static class StoryDevCommands - { - [Command("start", description = "Starts a story plot.", usage ="id:string")] - [RequiresArgument("id")] - [RemoteLock] - public static bool StartStory(Dictionary args) - { - Story.Start(args["id"].ToString()); - return true; - } - - [Command("list", description ="Lists all story IDs.")] - public static bool ListIds() - { - foreach(var type in ReflectMan.Types) - foreach(var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) - { - var attr = method.GetCustomAttributes(false).FirstOrDefault(x => x is StoryAttribute); - if (attr != null) - Console.WriteLine(" - " + (attr as StoryAttribute).StoryID); - } - return true; - } - - [Command("unexperience", description = "Marks a story plot as not-experienced yet.", usage ="id:string")] - [RemoteLock] - [RequiresArgument("id")] - public static bool Unexperience(Dictionary args) - { - string id = args["id"].ToString(); - if (SaveSystem.CurrentSave.StoriesExperienced.Contains(id)) - { - Console.WriteLine("Unexperiencing " + id + "."); - SaveSystem.CurrentSave.StoriesExperienced.Remove(id); - SaveSystem.SaveGame(); - } - else - { - Console.WriteLine("Story ID not found."); - } - - return true; - } - - [Command("experience", description = "Marks a story plot as experienced without triggering the plot.", usage ="{id:}")] - [RequiresArgument("id")] - [RemoteLock] - public static bool Experience(Dictionary args) - { - SaveSystem.CurrentSave.StoriesExperienced.Add(args["id"].ToString()); - SaveSystem.SaveGame(); - return true; - } - } -} + \ No newline at end of file diff --git a/ShiftOS.WinForms/OobeStory.cs b/ShiftOS.WinForms/OobeStory.cs index cab1ec8..0d9b817 100644 --- a/ShiftOS.WinForms/OobeStory.cs +++ b/ShiftOS.WinForms/OobeStory.cs @@ -13,7 +13,6 @@ using ShiftOS.Objects; namespace ShiftOS.WinForms { - [Namespace("test")] public class OobeStory { [Command("test")] diff --git a/ShiftOS.WinForms/Servers/RemoteTerminalServer.cs b/ShiftOS.WinForms/Servers/RemoteTerminalServer.cs index d57e28f..849049f 100644 --- a/ShiftOS.WinForms/Servers/RemoteTerminalServer.cs +++ b/ShiftOS.WinForms/Servers/RemoteTerminalServer.cs @@ -10,7 +10,6 @@ using ShiftOS.Objects; namespace ShiftOS.WinForms.Servers { - [Namespace("rts")] [Server("Remote Terminal Server", 21)] //[RequiresUpgrade("story_hacker101_breakingthebonds")] //Uncomment when story is implemented. public class RemoteTerminalServer : Server diff --git a/ShiftOS.WinForms/ShiftOS.WinForms.csproj b/ShiftOS.WinForms/ShiftOS.WinForms.csproj index 9e16b19..00b4d83 100644 --- a/ShiftOS.WinForms/ShiftOS.WinForms.csproj +++ b/ShiftOS.WinForms/ShiftOS.WinForms.csproj @@ -131,12 +131,6 @@ Chat.cs - - UserControl - - - CoherenceOverlay.cs - UserControl diff --git a/ShiftOS.WinForms/SkinCommands.cs b/ShiftOS.WinForms/SkinCommands.cs index 1f32d96..f35c449 100644 --- a/ShiftOS.WinForms/SkinCommands.cs +++ b/ShiftOS.WinForms/SkinCommands.cs @@ -9,7 +9,6 @@ using ShiftOS.Objects.ShiftFS; namespace ShiftOS.WinForms { - [Namespace("skins")] public static class SkinCommands { [Command("reset")] diff --git a/ShiftOS.WinForms/TestCommandsForUpgrades.cs b/ShiftOS.WinForms/TestCommandsForUpgrades.cs index 739a2a2..5f28270 100644 --- a/ShiftOS.WinForms/TestCommandsForUpgrades.cs +++ b/ShiftOS.WinForms/TestCommandsForUpgrades.cs @@ -1,21 +1 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ShiftOS.Engine; - -namespace ShiftOS.WinForms -{ - [Namespace("test")] - public static class TestCommandsForUpgrades - { - [Command("simpletest")] - public static bool Simple() - { - return true; - } - } - - -} + \ No newline at end of file diff --git a/ShiftOS.WinForms/TrailerCommands.cs b/ShiftOS.WinForms/TrailerCommands.cs index 182d03d..e69de29 100644 --- a/ShiftOS.WinForms/TrailerCommands.cs +++ b/ShiftOS.WinForms/TrailerCommands.cs @@ -1,48 +0,0 @@ -/* - * MIT License - * - * Copyright (c) 2017 Michael VanOverbeek and ShiftOS devs - * - * 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: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * 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. - */ - -#define TRAILER -#if TRAILER -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ShiftOS.Engine; - -namespace ShiftOS.WinForms -{ - [Namespace("trailer")] - public static class TrailerCommands - { - [Command("init")] - public static bool TrailerInit() - { - var oobe = new Oobe(); - oobe.StartTrailer(); - return true; - } - } -} -#endif \ No newline at end of file diff --git a/ShiftOS.WinForms/WinformsDesktop.cs b/ShiftOS.WinForms/WinformsDesktop.cs index f6c4383..82d99f0 100644 --- a/ShiftOS.WinForms/WinformsDesktop.cs +++ b/ShiftOS.WinForms/WinformsDesktop.cs @@ -47,7 +47,6 @@ namespace ShiftOS.WinForms /// /// Winforms desktop. /// - [Namespace("desktop")] public partial class WinformsDesktop : Form, IDesktop { public MainMenu.MainMenu ParentMenu = null; diff --git a/ShiftOS_TheReturn/Command.cs b/ShiftOS_TheReturn/Command.cs index 09cf206..b90f604 100644 --- a/ShiftOS_TheReturn/Command.cs +++ b/ShiftOS_TheReturn/Command.cs @@ -135,42 +135,6 @@ namespace ShiftOS.Engine } } - /// - /// Denotes a Terminal command namespace. - /// - public class Namespace : Attribute - { - /// - /// The namespace's name. - /// - public string name; - /// - /// Whether the namespace should be hidden from the help system. Overrides all child s' hide values. - /// - public bool hide; - - /// - /// Creates a new instance of the . - /// - /// The name of the namespace. - public Namespace(string n) - { - name = n; - } - - - /// - /// Creates a new instance of the . - /// - /// The name of the namespace. - /// Whether this namespace should be hidden from the user. - public Namespace(string n, bool hide) - { - name = n; - this.hide = hide; - } - } - /// /// Marks a Terminal command as obsolete. /// diff --git a/ShiftOS_TheReturn/Commands.cs b/ShiftOS_TheReturn/Commands.cs index 6f3ab15..9221bba 100644 --- a/ShiftOS_TheReturn/Commands.cs +++ b/ShiftOS_TheReturn/Commands.cs @@ -44,7 +44,6 @@ using ShiftOS.Objects.ShiftFS; namespace ShiftOS.Engine { - [Namespace("infobox", hide = true)] [RequiresUpgrade("desktop;wm_free_placement")] public static class InfoboxDebugCommands { @@ -107,7 +106,6 @@ namespace ShiftOS.Engine } - [Namespace("audio")] public static class AudioCommands { [Command("setvol", description = "Set the volume of the system audio to anywhere between 0 and 100.")] @@ -129,79 +127,7 @@ namespace ShiftOS.Engine } } - [RequiresUpgrade("mud_fundamentals")] - [Namespace("mud")] - public static class MUDCommands - { - [MultiplayerOnly] - [Command("status")] - public static bool Status() - { - ServerManager.PrintDiagnostics(); - return true; - } - - [Command("connect")] - public static bool Connect(Dictionary args) - { - try - { - string ip = (args.ContainsKey("addr") == true) ? args["addr"] as string : "michaeltheshifter.me"; - int port = (args.ContainsKey("port") == true) ? Convert.ToInt32(args["port"] as string) : 13370; - try - { - ServerManager.Initiate(ip, port); - } - catch (Exception ex) - { - Console.WriteLine("{ERROR}: " + ex.Message); - } - - TerminalBackend.PrefixEnabled = false; - return true; - } - catch (Exception ex) - { - Console.WriteLine("Error running script:" + ex); - return false; - } - } - - [Command("reconnect")] - [RequiresUpgrade("hacker101_deadaccts")] - public static bool Reconnect() - { - Console.WriteLine("--reconnecting to multi-user domain..."); - KernelWatchdog.MudConnected = true; - Console.WriteLine("--done."); - return true; - } - - [MultiplayerOnly] - [Command("disconnect")] - [RequiresUpgrade("hacker101_deadaccts")] - public static bool Disconnect() - { - Console.WriteLine("--connection to multi-user domain severed..."); - KernelWatchdog.MudConnected = false; - return true; - } - - [MultiplayerOnly] - [Command("sendmsg")] - [KernelMode] - [RequiresUpgrade("hacker101_deadaccts")] - [RequiresArgument("header")] - [RequiresArgument("body")] - public static bool SendMessage(Dictionary args) - { - ServerManager.SendMessage(args["header"].ToString(), args["body"].ToString()); - return true; - } - } - [TutorialLock] - [Namespace("trm")] public static class TerminalCommands { [Command("clear")] @@ -220,167 +146,6 @@ namespace ShiftOS.Engine } } -#if DEVEL - internal class Rock : Exception - { - internal Rock() : base("Someone threw a rock at the window, and the Terminal shattered.") - { - - } - } - - [MultiplayerOnly] - [Namespace("dev")] - public static class ShiftOSDevCommands - { - [Command("buy")] - public static bool UnlockUpgrade(Dictionary args) - { - string upg = args["id"].ToString(); - try - { - SaveSystem.CurrentSave.Upgrades[upg] = true; - Shiftorium.InvokeUpgradeInstalled(); - SaveSystem.SaveGame(); - } - catch - { - Console.WriteLine("Upgrade not found."); - } - return true; - } - - [Command("rock", description = "A little surprise for unstable builds...")] - public static bool ThrowASandwichingRock() - { - Infobox.Show("He who lives in a glass house shouldn't throw stones...", new Rock().Message); - return false; - } - - - [Command("unbuy")] - [RequiresArgument("upgrade")] - public static bool UnbuyUpgrade(Dictionary args) - { - try - { - SaveSystem.CurrentSave.Upgrades[args["upgrade"].ToString()] = false; - SaveSystem.SaveGame(); - Desktop.PopulateAppLauncher(); - Desktop.CurrentDesktop.SetupDesktop(); - } - catch - { - Console.WriteLine("Upgrade not found."); - } - return true; - } - - [Command("getallupgrades")] - public static bool GetAllUpgrades() - { - Console.WriteLine(JsonConvert.SerializeObject(SaveSystem.CurrentSave.Upgrades, Formatting.Indented)); - return true; - } - - [Command("multarg")] - [RequiresArgument("id")] - [RequiresArgument("name")] - [RequiresArgument("type")] - public static bool MultArg(Dictionary args) - { - Console.WriteLine("Success! "+args.ToString()); - return true; - } - - [Command("restart")] - public static bool Restart() - { - SaveSystem.CurrentSave.Upgrades = new Dictionary(); - SaveSystem.CurrentSave.Codepoints = 0; - SaveSystem.CurrentSave.StoriesExperienced.Clear(); - SaveSystem.CurrentSave.StoriesExperienced.Add("mud_fundamentals"); - SaveSystem.SaveGame(); - Shiftorium.InvokeUpgradeInstalled(); - return true; - } - - [Command("freecp")] - public static bool FreeCodepoints(Dictionary args) - { - if (args.ContainsKey("amount")) - try - { - ulong codepointsToAdd = Convert.ToUInt64(args["amount"].ToString()); - SaveSystem.CurrentSave.Codepoints += codepointsToAdd; - return true; - } - catch (Exception ex) - { - Console.WriteLine("{ERROR}: " + ex.Message); - return true; - } - - SaveSystem.CurrentSave.Codepoints += 1000; - return true; - } - - [Command("unlockeverything")] - public static bool UnlockAllUpgrades() - { - foreach (var upg in Shiftorium.GetDefaults()) - { - if (!SaveSystem.CurrentSave.Upgrades.ContainsKey(upg.ID)) - SaveSystem.CurrentSave.Upgrades.Add(upg.ID, true); - else - SaveSystem.CurrentSave.Upgrades[upg.ID] = true; - } - Shiftorium.InvokeUpgradeInstalled(); - SkinEngine.LoadSkin(); - return true; - } - - [Command("info")] - public static bool DevInformation() - { - Console.WriteLine("{SHIFTOS_PLUS_MOTTO}"); - Console.WriteLine("{SHIFTOS_VERSION_INFO}" + Assembly.GetExecutingAssembly().GetName().Version); - return true; - } - [Command("pullfile")] - public static bool PullFile(Dictionary args) - { - if (args.ContainsKey("physical") && args.ContainsKey("virtual")) - { - string file = (string)args["physical"]; - string dest = (string)args["virtual"]; - if (System.IO.File.Exists(file)) - { - Console.WriteLine("Pulling physical file to virtual drive..."); - byte[] filebytes = System.IO.File.ReadAllBytes(file); - ShiftOS.Objects.ShiftFS.Utils.WriteAllBytes(dest, filebytes); - } - else - { - Console.WriteLine("The specified file does not exist on the physical drive."); - } - } - else - { - Console.WriteLine("You must supply a physical path."); - } - return true; - } - [Command("crash")] - public static bool CrashInstantly() - { - CrashHandler.Start(new Exception("ShiftOS was sent a command to forcefully crash.")); - return true; - } - } -#endif - - [Namespace("sos")] public static class ShiftOSCommands { @@ -478,38 +243,17 @@ namespace ShiftOS.Engine } [Command("help", "{COMMAND_HELP_USAGE", "{COMMAND_HELP_DESCRIPTION}")] - public static bool Help(Dictionary args) + public static bool Help() { var sb = new StringBuilder(); sb.AppendLine("Retrieving help data."); - - if (args.ContainsKey("ns")) + //print all unique namespaces. + foreach (var n in TerminalBackend.Commands.Select(x => x.CommandInfo).Distinct().OrderBy(x=>x.name)) { - string ns = args["ns"].ToString(); - //First let's check for a command that has this namespace. - var cmdtest = TerminalBackend.Commands.FirstOrDefault(x => x.NamespaceInfo.name == ns); - if (cmdtest == null) //Namespace not found. - sb.AppendLine("Error retrieving help for namespace \"" + ns + "\". Namespace not found."); - else - { - //Now do the actual scan. - sb.AppendLine("Namespace: " + ns); - foreach(var cmd in TerminalBackend.Commands.Where(x => x.NamespaceInfo.name == ns)) - { - string str = cmd.ToString(); - str = str.Replace(str.Substring(str.LastIndexOf("|")), ""); - sb.AppendLine(str); - } - } - } - else - { - - //print all unique namespaces. - foreach(var n in TerminalBackend.Commands.Select(x => x.NamespaceInfo.name).Distinct()) - { - sb.AppendLine("sos.help{ns:\"" + n + "\"}"); - } + sb.Append(n.name); + if (Shiftorium.UpgradeInstalled("help_descriptions")) + sb.Append(" - " + n.description); + sb.AppendLine(); } Console.WriteLine(sb.ToString()); @@ -565,7 +309,6 @@ Upgrades: {SaveSystem.CurrentSave.CountUpgrades()} installed, } [MultiplayerOnly] - [Namespace("shiftorium")] public static class ShiftoriumCommands { [Command("buy")] @@ -668,7 +411,7 @@ shiftorium.buy{{upgrade:""{upg.ID}""}}"); return true; } - [Command("list")] + [Command("shiftorium", description ="Lists all available Shiftorium upgrades.")] public static bool ListAll(Dictionary args) { try @@ -742,7 +485,6 @@ shiftorium.buy{{upgrade:""{upg.ID}""}}"); } } - [Namespace("win")] public static class WindowCommands { diff --git a/ShiftOS_TheReturn/PythonAPI.cs b/ShiftOS_TheReturn/PythonAPI.cs index cc3798c..7db4c45 100644 --- a/ShiftOS_TheReturn/PythonAPI.cs +++ b/ShiftOS_TheReturn/PythonAPI.cs @@ -291,7 +291,6 @@ namespace ShiftOS.Engine } #if DEBUG - [Namespace("dev")] public static class PythonCmds { [Command("runpystring", description = "Run some Python code. (Only present in DEBUG builds of ShiftOS)")] diff --git a/ShiftOS_TheReturn/ReflectMan.cs b/ShiftOS_TheReturn/ReflectMan.cs index 78f6bf3..d194754 100644 --- a/ShiftOS_TheReturn/ReflectMan.cs +++ b/ShiftOS_TheReturn/ReflectMan.cs @@ -104,7 +104,6 @@ namespace ShiftOS.Engine } #if DEBUG - [Namespace("dev")] public static class ReflectDebug { [Command("listalltypes", description = "List all types that were found by ReflectMan. Only present in DEBUG builds of ShiftOS.")] diff --git a/ShiftOS_TheReturn/TerminalBackend.cs b/ShiftOS_TheReturn/TerminalBackend.cs index 81ea971..4594eb3 100644 --- a/ShiftOS_TheReturn/TerminalBackend.cs +++ b/ShiftOS_TheReturn/TerminalBackend.cs @@ -148,7 +148,6 @@ namespace ShiftOS.Engine return hash; } - public Namespace NamespaceInfo { get; set; } public Command CommandInfo { get; set; } public List RequiredArguments { get; set; } @@ -161,16 +160,14 @@ namespace ShiftOS.Engine public override string ToString() { StringBuilder sb = new StringBuilder(); - sb.Append(this.NamespaceInfo.name); - sb.Append("."); sb.Append(this.CommandInfo.name); if (this.RequiredArguments.Count > 0) { - sb.Append("{"); + sb.Append(" "); foreach (var arg in RequiredArguments) { - sb.Append(arg); - sb.Append(":"); + sb.Append("--" + arg); + sb.Append(" "); if (RequiredArguments.IndexOf(arg) < RequiredArguments.Count - 1) sb.Append(','); } @@ -295,41 +292,42 @@ namespace ShiftOS.Engine public static void PopulateTerminalCommands() { Commands = new List(); - foreach(var type in ReflectMan.Types) + foreach (var type in ReflectMan.Types) { - var ns = type.GetCustomAttributes(false).FirstOrDefault(x => x is Namespace) as Namespace; - if(ns != null) + foreach (var mth in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) { - foreach(var mth in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) + var cmd = mth.GetCustomAttributes(false).FirstOrDefault(x => x is Command); + if (cmd != null) { - var cmd = mth.GetCustomAttributes(false).FirstOrDefault(x => x is Command); - if(cmd != null) - { - var tc = new TerminalCommand(); - tc.RequiresElevation = !(type.GetCustomAttributes(false).FirstOrDefault(x => x is KernelModeAttribute) == null); + var tc = new TerminalCommand(); + tc.RequiresElevation = !(type.GetCustomAttributes(false).FirstOrDefault(x => x is KernelModeAttribute) == null); - tc.NamespaceInfo = ns; - tc.CommandInfo = cmd as Command; - tc.RequiresElevation = tc.RequiresElevation || !(mth.GetCustomAttributes(false).FirstOrDefault(x => x is KernelModeAttribute) == null); - tc.RequiredArguments = new List(); - foreach (var arg in mth.GetCustomAttributes(false).Where(x=>x is RequiresArgument)) - { - var rarg = arg as RequiresArgument; - tc.RequiredArguments.Add(rarg.argument); - } - var rupg = mth.GetCustomAttributes(false).FirstOrDefault(x => x is RequiresUpgradeAttribute) as RequiresUpgradeAttribute; - if (rupg != null) - tc.Dependencies = rupg.Upgrade; - else - tc.Dependencies = ""; - tc.CommandType = type; - tc.CommandHandler = mth; - if (!Commands.Contains(tc)) - Commands.Add(tc); + tc.CommandInfo = cmd as Command; + tc.RequiresElevation = tc.RequiresElevation || !(mth.GetCustomAttributes(false).FirstOrDefault(x => x is KernelModeAttribute) == null); + tc.RequiredArguments = new List(); + foreach (var arg in mth.GetCustomAttributes(false).Where(x => x is RequiresArgument)) + { + var rarg = arg as RequiresArgument; + tc.RequiredArguments.Add(rarg.argument); } + var rupg = mth.GetCustomAttributes(false).FirstOrDefault(x => x is RequiresUpgradeAttribute) as RequiresUpgradeAttribute; + if (rupg != null) + tc.Dependencies = rupg.Upgrade; + else + tc.Dependencies = ""; + tc.CommandType = type; + tc.CommandHandler = mth; + + var ambiguity = Commands.FirstOrDefault(x => x.CommandInfo.name == tc.CommandInfo.name); + if (ambiguity != null) + throw new Exception("Command ambiguity error. You can't have two commands with the same name: " + $"{tc} == {ambiguity}"); + + if (!Commands.Contains(tc)) + Commands.Add(tc); } } + } Console.WriteLine("[termdb] " + Commands.Count + " commands found."); } @@ -465,7 +463,7 @@ namespace ShiftOS.Engine string[] split = text.Split('.'); - var cmd = Commands.FirstOrDefault(x => x.NamespaceInfo.name == split[0] && x.CommandInfo.name == split[1]); + var cmd = Commands.FirstOrDefault(x => x.CommandInfo.name == text); if (cmd == null) return false; if (!Shiftorium.UpgradeInstalled(cmd.Dependencies)) diff --git a/ShiftOS_TheReturn/UserManagementCommands.cs b/ShiftOS_TheReturn/UserManagementCommands.cs index a64c99c..cac535b 100644 --- a/ShiftOS_TheReturn/UserManagementCommands.cs +++ b/ShiftOS_TheReturn/UserManagementCommands.cs @@ -10,7 +10,6 @@ namespace ShiftOS.Engine /// /// Administrative user management terminal commands. /// - [Namespace("admin")] [KernelMode] [RequiresUpgrade("mud_fundamentals")] public static class AdminUserManagementCommands @@ -173,7 +172,6 @@ namespace ShiftOS.Engine /// /// Non-administrative user management terminal commands. /// - [Namespace("user")] [RequiresUpgrade("mud_fundamentals")] public static class UserManagementCommands { -- cgit v1.2.3