Merge a fuckton of shit.

This commit is contained in:
Michael VanOverbeek 2017-05-21 12:29:53 +00:00
parent 31cc9148dd
commit 76b54853ba
32 changed files with 0 additions and 12644 deletions

View file

@ -1,496 +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
//#define CRASHONSTART
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections;
using static ShiftOS.Engine.SkinEngine;
using ShiftOS.Engine;
using ShiftOS.Objects;
using ShiftOS.WinForms.Tools;
namespace ShiftOS.WinForms.Applications
{
[Launcher("Terminal", false, null, "Utilities")]
[WinOpen("terminal")]
[DefaultIcon("iconTerminal")]
public partial class Terminal : UserControl, IShiftOSWindow
{
public static Stack<string> ConsoleStack = new Stack<string>();
public static System.Windows.Forms.Timer ti = new System.Windows.Forms.Timer();
public static string latestCommmand = "";
public static bool IsInRemoteSystem = false;
public static string RemoteGuid = "";
[Obsolete("This is used for compatibility with old parts of the backend. Please use TerminalBackend instead.")]
public static bool PrefixEnabled
{
get
{
return TerminalBackend.PrefixEnabled;
}
set
{
TerminalBackend.PrefixEnabled = value;
}
}
[Obsolete("This is used for compatibility with old parts of the backend. Please use TerminalBackend instead.")]
public static bool InStory
{
get
{
return TerminalBackend.InStory;
}
set
{
TerminalBackend.InStory = value;
}
}
[Obsolete("This is used for compatibility with old parts of the backend. Please use TerminalBackend instead.")]
public static string LastCommand
{
get
{
return TerminalBackend.LastCommand;
}
set
{
TerminalBackend.LastCommand = value;
}
}
public int TutorialProgress
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
[Obsolete("This is used for compatibility with old parts of the backend. Please use TerminalBackend instead.")]
public static void InvokeCommand(string text)
{
TerminalBackend.InvokeCommand(text);
}
public Terminal()
{
InitializeComponent();
SaveSystem.GameReady += () =>
{
try
{
this.Invoke(new Action(() =>
{
ResetAllKeywords();
rtbterm.Text = "";
if (!Shiftorium.UpgradeInstalled("desktop"))
{
TerminalBackend.PrefixEnabled = true;
TerminalBackend.InStory = false;
TerminalBackend.PrintPrompt();
if (Shiftorium.UpgradeInstalled("wm_free_placement"))
{
this.ParentForm.Width = 640;
this.ParentForm.Height = 480;
this.ParentForm.Left = (Screen.PrimaryScreen.Bounds.Width - 640) / 2;
this.ParentForm.Top = (Screen.PrimaryScreen.Bounds.Height - 480) / 2;
}
}
else
{
AppearanceManager.Close(this);
}
}));
}
catch { }
};
this.DoubleBuffered = true;
}
public void FocusOnTerminal()
{
rtbterm.Focus();
}
public static string GetTime()
{
var time = DateTime.Now;
if (ShiftoriumFrontend.UpgradeInstalled("full_precision_time"))
{
return DateTime.Now.ToString("h:mm:ss tt");
}
else if (ShiftoriumFrontend.UpgradeInstalled("clock_am_and_pm"))
{
return time.TimeOfDay.TotalHours > 12 ? $"{time.Hour - 12} PM" : $"{time.Hour} AM";
}
else if (ShiftoriumFrontend.UpgradeInstalled("clock_hours"))
{
return ((int)time.TimeOfDay.TotalHours).ToString();
}
else if (ShiftoriumFrontend.UpgradeInstalled("clock_minutes"))
{
return ((int)time.TimeOfDay.TotalMinutes).ToString();
}
else if (ShiftoriumFrontend.UpgradeInstalled("clock"))
{
return ((int)time.TimeOfDay.TotalSeconds).ToString();
}
return "";
}
public static event TextSentEventHandler TextSent;
public void ResetAllKeywords()
{
string primary = SaveSystem.CurrentUser.Username + " ";
string secondary = "shiftos ";
var asm = Assembly.GetExecutingAssembly();
var types = asm.GetTypes();
foreach (var type in types)
{
foreach (var a in type.GetCustomAttributes(false))
{
if (ShiftoriumFrontend.UpgradeAttributesUnlocked(type))
{
if (a is Namespace)
{
var ns = a as Namespace;
if (!primary.Contains(ns.name))
{
primary += ns.name + " ";
}
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
if (ShiftoriumFrontend.UpgradeAttributesUnlocked(method))
{
foreach (var ma in method.GetCustomAttributes(false))
{
if (ma is Command)
{
var cmd = ma as Command;
if (!secondary.Contains(cmd.name))
secondary += cmd.name + " ";
}
}
}
}
}
}
}
}
}
public static void MakeWidget(Controls.TerminalBox txt)
{
AppearanceManager.StartConsoleOut();
txt.GotFocus += (o, a) =>
{
AppearanceManager.ConsoleOut = txt;
};
txt.KeyDown += (o, a) =>
{
if (a.Control == true || a.Alt == true)
{
a.SuppressKeyPress = true;
return;
}
if (a.KeyCode == Keys.Enter)
{
try
{
a.SuppressKeyPress = true;
Console.WriteLine("");
var text = txt.Lines.ToArray();
var text2 = text[text.Length - 2];
var text3 = "";
var text4 = Regex.Replace(text2, @"\t|\n|\r", "");
if (IsInRemoteSystem == true)
{
ServerManager.SendMessage("trm_invcmd", JsonConvert.SerializeObject(new
{
guid = RemoteGuid,
command = text4
}));
}
else
{
if (TerminalBackend.PrefixEnabled)
{
text3 = text4.Remove(0, $"{SaveSystem.CurrentUser.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ".Length);
}
TerminalBackend.LastCommand = text3;
TextSent?.Invoke(text4);
TerminalBackend.SendText(text4);
if (TerminalBackend.InStory == false)
{
if (text3 == "stop theme")
{
CurrentCommandParser.parser = null;
}
else
{
if (CurrentCommandParser.parser == null)
{
TerminalBackend.InvokeCommand(text3);
}
else
{
var result = CurrentCommandParser.parser.ParseCommand(text3);
if (result.Equals(default(KeyValuePair<KeyValuePair<string, string>, Dictionary<string, string>>)))
{
Console.WriteLine("Syntax Error: Syntax Error");
}
else
{
TerminalBackend.InvokeCommand(result.Key.Key, result.Key.Value, result.Value);
}
}
}
}
if (TerminalBackend.PrefixEnabled)
{
TerminalBackend.PrintPrompt();
}
}
}
catch
{
}
}
else if (a.KeyCode == Keys.Back)
{
try
{
var tostring3 = txt.Lines[txt.Lines.Length - 1];
var tostringlen = tostring3.Length + 1;
var workaround = $"{SaveSystem.CurrentUser.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ";
var derp = workaround.Length + 1;
if (tostringlen != derp)
{
AppearanceManager.CurrentPosition--;
}
else
{
a.SuppressKeyPress = true;
}
}
catch
{
Debug.WriteLine("Drunky alert in terminal.");
}
}
else if (a.KeyCode == Keys.Left)
{
var getstring = txt.Lines[txt.Lines.Length - 1];
var stringlen = getstring.Length + 1;
var header = $"{SaveSystem.CurrentUser.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ";
var headerlen = header.Length + 1;
var selstart = txt.SelectionStart;
var remstrlen = txt.TextLength - stringlen;
var finalnum = selstart - remstrlen;
if (finalnum != headerlen)
{
AppearanceManager.CurrentPosition--;
}
else
{
a.SuppressKeyPress = true;
}
}
else if (a.KeyCode == Keys.Up)
{
var tostring3 = txt.Lines[txt.Lines.Length - 1];
if (tostring3 == $"{SaveSystem.CurrentUser.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ")
Console.Write(TerminalBackend.LastCommand);
a.SuppressKeyPress = true;
}
else
{
if (TerminalBackend.InStory)
{
a.SuppressKeyPress = true;
}
AppearanceManager.CurrentPosition++;
}
};
AppearanceManager.ConsoleOut = txt;
txt.Focus();
txt.Font = LoadedSkin.TerminalFont;
txt.ForeColor = ControlManager.ConvertColor(LoadedSkin.TerminalForeColorCC);
txt.BackColor = ControlManager.ConvertColor(LoadedSkin.TerminalBackColorCC);
}
private void Terminal_Load(object sender, EventArgs e)
{
ServerManager.MessageReceived += (msg) =>
{
if (msg.Name == "trm_handshake_guid")
{
IsInRemoteSystem = true;
RemoteGuid = msg.GUID;
}
else if (msg.Name == "trm_handshake_stop")
{
IsInRemoteSystem = false;
RemoteGuid = "";
}
};
}
private void Terminal_FormClosing(object sender, FormClosingEventArgs e)
{
ti.Stop();
IsInRemoteSystem = false;
RemoteGuid = "";
}
public void OnLoad()
{
MakeWidget(rtbterm);
if (SaveSystem.CurrentSave != null)
{
if (!ShiftoriumFrontend.UpgradeInstalled("window_manager"))
{
rtbterm.Select(rtbterm.TextLength, 0);
}
}
new Thread(() =>
{
Thread.Sleep(1000);
TerminalBackend.PrintPrompt();
}).Start();
}
public void OnSkinLoad()
{
try
{
rtbterm.Font = LoadedSkin.TerminalFont;
rtbterm.ForeColor = ControlManager.ConvertColor(LoadedSkin.TerminalForeColorCC);
rtbterm.BackColor = ControlManager.ConvertColor(LoadedSkin.TerminalBackColorCC);
}
catch
{
}
}
public bool OnUnload()
{
if (SaveSystem.ShuttingDown == false)
{
if (!ShiftoriumFrontend.UpgradeInstalled("desktop"))
{
if (AppearanceManager.OpenForms.Count <= 1)
{
Console.WriteLine("");
Console.WriteLine("{WIN_CANTCLOSETERMINAL}");
try
{
Console.WriteLine("");
if (TerminalBackend.PrefixEnabled)
{
Console.Write($"{SaveSystem.CurrentUser.Username}@shiftos:~$ ");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
}
}
return true;
}
public void OnUpgrade()
{
}
private void rtbterm_TextChanged(object sender, EventArgs e)
{
}
internal void ClearText()
{
rtbterm.Text = "";
}
}
}

View file

@ -1,130 +0,0 @@
namespace ShiftOS.WinForms.Applications
{
partial class UpdateManager
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lbupdatetitle = new System.Windows.Forms.Label();
this.pnlupdatebar = new System.Windows.Forms.Panel();
this.pgdownload = new ShiftOS.WinForms.Controls.ShiftedProgressBar();
this.btnaction = new System.Windows.Forms.Button();
this.btnclose = new System.Windows.Forms.Button();
this.wbstatus = new System.Windows.Forms.WebBrowser();
this.pnlupdatebar.SuspendLayout();
this.SuspendLayout();
//
// lbupdatetitle
//
this.lbupdatetitle.AutoSize = true;
this.lbupdatetitle.Dock = System.Windows.Forms.DockStyle.Top;
this.lbupdatetitle.Location = new System.Drawing.Point(0, 0);
this.lbupdatetitle.Margin = new System.Windows.Forms.Padding(10);
this.lbupdatetitle.Name = "lbupdatetitle";
this.lbupdatetitle.Size = new System.Drawing.Size(117, 13);
this.lbupdatetitle.TabIndex = 0;
this.lbupdatetitle.Tag = "header1";
this.lbupdatetitle.Text = "Checking for updates...";
//
// pnlupdatebar
//
this.pnlupdatebar.Controls.Add(this.pgdownload);
this.pnlupdatebar.Controls.Add(this.btnaction);
this.pnlupdatebar.Controls.Add(this.btnclose);
this.pnlupdatebar.Dock = System.Windows.Forms.DockStyle.Bottom;
this.pnlupdatebar.Location = new System.Drawing.Point(0, 426);
this.pnlupdatebar.Name = "pnlupdatebar";
this.pnlupdatebar.Size = new System.Drawing.Size(597, 33);
this.pnlupdatebar.TabIndex = 1;
//
// pgdownload
//
this.pgdownload.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pgdownload.BlockSize = 5;
this.pgdownload.Location = new System.Drawing.Point(86, 4);
this.pgdownload.Maximum = 100;
this.pgdownload.Name = "pgdownload";
this.pgdownload.Size = new System.Drawing.Size(427, 23);
this.pgdownload.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
this.pgdownload.TabIndex = 2;
this.pgdownload.Text = "Updating...";
this.pgdownload.Value = 0;
//
// btnaction
//
this.btnaction.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnaction.Location = new System.Drawing.Point(519, 4);
this.btnaction.Name = "btnaction";
this.btnaction.Size = new System.Drawing.Size(75, 23);
this.btnaction.TabIndex = 1;
this.btnaction.Text = "Update";
this.btnaction.UseVisualStyleBackColor = true;
//
// btnclose
//
this.btnclose.Location = new System.Drawing.Point(4, 4);
this.btnclose.Name = "btnclose";
this.btnclose.Size = new System.Drawing.Size(75, 23);
this.btnclose.TabIndex = 0;
this.btnclose.Text = "{CLOSE}";
this.btnclose.UseVisualStyleBackColor = true;
this.btnclose.Click += new System.EventHandler(this.btnclose_Click);
//
// wbstatus
//
this.wbstatus.Dock = System.Windows.Forms.DockStyle.Fill;
this.wbstatus.Location = new System.Drawing.Point(0, 13);
this.wbstatus.MinimumSize = new System.Drawing.Size(20, 20);
this.wbstatus.Name = "wbstatus";
this.wbstatus.Size = new System.Drawing.Size(597, 413);
this.wbstatus.TabIndex = 2;
//
// UpdateManager
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.wbstatus);
this.Controls.Add(this.pnlupdatebar);
this.Controls.Add(this.lbupdatetitle);
this.Name = "UpdateManager";
this.Size = new System.Drawing.Size(597, 459);
this.pnlupdatebar.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lbupdatetitle;
private System.Windows.Forms.Panel pnlupdatebar;
private Controls.ShiftedProgressBar pgdownload;
private System.Windows.Forms.Button btnaction;
private System.Windows.Forms.Button btnclose;
private System.Windows.Forms.WebBrowser wbstatus;
}
}

View file

@ -1,168 +0,0 @@
namespace ShiftOS.WinForms.Applications
{
partial class VideoPlayer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VideoPlayer));
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.flcontrols = new System.Windows.Forms.FlowLayoutPanel();
this.btnplay = new System.Windows.Forms.Button();
this.pgplaytime = new ShiftOS.WinForms.Controls.ShiftedProgressBar();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.addSongToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.wpaudio = new AxWMPLib.AxWindowsMediaPlayer();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.flcontrols.SuspendLayout();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.wpaudio)).BeginInit();
this.SuspendLayout();
//
// toolStripContainer1
//
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.wpaudio);
this.toolStripContainer1.ContentPanel.Controls.Add(this.flcontrols);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(805, 402);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.LeftToolStripPanelVisible = false;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.RightToolStripPanelVisible = false;
this.toolStripContainer1.Size = new System.Drawing.Size(805, 426);
this.toolStripContainer1.TabIndex = 3;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menuStrip1);
//
// flcontrols
//
this.flcontrols.AutoSize = true;
this.flcontrols.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flcontrols.Controls.Add(this.btnplay);
this.flcontrols.Controls.Add(this.pgplaytime);
this.flcontrols.Dock = System.Windows.Forms.DockStyle.Bottom;
this.flcontrols.Location = new System.Drawing.Point(0, 373);
this.flcontrols.Name = "flcontrols";
this.flcontrols.Size = new System.Drawing.Size(805, 29);
this.flcontrols.TabIndex = 0;
//
// btnplay
//
this.btnplay.AutoSize = true;
this.btnplay.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnplay.Location = new System.Drawing.Point(3, 3);
this.btnplay.Name = "btnplay";
this.btnplay.Size = new System.Drawing.Size(37, 23);
this.btnplay.TabIndex = 0;
this.btnplay.Text = "Play";
this.btnplay.UseVisualStyleBackColor = true;
this.btnplay.Click += new System.EventHandler(this.btnplay_Click);
//
// pgplaytime
//
this.pgplaytime.BlockSize = 5;
this.pgplaytime.Location = new System.Drawing.Point(46, 3);
this.pgplaytime.Maximum = 100;
this.pgplaytime.Name = "pgplaytime";
this.pgplaytime.Size = new System.Drawing.Size(749, 23);
this.pgplaytime.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
this.pgplaytime.TabIndex = 1;
this.pgplaytime.Tag = "keepbg";
this.pgplaytime.Text = "shiftedProgressBar1";
this.pgplaytime.Value = 0;
this.pgplaytime.MouseDown += new System.Windows.Forms.MouseEventHandler(this.startScrub);
this.pgplaytime.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pgplaytime_MouseMove);
this.pgplaytime.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pgplaytime_MouseUp);
//
// menuStrip1
//
this.menuStrip1.Dock = System.Windows.Forms.DockStyle.None;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addSongToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(805, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// addSongToolStripMenuItem
//
this.addSongToolStripMenuItem.Name = "addSongToolStripMenuItem";
this.addSongToolStripMenuItem.Size = new System.Drawing.Size(81, 20);
this.addSongToolStripMenuItem.Text = "Open Video";
this.addSongToolStripMenuItem.Click += new System.EventHandler(this.addSongToolStripMenuItem_Click);
//
// wpaudio
//
this.wpaudio.Dock = System.Windows.Forms.DockStyle.Fill;
this.wpaudio.Enabled = true;
this.wpaudio.Location = new System.Drawing.Point(0, 0);
this.wpaudio.Name = "wpaudio";
this.wpaudio.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("wpaudio.OcxState")));
this.wpaudio.Size = new System.Drawing.Size(805, 373);
this.wpaudio.TabIndex = 2;
this.wpaudio.Visible = false;
//
// VideoPlayer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.toolStripContainer1);
this.Name = "VideoPlayer";
this.Size = new System.Drawing.Size(805, 426);
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.ContentPanel.PerformLayout();
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.flcontrols.ResumeLayout(false);
this.flcontrols.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.wpaudio)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private System.Windows.Forms.FlowLayoutPanel flcontrols;
private System.Windows.Forms.Button btnplay;
private Controls.ShiftedProgressBar pgplaytime;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem addSongToolStripMenuItem;
private AxWMPLib.AxWindowsMediaPlayer wpaudio;
}
}

View file

@ -1,147 +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.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShiftOS.WinForms.Controls
{
public partial class ShiftedProgressBar : Control
{
public ShiftedProgressBar()
{
this.SizeChanged += (o, a) =>
{
this.Refresh();
};
var t = new Timer();
t.Interval = 100;
t.Tick += (o, a) =>
{
if(this._style == ProgressBarStyle.Marquee)
{
if(_marqueePos >= this.Width)
{
_marqueePos = 0 - (this.Width / 4);
}
else
{
_marqueePos++;
}
this.Refresh();
}
};
t.Start();
}
private int _value = 0;
private int _max = 100;
public int Value
{
get
{
return _value;
}
set
{
_value = value;
this.Refresh();
}
}
public int Maximum
{
get
{
return _max;
}
set
{
_max = value;
this.Refresh();
}
}
public ProgressBarStyle _style = ProgressBarStyle.Continuous;
public ProgressBarStyle Style
{
get { return _style; }
set { _style = value; this.Refresh(); }
}
private int _blocksize = 5;
public int BlockSize
{
get { return _blocksize; }
set
{
_blocksize = value;
this.Refresh();
}
}
protected override void OnPaint(PaintEventArgs pe)
{
pe.Graphics.Clear(Color.Black);
switch (_style)
{
case ProgressBarStyle.Continuous:
double width = linear(this.Value, 0, this.Maximum, 0, this.Width);
pe.Graphics.FillRectangle(new SolidBrush(Color.Green), new RectangleF(0, 0, (float)width, this.Height));
break;
case ProgressBarStyle.Blocks:
int block_count = this.Width / (this._blocksize + 2);
int blocks = (int)linear(this.Value, 0, this.Maximum, 0, block_count);
for(int i = 0; i < blocks - 1; i++)
{
int position = i * (_blocksize + 2);
pe.Graphics.FillRectangle(new SolidBrush(Color.Green), new Rectangle(position, 0, _blocksize, this.Height));
}
break;
case ProgressBarStyle.Marquee:
pe.Graphics.FillRectangle(new SolidBrush(Color.Green), new Rectangle(_marqueePos, 0, this.Width / 4, this.Height));
break;
}
}
private int _marqueePos = 0;
static private double linear(double x, double x0, double x1, double y0, double y1)
{
if ((x1 - x0) == 0)
{
return (y0 + y1) / 2;
}
return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
}
}
}

View file

@ -1,257 +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.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ShiftOS.Engine;
using ShiftOS.WinForms.Tools;
namespace ShiftOS.WinForms.Controls
{
public class TerminalBox : RichTextBox, ITerminalWidget
{
public void SelectBottom()
{
try
{
this.Select(this.Text.Length, 0);
this.ScrollToCaret();
}
catch { }
}
protected override void Dispose(bool disposing)
{
if (disposing == true)
if(AppearanceManager.ConsoleOut == this)
AppearanceManager.ConsoleOut = null;
base.Dispose(disposing);
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
this.Select(this.TextLength, 0);
}
public void Write(string text)
{
this.HideSelection = true;
this.SelectionFont = ConstructFont();
this.SelectionColor = ControlManager.ConvertColor(ConsoleEx.ForegroundColor);
this.SelectionBackColor = ControlManager.ConvertColor(ConsoleEx.BackgroundColor);
this.AppendText(Localization.Parse(text));
this.HideSelection = false;
}
private Font ConstructFont()
{
FontStyle fs = FontStyle.Regular;
if (ConsoleEx.Bold)
fs = fs | FontStyle.Bold;
if (ConsoleEx.Italic)
fs = fs | FontStyle.Italic;
if (ConsoleEx.Underline)
fs = fs | FontStyle.Underline;
return new Font(this.Font, fs);
}
public void WriteLine(string text)
{
Engine.AudioManager.PlayStream(Properties.Resources.writesound);
this.HideSelection = true;
this.Select(this.TextLength, 0);
this.SelectionFont = ConstructFont();
this.SelectionColor = ControlManager.ConvertColor(ConsoleEx.ForegroundColor);
this.SelectionBackColor = ControlManager.ConvertColor(ConsoleEx.BackgroundColor);
this.AppendText(Localization.Parse(text) + Environment.NewLine);
this.HideSelection = false;
}
bool quickCopying = false;
protected override void OnMouseDown(MouseEventArgs e)
{
//if right-clicking, then we initiate a quick-copy.
if (e.Button == MouseButtons.Right)
quickCopying = true;
//Override the mouse event so that it's a left-click at all times.
base.OnMouseDown(new MouseEventArgs(MouseButtons.Left, e.Clicks, e.X, e.Y, e.Delta));
}
protected override void OnMouseUp(MouseEventArgs mevent)
{
if(quickCopying == true)
{
if (!string.IsNullOrWhiteSpace(this.SelectedText))
{
this.Copy();
}
}
base.OnMouseUp(mevent);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!TerminalBackend.InStory)
{
switch (e.KeyCode) {
case Keys.Add:
case Keys.Alt:
case Keys.Apps:
case Keys.Attn:
case Keys.BrowserBack:
case Keys.BrowserFavorites:
case Keys.BrowserForward:
case Keys.BrowserHome:
case Keys.BrowserRefresh:
case Keys.BrowserSearch:
case Keys.BrowserStop:
case Keys.Cancel:
case Keys.Capital:
case Keys.Clear:
case Keys.Control:
case Keys.ControlKey:
case Keys.Crsel:
case Keys.Decimal:
case Keys.Divide:
case Keys.Down:
case Keys.End:
case Keys.Enter:
case Keys.EraseEof:
case Keys.Escape:
case Keys.Execute:
case Keys.Exsel:
case Keys.F1:
case Keys.F10:
case Keys.F11:
case Keys.F12:
case Keys.F13:
case Keys.F14:
case Keys.F15:
case Keys.F16:
case Keys.F17:
case Keys.F18:
case Keys.F19:
case Keys.F2:
case Keys.F20:
case Keys.F21:
case Keys.F22:
case Keys.F23:
case Keys.F24:
case Keys.F3:
case Keys.F4:
case Keys.F5:
case Keys.F6:
case Keys.F7:
case Keys.F8:
case Keys.F9:
case Keys.FinalMode:
case Keys.HanguelMode:
case Keys.HanjaMode:
case Keys.Help:
case Keys.Home:
case Keys.IMEAccept:
case Keys.IMEConvert:
case Keys.IMEModeChange:
case Keys.IMENonconvert:
case Keys.Insert:
case Keys.JunjaMode:
case Keys.KeyCode:
case Keys.LaunchApplication1:
case Keys.LaunchApplication2:
case Keys.LaunchMail:
case Keys.LButton:
case Keys.LControlKey:
case Keys.Left:
case Keys.LineFeed:
case Keys.LMenu:
case Keys.LShiftKey:
case Keys.LWin:
case Keys.MButton:
case Keys.MediaNextTrack:
case Keys.MediaPlayPause:
case Keys.MediaPreviousTrack:
case Keys.MediaStop:
case Keys.Menu:
case Keys.Modifiers:
case Keys.Multiply:
case Keys.Next:
case Keys.NoName:
case Keys.None:
case Keys.NumLock:
case Keys.Pa1:
case Keys.Packet:
case Keys.PageUp:
case Keys.Pause:
case Keys.Play:
case Keys.Print:
case Keys.PrintScreen:
case Keys.ProcessKey:
case Keys.RButton:
case Keys.RControlKey:
case Keys.Right:
case Keys.RMenu:
case Keys.RShiftKey:
case Keys.RWin:
case Keys.Scroll:
case Keys.Select:
case Keys.SelectMedia:
case Keys.Separator:
case Keys.Shift:
case Keys.ShiftKey:
case Keys.Sleep:
case Keys.Subtract:
case Keys.Tab:
case Keys.Up:
case Keys.VolumeDown:
case Keys.VolumeMute:
case Keys.VolumeUp:
case Keys.XButton1:
case Keys.XButton2:
case Keys.Zoom:
break;
default:
//Engine.AudioManager.PlayStream(Properties.Resources.typesound); // infernal beeping noise only enable for the trailers
break;
}
}
}
public TerminalBox() : base()
{
this.Tag = "keepbg keepfg keepfont";
}
}
}

View file

@ -1,116 +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
{
partial class DownloadControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pcicon = new System.Windows.Forms.PictureBox();
this.lbshiftneturl = new System.Windows.Forms.Label();
this.pgprogress = new ShiftOS.WinForms.Controls.ShiftedProgressBar();
((System.ComponentModel.ISupportInitialize)(this.pcicon)).BeginInit();
this.SuspendLayout();
//
// pcicon
//
this.pcicon.BackColor = System.Drawing.Color.Black;
this.pcicon.Location = new System.Drawing.Point(4, 4);
this.pcicon.Name = "pcicon";
this.pcicon.Size = new System.Drawing.Size(42, 42);
this.pcicon.TabIndex = 1;
this.pcicon.TabStop = false;
//
// lbshiftneturl
//
this.lbshiftneturl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lbshiftneturl.Location = new System.Drawing.Point(52, 4);
this.lbshiftneturl.Name = "lbshiftneturl";
this.lbshiftneturl.Size = new System.Drawing.Size(323, 42);
this.lbshiftneturl.TabIndex = 2;
this.lbshiftneturl.Text = "label1";
this.lbshiftneturl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// pgprogress
//
this.pgprogress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pgprogress.BlockSize = 5;
this.pgprogress.Location = new System.Drawing.Point(4, 52);
this.pgprogress.Maximum = 100;
this.pgprogress.Name = "pgprogress";
this.pgprogress.Size = new System.Drawing.Size(371, 23);
this.pgprogress.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
this.pgprogress.TabIndex = 0;
this.pgprogress.Text = "shiftedProgressBar1";
this.pgprogress.Value = 0;
//
// DownloadControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lbshiftneturl);
this.Controls.Add(this.pcicon);
this.Controls.Add(this.pgprogress);
this.Name = "DownloadControl";
this.Size = new System.Drawing.Size(382, 82);
((System.ComponentModel.ISupportInitialize)(this.pcicon)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Controls.ShiftedProgressBar pgprogress;
private System.Windows.Forms.PictureBox pcicon;
private System.Windows.Forms.Label lbshiftneturl;
}
}

View file

@ -1,600 +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.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using ShiftOS.Engine;
using ShiftOS.Objects;
using ShiftOS.Objects.ShiftFS;
using ShiftOS.Unite;
using ShiftOS.WinForms.Tools;
namespace ShiftOS.WinForms
{
public partial class Oobe : Form, IOobe, ITutorial
{
public Oobe()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
this.BackColor = Color.Black;
this.Load += (o, a) =>
{
ControlManager.SetupControls(this);
};
}
string rtext;
string gtexttotype;
int charcount;
int slashcount;
Label textgeninput;
public bool upgraded = false;
private bool typing = false;
public void TextType(string texttotype)
{
textgeninput.TextAlign = ContentAlignment.MiddleCenter;
while(typing == true)
{
//JESUS CHRIST PAST MICHAEL.
//We should PROBABLY block the thread... You know... not everyone has a 10-core processor.
Thread.Sleep(100);
}
charcount = texttotype.Length;
gtexttotype = texttotype;
slashcount = 1;
foreach (var c in gtexttotype)
{
typing = true;
rtext += c;
this.Invoke(new Action(() =>
{
textgeninput.Text = rtext + "|";
}));
slashcount++;
if (slashcount == 5)
slashcount = 1;
Thread.Sleep(50);
}
rtext += Environment.NewLine;
typing = false;
}
public Save MySave = null;
public event EventHandler OnComplete;
private int tutPrg = 0;
public int TutorialProgress
{
get
{
return tutPrg;
}
set
{
tutPrg = value;
}
}
public void StartShowing(Save save)
{
var t = new Thread(new ThreadStart(() =>
{
try
{
textgeninput = this.lblhackwords;
this.Invoke(new Action(() =>
{
lblHijack.Hide();
}));
TextType(@"Throughout many years, man has tried to develop
a digital environment usable by anyone that never goes
offline, full of AIs and humans alike, thinking, interacting,
innovating.
No one has ever come close to a digital society of such
properties yet, except for one sentient being. It does not
have a life, a gender, an age or a body, but simply one name.
They call it ""DevX"".
If anyone sees this message, my identity is anonymous, but I
need your help. I am trapped within ""DevX""'s digital society
with no way out, constantly under attack.
You must join the digital society, rise up the ranks, and save us.
- undisclosed_0x1DDFB5977.");
Thread.Sleep(5000);
while(this.Opacity > 0f)
{
this.Invoke(new Action(() =>
{
this.Opacity -= 0.01f;
}));
Thread.Sleep(25);
}
Story.Start("mud_fundamentals");
this.Invoke(new Action(this.Close));
}
catch (Exception e)
{
TextType("I have experienced an error.");
TextType(e.ToString());
}
}));
this.Show();
this.BringToFront();
this.TopMost = true;
t.IsBackground = true;
t.Start();
}
public void Clear()
{
this.Invoke(new Action(() =>
{
rtext = "";
textgeninput.Text = "";
}));
}
public void ShowSaveTransfer(Save save)
{
//Stub.
}
public void PerformUniteLogin()
{
}
public void PromptForLogin()
{
Infobox.Show("Login", "Since the last time you've played ShiftOS, some changes have been made to the login system. You must now login using your website credentials.", () =>
{
Infobox.PromptYesNo("Website account", "Do you have an account at http://getshiftos.ml?", (hasAccount) =>
{
if(hasAccount == true)
{
var loginDialog = new UniteLoginDialog((success)=>
{
string token = success;
var uClient = new UniteClient("http://getshiftos.ml", token);
Infobox.Show("Welcome to ShiftOS.", $"Hello, {uClient.GetDisplayName()}! We've signed you into your account. We'll now try to link your ShiftOS account with your save file.", () =>
{
ServerMessageReceived smr = null;
smr = (msg) =>
{
ServerManager.MessageReceived -= smr;
if (msg.Name == "mud_savefile")
{
SaveSystem.CurrentSave = JsonConvert.DeserializeObject<Save>(msg.Contents);
SaveSystem.SaveGame();
}
else if(msg.Name=="mud_login_denied")
{
LinkSaveFile(token);
}
};
ServerManager.MessageReceived += smr;
ServerManager.SendMessage("mud_token_login", token);
});
});
AppearanceManager.SetupDialog(loginDialog);
}
else
{
var signupDialog = new UniteSignupDialog((token) =>
{
ServerMessageReceived smr = null;
smr = (msg) =>
{
ServerManager.MessageReceived -= smr;
if (msg.Name == "mud_savefile")
{
SaveSystem.CurrentSave = JsonConvert.DeserializeObject<Save>(msg.Contents);
SaveSystem.SaveGame();
}
else if (msg.Name == "mud_login_denied")
{
LinkSaveFile(token);
}
};
ServerManager.MessageReceived += smr;
ServerManager.SendMessage("mud_token_login", token);
});
AppearanceManager.SetupDialog(signupDialog);
}
});
});
}
public void LinkSaveFile(string token)
{
if (Utils.FileExists(Paths.GetPath("user.dat")))
{
try
{
var details = JsonConvert.DeserializeObject<ClientSave>(Utils.ReadAllText(Paths.GetPath("user.dat")));
ServerMessageReceived smr = null;
bool msgreceived = false;
bool found = false;
smr = (msg) =>
{
if (msg.Name == "mud_savefile")
{
var save = JsonConvert.DeserializeObject<Save>(msg.Contents);
save.UniteAuthToken = token;
Infobox.Show("Migration complete.", "We have migrated your old save file to the new system successfully. You can still log in using the old system on old builds of ShiftOS.", () =>
{
SaveSystem.CurrentSave = save;
SaveSystem.SaveGame();
found = true;
msgreceived = true;
});
}
else if (msg.Name == "mud_login_denied")
{
found = false;
msgreceived = true;
}
ServerManager.MessageReceived -= smr;
};
ServerManager.MessageReceived += smr;
ServerManager.SendMessage("mud_login", JsonConvert.SerializeObject(new
{
username = details.Username,
password = details.Password
}));
while (msgreceived == false)
Thread.Sleep(10);
if (found == true)
return;
}
catch
{
}
}
var client = new UniteClient("http://getshiftos.ml", token);
var sve = new Save();
sve.Username = client.GetEmail();
sve.Password = Guid.NewGuid().ToString();
sve.SystemName = client.GetSysName();
sve.UniteAuthToken = token;
sve.Codepoints = 0;
sve.Upgrades = new Dictionary<string, bool>();
sve.ID = Guid.NewGuid();
sve.StoriesExperienced = new List<string>();
sve.StoriesExperienced.Add("mud_fundamentals");
Infobox.Show("Welcome to ShiftOS.", "Welcome to ShiftOS, " + client.GetDisplayName() + ". We have created a save file for you. Now, go on and Shift It Your Way.", () =>
{
sve.StoryPosition = 8675309;
SaveSystem.CurrentSave = sve;
Shiftorium.Silent = true;
SaveSystem.SaveGame();
Shiftorium.Silent = false;
});
}
public void ForceReboot()
{
string json = Utils.ExportMount(0);
System.IO.File.WriteAllText(Paths.SaveFile, json);
System.Diagnostics.Process.Start(Application.ExecutablePath);
Environment.Exit(0);
}
public void StartTrailer()
{
while(AppearanceManager.OpenForms.Count > 0)
{
AppearanceManager.OpenForms[0].Close();
}
this.Show();
this.TopMost = true;
this.TransparencyKey = Color.Magenta;
this.BackColor = this.TransparencyKey;
textgeninput = lblHijack;
textgeninput.BackColor = Color.Black;
textgeninput.Font = new Font("Lucida Console", 13F, FontStyle.Bold);
textgeninput.AutoSize = true;
textgeninput.TextAlign = ContentAlignment.MiddleCenter;
textgeninput.TextChanged += (o, a) =>
{
textgeninput.Location = new Point(
(this.Width - textgeninput.Width) / 2,
(this.Height - textgeninput.Height) / 2
);
};
var t = new Thread(() =>
{
Clear();
Thread.Sleep(5000);
TextType("Michael VanOverbeek");
TextType("presents...");
Thread.Sleep(2000);
Clear();
Thread.Sleep(1000);
TextType("A community-developed game");
Thread.Sleep(3000);
Clear();
Thread.Sleep(1000);
this.Invoke(new Action(() =>
{
textgeninput.Font = new Font("Lucida Console", 14F, FontStyle.Bold);
this.BackColor = Color.Black;
}));
TextType("Welcome to ShiftOS.");
Thread.Sleep(4000);
Clear();
textgeninput = lblhackwords;
TextType("Hello.");
Thread.Sleep(500);
TextType("You have been cordially and involuntarily selected to participate in the development and testing of an experimental operating system called ShiftOS.");
Thread.Sleep(500);
TextType("I want ShiftOS to be the most advanced operating system in the world.");
Thread.Sleep(500);
TextType("In ShiftOS, you start out with nothing.");
Thread.Sleep(500);
TextType("And your goal is to upgrade the operating system from a barebones command line to a fully graphical operating system.");
Thread.Sleep(500);
TextType("Along the way, you'll meet many people - hackers, rebels, programmers, administrators and many more.");
Thread.Sleep(500);
TextType("You'll meet new friends and foes.");
Thread.Sleep(500);
TextType("Your goal: Take it over. Upgrade the operating system, and take over its multi-user domain.");
Thread.Sleep(500);
TextType("I won't reveal quite what you have to do, but if you can handle it, head over to http://getshiftos.ml/ and download the operating system now.");
Thread.Sleep(5000);
Clear();
textgeninput = lblHijack;
TextType("Think you can handle it?");
});
t.IsBackground = false;
t.Start();
}
public void Start()
{
Shiftorium.Silent = false;
foreach(var frm in AppearanceManager.OpenForms)
{
(frm as Form).Invoke(new Action(() => {
frm.Close();
}));
}
TerminalBackend.CommandProcessed += (cmd, args) =>
{
if(cmd == "sos.help")
{
if (TutorialProgress == 0)
TutorialProgress = 1;
}
else if(cmd == "sos.status")
{
if (TutorialProgress == 1)
TutorialProgress = 2;
}
else if(cmd == "shiftorium.list")
{
if (TutorialProgress == 2)
{
TutorialProgress = 3;
SaveSystem.TransferCodepointsFrom("sys", 50);
}
}
else if(cmd == "shiftorium.info" && args == "{\"upgrade\":\"mud_fundamentals\"}")
{
if (TutorialProgress == 3)
TutorialProgress = 4;
}
else if(cmd == "win.open")
{
if (TutorialProgress == 4)
TutorialProgress = 5;
}
};
if(this.Visible == false)
this.Show();
var t = new Thread(() =>
{
textgeninput = lblHijack;
Clear();
textgeninput = lblhackwords;
Clear();
this.Invoke(new Action(() =>
{
textgeninput.Font = SkinEngine.LoadedSkin.TerminalFont;
}));
TextType("ShiftOS has been installed successfully.");
Thread.Sleep(500);
TextType("Before you can continue to the operating system, here's a little tutorial on how to use it.");
Thread.Sleep(500);
TextType("Starting a Terminal...");
Applications.Terminal term = null;
this.Invoke(new Action(() =>
{
term = new Applications.Terminal();
this.Controls.Add(term);
term.Location = new Point(
(this.Width - term.Width) / 2,
(this.Height - term.Height) / 2
);
term.Show();
term.OnLoad();
term.OnSkinLoad();
term.OnUpgrade();
}));
TextType("This little text box is called a Terminal.");
Thread.Sleep(500);
TextType("Normally, it would appear in full-screen, but this window is hosting it as a control so you can see this text as well.");
Thread.Sleep(500);
TextType("In ShiftOS, the Terminal is your main control centre for the operating system. You can see system status, check Codepoints, open other programs, buy upgrades, and more.");
Thread.Sleep(500);
TextType("Go ahead and type 'sos.help' to see a list of commands.");
while (TutorialProgress == 0)
{
//JESUS CHRIST PAST MICHAEL.
//We should PROBABLY block the thread... You know... not everyone has a 10-core processor.
Thread.Sleep(100);
}
TextType("As you can see, sos.help gives you a list of all commands in the system.");
Thread.Sleep(500);
TextType("You can run any command, by typing in their Namespace, followed by a period (.), followed by their Command Name.");
Thread.Sleep(500);
TextType("Go ahead and run the 'status' command within the 'sos' namespace to see what the command does.");
while (TutorialProgress == 1)
{
//JESUS CHRIST PAST MICHAEL.
//We should PROBABLY block the thread... You know... not everyone has a 10-core processor.
Thread.Sleep(100);
}
TextType("Brilliant. The sos.status command will tell you how many Codepoints you have, as well as how many upgrades you have installed and how many are available.");
Thread.Sleep(500);
TextType("Codepoints, as you know, are a special currency within ShiftOS. They are used to buy things within the multi-user domain, such as upgrades, scripts, and applications.");
Thread.Sleep(500);
TextType("You can earn Codepoints by doing things in ShiftOS - such as completing jobs for other users, making things like skins, scripts, documents, etc, and playing games like Pong.");
Thread.Sleep(500);
TextType("At times, you'll be given Codepoints to help complete a task. You will receive Codepoints from 'sys' - the multi-user domain itself.");
//SaveSystem.TransferCodepointsFrom("sys", 50);
TextType("Right now, you don't have any upgrades. Upgrades can give ShiftOS additional features and capabilities - like new core applications, supported file types, and new Terminal commands.");
Thread.Sleep(500);
TextType("You can easily get upgrades using the Shiftorium - a repository of approved ShiftOS upgrades.");
Thread.Sleep(500);
TextType("To start using the Shiftorium, simply type 'shiftorium.list' to see available upgrades.");
while (TutorialProgress == 2)
{
//JESUS CHRIST PAST MICHAEL.
//We should PROBABLY block the thread... You know... not everyone has a 10-core processor.
Thread.Sleep(100);
}
Clear();
TextType("Right now, you have enough Codepoints to buy the 'mud_fundamentals' upgrade. You can use shiftorium.info to see information about this upgrade.");
Thread.Sleep(500);
TextType("Some commands, like shiftorium.info, require you to pass information to them in the form of arguments.");
Thread.Sleep(500);
TextType("Argument pairs sit at the end of the command, and are enclosed in curly braces.");
Thread.Sleep(500);
TextType("Inside these curly braces, you can input an argument key, followed by a colon, followed by the value. Then, if you need multiple arguments, you can put a comma after the value, and then insert another argument pair.");
Thread.Sleep(500);
TextType("There are different value types - numeric values, which can be any positive or negative 32-bit integer");
Thread.Sleep(500);
TextType("Then there are boolean values which can be either 'true' or 'false'");
Thread.Sleep(500);
TextType("Then there are string values, which are enclosed in double-quotes.");
Thread.Sleep(500);
TextType(" If for some reason you need to use a double-quote inside a string, you must escape it using a single backslash followed by the quote, like this: key:\"My \\\"awesome\\\" value.\"");
Thread.Sleep(500);
TextType("If you want to escape a backslash inside a string, simply type two backslashes instead of one - for example key:\"Back\\\\slash.\"");
Thread.Sleep(500);
TextType("shiftorium.info requires an upgrade argument, which is a string type. Go ahead and give shiftorium.info's upgrade argument the 'mud_fundamentals' upgrade's ID.");
while (TutorialProgress == 3)
{
//JESUS CHRIST PAST MICHAEL.
//We should PROBABLY block the thread... You know... not everyone has a 10-core processor.
Thread.Sleep(100);
}
TextType("As you can see, mud_fundamentals is very useful. In fact, a lot of useful upgrades depend on it. You should buy it!");
Thread.Sleep(500);
TextType("shiftorium.info already gave you a command that will let you buy the upgrade - go ahead and run that command!");
while (!Shiftorium.UpgradeInstalled("mud_fundamentals"))
{ //JESUS CHRIST PAST MICHAEL.
//We should PROBABLY block the thread... You know... not everyone has a 10-core processor.
Thread.Sleep(100);
}
TextType("Hooray! You now have the MUD Fundamentals upgrade.");
Thread.Sleep(500);
TextType("You can also earn more Codepoints by playing Pong. To open Pong, you can use the win.open command.");
Thread.Sleep(500);
TextType("If you run win.open without arguments, you can see a list of applications that you can open.");
Thread.Sleep(500);
TextType("Just run win.open without arguments, and this tutorial will be completed!");
while (TutorialProgress == 4)
{
//JESUS CHRIST PAST MICHAEL.
//We should PROBABLY block the thread... You know... not everyone has a 10-core processor.
Thread.Sleep(100);
}
TextType("This concludes the ShiftOS beginners' guide brought to you by the multi-user domain. Stay safe in a connected world.");
Thread.Sleep(2000);
Desktop.InvokeOnWorkerThread(() =>
{
OnComplete?.Invoke(this, EventArgs.Empty);
SaveSystem.CurrentSave.StoryPosition = 2;
this.Close();
SaveSystem.SaveGame();
AppearanceManager.SetupWindow(new Applications.Terminal());
});
});
t.IsBackground = true;
t.Start();
}
}
}

View file

@ -1,269 +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.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using ShiftOS.Engine;
using Newtonsoft.Json;
using static ShiftOS.Objects.ShiftFS.Utils;
using ShiftOS.WinForms.Applications;
using ShiftOS.WinForms.Tools;
using System.Reflection;
using System.IO;
namespace ShiftOS.WinForms
{
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//if ANYONE puts code before those two winforms config lines they will be declared a drunky. - Michael
LoginManager.Init(new GUILoginFrontend());
CrashHandler.SetGameMetadata(Assembly.GetExecutingAssembly());
SkinEngine.SetIconProber(new ShiftOSIconProvider());
ShiftOS.Engine.AudioManager.Init(new ShiftOSAudioProvider());
Localization.RegisterProvider(new WFLanguageProvider());
AppearanceManager.OnExit += () =>
{
Environment.Exit(0);
};
TutorialManager.RegisterTutorial(new Oobe());
TerminalBackend.TerminalRequested += () =>
{
AppearanceManager.SetupWindow(new Applications.Terminal());
};
Infobox.Init(new Dialog());
FileSkimmerBackend.Init(new WinformsFSFrontend());
var desk = new WinformsDesktop();
Desktop.Init(desk);
OutOfBoxExperience.Init(new Oobe());
AppearanceManager.Initiate(new WinformsWindowManager());
Application.Run(desk);
}
}
internal class ShiftOSIconProvider : IIconProber
{
public Image GetIcon(DefaultIconAttribute attr)
{
var res = typeof(Properties.Resources);
foreach(var prop in res.GetProperties(BindingFlags.NonPublic | BindingFlags.Static))
{
if(prop.PropertyType.BaseType == typeof(Image))
{
if(prop.Name == attr.ID)
{
return prop.GetValue(null) as Image;
}
}
}
return new Bitmap(16, 16);
}
}
[ShiftoriumProvider]
internal class WinformsShiftoriumProvider : IShiftoriumProvider
{
public List<ShiftoriumUpgrade> GetDefaults()
{
var defaultList = JsonConvert.DeserializeObject<List<ShiftoriumUpgrade>>(Properties.Resources.Shiftorium);
foreach(var exe in Directory.GetFiles(Environment.CurrentDirectory))
{
if (exe.EndsWith(".exe") || exe.EndsWith(".dll"))
{
try
{
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);
}
}
}
catch { }
}
}
return defaultList;
}
}
public class WinformsFSFrontend : IFileSkimmer
{
public void OpenDirectory(string path)
{
var fs = new Applications.FileSkimmer();
AppearanceManager.SetupWindow(fs);
fs.ChangeDirectory(path);
}
public void GetPath(string[] filetypes, FileOpenerStyle style, Action<string> callback)
{
AppearanceManager.SetupDialog(new Applications.FileDialog(filetypes, style, callback));
}
public void OpenFile(string path)
{
try
{
switch (FileSkimmerBackend.GetFileType(path))
{
case FileType.TextFile:
if (!Shiftorium.UpgradeInstalled("textpad"))
throw new Exception();
var txt = new TextPad();
AppearanceManager.SetupWindow(txt);
txt.LoadFile(path);
break;
case FileType.Executable:
//NYI
throw new Exception();
case FileType.Lua:
try
{
var runner = new Engine.Scripting.LuaInterpreter();
runner.ExecuteFile(path);
}
catch (Exception ex)
{
Infobox.Show("{LUA_ERROR}", ex.Message);
}
break;
case FileType.JSON:
//NYI
throw new Exception();
case FileType.Filesystem:
MountPersistent(path);
//If this doesn't fail...
FileSkimmerBackend.OpenDirectory((Mounts.Count - 1).ToString() + ":");
break;
case FileType.Skin:
if (!Shiftorium.UpgradeInstalled("skinning"))
throw new Exception();
var sl = new Skin_Loader();
AppearanceManager.SetupWindow(sl);
sl.LoadedSkin = JsonConvert.DeserializeObject<Skin>(ReadAllText(path));
sl.SetupUI();
break;
case FileType.Image:
if (!Shiftorium.UpgradeInstalled("artpad_open"))
throw new Exception();
var ap = new Artpad();
AppearanceManager.SetupWindow(ap);
ap.LoadPicture(path);
break;
default:
throw new Exception();
}
}
catch
{
Infobox.Show("{NO_APP_TO_OPEN}", "{NO_APP_TO_OPEN_EXP}");
}
}
public Image GetImage(string path)
{
return Applications.FileSkimmer.GetImage(FileSkimmerBackend.GetFileType(path));
}
public string GetFileExtension(FileType fileType)
{
switch (fileType)
{
case FileType.Executable:
return ".saa";
case FileType.Filesystem:
return ".mfs";
case FileType.Image:
return ".pic";
case FileType.JSON:
return ".json";
case FileType.Lua:
return ".lua";
case FileType.Python:
return ".py";
case FileType.Skin:
return ".skn";
case FileType.TextFile:
return ".txt";
default:
return ".bin";
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,300 +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.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ShiftOS.Engine;
using static ShiftOS.Engine.AppearanceManager;
namespace ShiftOS.WinForms.Tools
{
public static class ControlManager
{
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
parent.Refresh();
}
public static void Close(this UserControl ctrl)
{
for (int i = 0; i < AppearanceManager.OpenForms.Count; i++)
{
if (OpenForms[i].ParentWindow == ctrl)
{
(OpenForms[i] as Form).Close();
return;
}
}
}
internal static Color ConvertColor(ConsoleColor cCol)
{
switch (cCol)
{
case ConsoleColor.Black:
return Color.Black;
case ConsoleColor.Gray:
return Color.Gray;
case ConsoleColor.DarkGray:
return Color.DarkGray;
case ConsoleColor.Blue:
return Color.Blue;
case ConsoleColor.Cyan:
return Color.Cyan;
case ConsoleColor.DarkBlue:
return Color.DarkBlue;
case ConsoleColor.DarkCyan:
return Color.DarkCyan;
case ConsoleColor.DarkGreen:
return Color.DarkGreen;
case ConsoleColor.DarkMagenta:
return Color.DarkMagenta;
case ConsoleColor.DarkRed:
return Color.DarkRed;
case ConsoleColor.DarkYellow:
return Color.YellowGreen;
case ConsoleColor.Yellow:
return Color.Yellow;
case ConsoleColor.Green:
return Color.Green;
case ConsoleColor.Magenta:
return Color.Magenta;
case ConsoleColor.Red:
return Color.Red;
case ConsoleColor.White:
return Color.White;
default:
return Color.Black;
}
}
public static void SetCursor(Control ctrl)
{
#if STUPID
if (!(ctrl is WebBrowser))
{
var mouse = SkinEngine.GetImage("mouse");
if (mouse == null)
mouse = Properties.Resources.DefaultMouse;
var mBmp = new Bitmap(mouse);
mBmp.MakeTransparent(Color.FromArgb(1, 0, 1));
var gfx = Graphics.FromImage(mBmp);
var handle = mBmp.GetHicon();
var cursor = new Cursor(handle);
ctrl.Cursor = cursor;
}
#endif
}
/// <summary>
/// Centers the control along its parent.
/// </summary>
/// <param name="ctrl">The control to center (this is an extension method - you can call it on a control as though it was a method in that control)</param>
public static void CenterParent(this Control ctrl)
{
ctrl.Location = new Point(
(ctrl.Parent.Width - ctrl.Width) / 2,
(ctrl.Parent.Height - ctrl.Height) / 2
);
}
public static void SetupControl(Control ctrl)
{
Desktop.InvokeOnWorkerThread(new Action(() =>
{
ctrl.SuspendLayout();
}));
if (!(ctrl is MenuStrip) && !(ctrl is ToolStrip) && !(ctrl is StatusStrip) && !(ctrl is ContextMenuStrip))
{
string tag = "";
try
{
if(ctrl.Tag != null)
tag = ctrl.Tag.ToString();
}
catch { }
if (!tag.Contains("keepbg"))
{
if (ctrl.BackColor != Control.DefaultBackColor)
{
Desktop.InvokeOnWorkerThread(() =>
{
ctrl.BackColor = SkinEngine.LoadedSkin.ControlColor;
});
}
}
if (!tag.Contains("keepfont"))
{
Desktop.InvokeOnWorkerThread(() =>
{
ctrl.ForeColor = SkinEngine.LoadedSkin.ControlTextColor;
ctrl.Font = SkinEngine.LoadedSkin.MainFont;
});
if (tag.Contains("header1"))
{
Desktop.InvokeOnWorkerThread(() =>
{
ctrl.Font = SkinEngine.LoadedSkin.HeaderFont;
});
}
if (tag.Contains("header2"))
{
Desktop.InvokeOnWorkerThread(() =>
{
ctrl.Font = SkinEngine.LoadedSkin.Header2Font;
});
}
if (tag.Contains("header3"))
{
Desktop.InvokeOnWorkerThread(() =>
{
ctrl.Font = SkinEngine.LoadedSkin.Header3Font;
});
}
}
try
{
string ctrlText = Localization.Parse(ctrl.Text);
Desktop.InvokeOnWorkerThread(() =>
{
ctrl.Text = ctrlText;
});
}
catch
{
}
ctrl.KeyDown += (o, a) =>
{
if (a.Control && a.KeyCode == Keys.T)
{
a.SuppressKeyPress = true;
Engine.AppearanceManager.SetupWindow(new Applications.Terminal());
}
ShiftOS.Engine.Scripting.LuaInterpreter.RaiseEvent("on_key_down", a);
//a.Handled = true;
};
if (ctrl is Button)
{
Desktop.InvokeOnWorkerThread(() =>
{
(ctrl as Button).FlatStyle = FlatStyle.Flat;
});
}
else if (ctrl is WindowBorder)
{
Desktop.InvokeOnWorkerThread(() =>
{
(ctrl as WindowBorder).Setup();
});
}
}
Desktop.InvokeOnWorkerThread(() =>
{
MakeDoubleBuffered(ctrl);
ctrl.ResumeLayout();
});
ControlSetup?.Invoke(ctrl);
}
public static event Action<Control> ControlSetup;
public static void MakeDoubleBuffered(Control c)
{
if (System.Windows.Forms.SystemInformation.TerminalServerSession)
return;
System.Reflection.PropertyInfo aProp =
typeof(System.Windows.Forms.Control).GetProperty(
"DoubleBuffered",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
aProp.SetValue(c, true, null);
}
public static void SetupControls(Control frm, bool runInThread = true)
{
SetupControl(frm);
frm.Click += (o, a) =>
{
Desktop.HideAppLauncher();
};
ThreadStart ts = () =>
{
for (int i = 0; i < frm.Controls.Count; i++)
{
SetupControls(frm.Controls[i], false);
}
};
if (runInThread == true)
{
var t = new Thread(ts);
t.IsBackground = true;
t.Start();
}
else
{
ts?.Invoke();
}
}
}
}

View file

@ -1,402 +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 FLOYDSTEINBERG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Threading;
using ShiftOS.Engine;
using System.Runtime.InteropServices;
namespace ShiftOS.WinForms.Tools
{
public static class DitheringEngine
{
public static Color GetColor(Color source)
{
if (Shiftorium.UpgradeInstalled("color_depth_24_bits"))
{
return Color.FromArgb(source.R, source.G, source.B); //get rid of the alpha channel.
}
else
{
if (Shiftorium.UpgradeInstalled("color_depth_16_bits"))
{
byte r = (byte)linear(source.R, 0, 0xFF, 0, 0x1F);
byte g = (byte)linear(source.G, 0, 0xFF, 0, 0x3F);
byte b = (byte)linear(source.B, 0, 0xFF, 0, 0x1F);
return Color.FromArgb(r, g, b);
}
else
{
int gray = (source.R + source.G + source.B) / 3;
if (Shiftorium.UpgradeInstalled("color_depth_8_bits"))
return Color.FromArgb(gray, gray, gray);
else
{
if (Shiftorium.UpgradeInstalled("color_depth_6_bits"))
{
int gray6 = (int)linear(gray, 0, 0xFF, 0, 0x3F) * 3;
return Color.FromArgb(gray6, gray6, gray6);
}
else
{
if (Shiftorium.UpgradeInstalled("color_depth_4_bits"))
{
int gray4 = (int)linear(linear(gray, 0, 0xFF, 0, 0xF), 0, 0xF, 0, 0xFF) * 0xF;
return Color.FromArgb(gray4, gray4, gray4);
}
else
{
if (Shiftorium.UpgradeInstalled("color_depth_2_bits"))
{
int gray2 = (int)linear(linear(gray, 0, 0xFF, 0, 0x3), 0, 0x3, 0, 0xFF) * 63;
return Color.FromArgb(gray2, gray2, gray2);
}
else {
if (gray >= 127)
{
return Color.Black;
}
else
{
return Color.White;
}
}
}
}
}
}
}
}
public static void DitherColor(Color source, int width, int height, Action<Image> result)
{
var bmp = new Bitmap(width + 1, height + 1);
var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
byte[] rgb = new byte[Math.Abs(data.Stride) * data.Height];
Marshal.Copy(data.Scan0, rgb, 0, rgb.Length);
for (int i = 0; i < rgb.Length - 3; i += 3)
{
rgb[i] = source.R;
rgb[i + 1] = source.G;
rgb[i + 2] = source.B;
}
Marshal.Copy(rgb, 0, data.Scan0, rgb.Length);
bmp.UnlockBits(data);
DitherImage(bmp, result);
}
static private double linear(double x, double x0, double x1, double y0, double y1)
{
if ((x1 - x0) == 0)
{
return (y0 + y1) / 2;
}
return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
}
#if NODITHER
public static void DitherImage(Image source, Action<Image> result)
{
Desktop.InvokeOnWorkerThread(new Action(() =>
{
result?.Invoke(source);
}));
}
#endif
#if BINARIZE
public static void DitherImage(Image source, Action<Image> result)
{
if (source == null)
{
result?.Invoke(source);
return;
}
var t = new Thread(new ThreadStart(() =>
{
var bmp = new Bitmap(source.Width, source.Height);
var sourceBmp = (Bitmap)source;
int error = 0;
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
Color c = sourceBmp.GetPixel(x, y);
int gray = ((c.R + c.G + c.B) / 3);
if (gray >= 127)
{
error = gray - 255;
bmp.SetPixel(x, y, Color.White);
}
else
{
error = gray;
bmp.SetPixel(x, y, Color.Black);
}
}
}
Desktop.InvokeOnWorkerThread(new Action(() => { result?.Invoke(bmp); }));
}));
t.IsBackground = true;
t.Start();
}
#endif
#if DITHER1D
public static void DitherImage(Image source, Action<Image> result)
{
if (source == null)
{
result?.Invoke(source);
return;
}
var t = new Thread(new ThreadStart(() =>
{
var bmp = new Bitmap(source.Width, source.Height);
var sourceBmp = (Bitmap)source;
int error = 0;
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
Color c = sourceBmp.GetPixel(x, y);
int gray = ((c.R + c.G + c.B) / 3) + error;
if (gray >= 127)
{
error = gray - 255;
bmp.SetPixel(x, y, Color.White);
}
else
{
error = gray;
bmp.SetPixel(x, y, Color.Black);
}
}
}
Desktop.InvokeOnWorkerThread(new Action(() => { result?.Invoke(bmp); }));
}));
t.IsBackground = true;
t.Start();
}
#endif
#if FLOYDSTEINBERG
public static void DitherImage(Image source, Action<Image> result)
{
if (source == null)
{
result?.Invoke(source);
return;
}
var bmp = new Bitmap(source.Width, source.Height);
var sourceBmp = (Bitmap)source;
var sourceLck = sourceBmp.LockBits(new Rectangle(0, 0, sourceBmp.Width, sourceBmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var destLck = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
int error_r = 0;
int sourceBytes = Math.Abs(sourceLck.Stride) * sourceLck.Height;
int destBytes = Math.Abs(destLck.Stride) * destLck.Height;
IntPtr sourcePtr = sourceLck.Scan0;
IntPtr destPtr = destLck.Scan0;
byte[] destArr = new byte[destBytes];
byte[] sourceArr = new byte[sourceBytes];
byte[] grays = new byte[destBytes];
Marshal.Copy(sourcePtr, sourceArr, 0, sourceBytes);
Marshal.Copy(destPtr, destArr, 0, destBytes);
int width = Math.Abs(destLck.Stride);
int height = destLck.Height;
bool sixteenBits = Shiftorium.UpgradeInstalled("color_depth_16_bits");
bool twoBits = Shiftorium.UpgradeInstalled("color_depth_2_bits");
bool sixBits = Shiftorium.UpgradeInstalled("color_depth_6_bits");
bool fourBits = Shiftorium.UpgradeInstalled("color_depth_4_bits");
bool eightBits = Shiftorium.UpgradeInstalled("color_depth_8_bits");
bool color_depth_floydsteinberg = Shiftorium.UpgradeInstalled("color_depth_floyd-steinberg_dithering");
bool dithering = Shiftorium.UpgradeInstalled("color_depth_dithering");
for (int y = 0; y < (destLck.Height); y++)
{
for (int x = 0; x < (Math.Abs(destLck.Stride)); x += 3)
{
int i = getIndexFromXY(x, y, width);
byte red = sourceArr[i];
byte green = sourceArr[i + 1];
byte blue = sourceArr[i + 2];
Color oldc = Color.FromArgb(red, green, blue);
Color newc;
if (sixteenBits)
{
newc = GetColor(oldc);
}
else
{
int gray = ((oldc.R + oldc.G + oldc.B) / 3);
byte newgray = 0;
if (dithering && !color_depth_floydsteinberg)
gray += error_r;
if (eightBits)
{
newgray = (byte)gray;
error_r = 0;
}
else if(sixBits)
{
newgray = (byte)(linear(gray, 0, 0xFF, 0, 0x3F) * 3);
error_r = newgray - gray;
}
else if (fourBits)
{
newgray = (byte)(linear(gray, 0, 0xFF, 0, 0xF) * 0xF);
error_r = newgray - gray;
}
else if (twoBits)
{
if (gray >= 191)
newgray = 0xFF;
else if (gray >= 127)
newgray = Color.LightGray.R;
else if (gray >= 64)
newgray = Color.DarkGray.R;
else
newgray = 0x00;
error_r = newgray - gray;
}
else
{
if (gray >= 127)
newgray = 0xFF;
else
newgray = 0x00;
error_r = newgray - gray;
}
newc = Color.FromArgb(newgray, newgray, newgray);
}
int nextIndex = getIndexFromXY(x + 3, y, width);
int nextRow = getIndexFromXY(x, y + 1, width);
int nextIndexOnNextRow = getIndexFromXY(x + 3, y + 1, width);
int prevIndexOnNextRow = getIndexFromXY(x - 3, y + 1, width);
grays[i] = newc.R;
grays[i + 1] = newc.G;
grays[i + 2] = newc.B;
if (dithering)
{
if (color_depth_floydsteinberg)
{
if (x + 3 < width)
{
sourceArr[nextIndex] += (byte)((error_r * 7) / 16);
sourceArr[nextIndex + 1] += (byte)((error_r * 7) / 16);
sourceArr[nextIndex + 2] += (byte)((error_r * 7) / 16);
}
if (y + 1 < height)
{
sourceArr[nextRow] += (byte)((error_r) / 16);
sourceArr[nextRow + 1] += (byte)((error_r) / 16);
sourceArr[nextRow + 2] += (byte)((error_r) / 16);
}
if (x + 3 < width && y + 1 < height)
{
sourceArr[nextIndexOnNextRow] += (byte)((error_r * 3) / 16);
sourceArr[nextIndexOnNextRow + 1] += (byte)((error_r * 3) / 16);
sourceArr[nextIndexOnNextRow + 2] += (byte)((error_r * 3) / 16);
}
if (x - 3 > 0 && y + 1 < height)
{
sourceArr[prevIndexOnNextRow] += (byte)((error_r * 5) / 16);
sourceArr[prevIndexOnNextRow + 1] += (byte)((error_r * 5) / 16);
sourceArr[prevIndexOnNextRow + 2] += (byte)((error_r * 5) / 16);
}
}
}
}
}
for (int i = 0; i < destArr.Length - 3; i++)
{
destArr[i] = grays[i];
}
Marshal.Copy(destArr, 0, destPtr, destBytes);
bmp.UnlockBits(destLck);
Desktop.InvokeOnWorkerThread(new Action(() => { result?.Invoke(bmp); }));
}
#endif
private static int getIndexFromXY(int x, int y, int width)
{
return (width * y) + x;
}
}
}

View file

@ -1,312 +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
{
partial class WinformsDesktop
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.desktoppanel = new System.Windows.Forms.Panel();
this.btnnotifications = new System.Windows.Forms.Button();
this.lbtime = new System.Windows.Forms.Label();
this.panelbuttonholder = new System.Windows.Forms.FlowLayoutPanel();
this.sysmenuholder = new System.Windows.Forms.Panel();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.apps = new System.Windows.Forms.ToolStripMenuItem();
this.pnlscreensaver = new System.Windows.Forms.Panel();
this.pnlwidgetlayer = new System.Windows.Forms.Panel();
this.pnlssicon = new System.Windows.Forms.Panel();
this.pnladvancedal = new System.Windows.Forms.Panel();
this.flapps = new System.Windows.Forms.FlowLayoutPanel();
this.flcategories = new System.Windows.Forms.FlowLayoutPanel();
this.pnlalsystemactions = new System.Windows.Forms.Panel();
this.btnshutdown = new System.Windows.Forms.Button();
this.pnlstatus = new System.Windows.Forms.Panel();
this.lbalstatus = new System.Windows.Forms.Label();
this.desktoppanel.SuspendLayout();
this.sysmenuholder.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.pnlscreensaver.SuspendLayout();
this.pnladvancedal.SuspendLayout();
this.pnlalsystemactions.SuspendLayout();
this.pnlstatus.SuspendLayout();
this.SuspendLayout();
//
// desktoppanel
//
this.desktoppanel.BackColor = System.Drawing.Color.Green;
this.desktoppanel.Controls.Add(this.btnnotifications);
this.desktoppanel.Controls.Add(this.lbtime);
this.desktoppanel.Controls.Add(this.panelbuttonholder);
this.desktoppanel.Controls.Add(this.sysmenuholder);
this.desktoppanel.Dock = System.Windows.Forms.DockStyle.Top;
this.desktoppanel.Location = new System.Drawing.Point(0, 0);
this.desktoppanel.Name = "desktoppanel";
this.desktoppanel.Size = new System.Drawing.Size(1296, 24);
this.desktoppanel.TabIndex = 0;
this.desktoppanel.Paint += new System.Windows.Forms.PaintEventHandler(this.desktoppanel_Paint);
//
// btnnotifications
//
this.btnnotifications.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnnotifications.AutoSize = true;
this.btnnotifications.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnnotifications.BackColor = System.Drawing.Color.Transparent;
this.btnnotifications.FlatAppearance.BorderSize = 0;
this.btnnotifications.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnnotifications.Location = new System.Drawing.Point(1066, -2);
this.btnnotifications.Name = "btnnotifications";
this.btnnotifications.Size = new System.Drawing.Size(136, 24);
this.btnnotifications.TabIndex = 3;
this.btnnotifications.Text = "Notifications (0)";
this.btnnotifications.UseVisualStyleBackColor = false;
this.btnnotifications.Click += new System.EventHandler(this.btnnotifications_Click);
//
// lbtime
//
this.lbtime.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.lbtime.AutoSize = true;
this.lbtime.Location = new System.Drawing.Point(3, 0);
this.lbtime.Name = "lbtime";
this.lbtime.Size = new System.Drawing.Size(49, 14);
this.lbtime.TabIndex = 0;
this.lbtime.Text = "label1";
this.lbtime.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.lbtime.Click += new System.EventHandler(this.lbtime_Click);
//
// panelbuttonholder
//
this.panelbuttonholder.AutoSize = true;
this.panelbuttonholder.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.panelbuttonholder.Location = new System.Drawing.Point(107, -77);
this.panelbuttonholder.Name = "panelbuttonholder";
this.panelbuttonholder.Size = new System.Drawing.Size(0, 0);
this.panelbuttonholder.TabIndex = 2;
//
// sysmenuholder
//
this.sysmenuholder.Controls.Add(this.menuStrip1);
this.sysmenuholder.Location = new System.Drawing.Point(12, 5);
this.sysmenuholder.Name = "sysmenuholder";
this.sysmenuholder.Size = new System.Drawing.Size(68, 24);
this.sysmenuholder.TabIndex = 1;
//
// menuStrip1
//
this.menuStrip1.Dock = System.Windows.Forms.DockStyle.Fill;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.apps});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Padding = new System.Windows.Forms.Padding(0);
this.menuStrip1.Size = new System.Drawing.Size(68, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// apps
//
this.apps.AutoSize = false;
this.apps.Name = "apps";
this.apps.Padding = new System.Windows.Forms.Padding(0);
this.apps.Size = new System.Drawing.Size(58, 20);
this.apps.Tag = "applauncherbutton";
this.apps.Text = "ShiftOS";
this.apps.Click += new System.EventHandler(this.apps_Click);
//
// pnlscreensaver
//
this.pnlscreensaver.Controls.Add(this.pnlssicon);
this.pnlscreensaver.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlscreensaver.Location = new System.Drawing.Point(0, 24);
this.pnlscreensaver.Name = "pnlscreensaver";
this.pnlscreensaver.Size = new System.Drawing.Size(1296, 714);
this.pnlscreensaver.TabIndex = 1;
this.pnlscreensaver.Visible = false;
//
// pnlwidgetlayer
//
this.pnlwidgetlayer.BackColor = System.Drawing.Color.Transparent;
this.pnlwidgetlayer.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlwidgetlayer.Location = new System.Drawing.Point(0, 24);
this.pnlwidgetlayer.Name = "pnlwidgetlayer";
this.pnlwidgetlayer.Size = new System.Drawing.Size(1296, 714);
this.pnlwidgetlayer.TabIndex = 1;
//
// pnlssicon
//
this.pnlssicon.Location = new System.Drawing.Point(303, 495);
this.pnlssicon.Name = "pnlssicon";
this.pnlssicon.Size = new System.Drawing.Size(200, 100);
this.pnlssicon.TabIndex = 0;
//
// pnladvancedal
//
this.pnladvancedal.Controls.Add(this.flapps);
this.pnladvancedal.Controls.Add(this.flcategories);
this.pnladvancedal.Controls.Add(this.pnlalsystemactions);
this.pnladvancedal.Controls.Add(this.pnlstatus);
this.pnladvancedal.Location = new System.Drawing.Point(0, 24);
this.pnladvancedal.Name = "pnladvancedal";
this.pnladvancedal.Size = new System.Drawing.Size(433, 417);
this.pnladvancedal.TabIndex = 1;
this.pnladvancedal.Visible = false;
//
// flapps
//
this.flapps.Dock = System.Windows.Forms.DockStyle.Fill;
this.flapps.Location = new System.Drawing.Point(221, 58);
this.flapps.Name = "flapps";
this.flapps.Size = new System.Drawing.Size(212, 328);
this.flapps.TabIndex = 3;
//
// flcategories
//
this.flcategories.Dock = System.Windows.Forms.DockStyle.Left;
this.flcategories.Location = new System.Drawing.Point(0, 58);
this.flcategories.Name = "flcategories";
this.flcategories.Size = new System.Drawing.Size(221, 328);
this.flcategories.TabIndex = 2;
//
// pnlalsystemactions
//
this.pnlalsystemactions.Controls.Add(this.btnshutdown);
this.pnlalsystemactions.Dock = System.Windows.Forms.DockStyle.Bottom;
this.pnlalsystemactions.Location = new System.Drawing.Point(0, 386);
this.pnlalsystemactions.Name = "pnlalsystemactions";
this.pnlalsystemactions.Size = new System.Drawing.Size(433, 31);
this.pnlalsystemactions.TabIndex = 1;
//
// btnshutdown
//
this.btnshutdown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnshutdown.AutoSize = true;
this.btnshutdown.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnshutdown.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnshutdown.Location = new System.Drawing.Point(355, 3);
this.btnshutdown.Name = "btnshutdown";
this.btnshutdown.Size = new System.Drawing.Size(75, 26);
this.btnshutdown.TabIndex = 0;
this.btnshutdown.Text = "Shutdown";
this.btnshutdown.UseVisualStyleBackColor = true;
this.btnshutdown.Click += new System.EventHandler(this.btnshutdown_Click);
//
// pnlstatus
//
this.pnlstatus.Controls.Add(this.lbalstatus);
this.pnlstatus.Dock = System.Windows.Forms.DockStyle.Top;
this.pnlstatus.Location = new System.Drawing.Point(0, 0);
this.pnlstatus.Name = "pnlstatus";
this.pnlstatus.Size = new System.Drawing.Size(433, 58);
this.pnlstatus.TabIndex = 0;
//
// lbalstatus
//
this.lbalstatus.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbalstatus.Location = new System.Drawing.Point(0, 0);
this.lbalstatus.Name = "lbalstatus";
this.lbalstatus.Size = new System.Drawing.Size(433, 58);
this.lbalstatus.TabIndex = 0;
this.lbalstatus.Text = "michael@system\r\n0 Codepoints\r\n0 installed, 0 available";
this.lbalstatus.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// WinformsDesktop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Black;
this.ClientSize = new System.Drawing.Size(1296, 738);
this.Controls.Add(this.pnlwidgetlayer);
this.Controls.Add(this.pnladvancedal);
this.Controls.Add(this.pnlscreensaver);
this.Controls.Add(this.desktoppanel);
this.Font = new System.Drawing.Font("Consolas", 9F);
this.ForeColor = System.Drawing.Color.LightGreen;
this.MainMenuStrip = this.menuStrip1;
this.Name = "WinformsDesktop";
this.Text = "Desktop";
this.Load += new System.EventHandler(this.Desktop_Load);
this.desktoppanel.ResumeLayout(false);
this.desktoppanel.PerformLayout();
this.sysmenuholder.ResumeLayout(false);
this.sysmenuholder.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.pnlscreensaver.ResumeLayout(false);
this.pnladvancedal.ResumeLayout(false);
this.pnlalsystemactions.ResumeLayout(false);
this.pnlalsystemactions.PerformLayout();
this.pnlstatus.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel desktoppanel;
private System.Windows.Forms.Label lbtime;
private System.Windows.Forms.Panel sysmenuholder;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem apps;
private System.Windows.Forms.FlowLayoutPanel panelbuttonholder;
private System.Windows.Forms.Button btnnotifications;
private System.Windows.Forms.Panel pnlscreensaver;
private System.Windows.Forms.Panel pnlssicon;
private System.Windows.Forms.Panel pnladvancedal;
private System.Windows.Forms.Panel pnlalsystemactions;
private System.Windows.Forms.Button btnshutdown;
private System.Windows.Forms.Panel pnlstatus;
private System.Windows.Forms.Label lbalstatus;
private System.Windows.Forms.FlowLayoutPanel flapps;
private System.Windows.Forms.FlowLayoutPanel flcategories;
private System.Windows.Forms.Panel pnlwidgetlayer;
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,379 +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 MUD_RAPIDDEV
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using static ShiftOS.Engine.SaveSystem;
namespace ShiftOS.Engine
{
/// <summary>
/// Provides functionality for managing windows within ShiftOS.
/// </summary>
public static class AppearanceManager
{
[Obsolete("Please use Localization.GetAllLanguages().")]
public static string[] GetLanguages()
{
return Localization.GetAllLanguages();
}
/// <summary>
/// Sets the title text of the specified window.
/// </summary>
/// <param name="window">The window to modify</param>
/// <param name="title">The title text to use</param>
/// <exception cref="ArgumentNullException">Thrown if the window is null.</exception>
public static void SetWindowTitle(IShiftOSWindow window, string title)
{
if (window == null)
throw new ArgumentNullException("window", "The window cannot be null.");
winmgr.SetTitle(window, title);
}
public static IEnumerable<Type> GetAllWindowTypes()
{
List<Type> types = new List<Type>();
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())
{
if (type.GetInterfaces().Contains(typeof(IShiftOSWindow)))
types.Add(type);
}
}
catch { }
}
}
return types;
}
/// <summary>
/// Returns the default window title for a specified <see cref="IShiftOSWindow"/>-inheriting type.
/// </summary>
/// <param name="winType">The type to scan</param>
/// <returns>The default title</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="winType"/> is null.</exception>
public static string GetDefaultTitle(Type winType)
{
if (winType == null)
throw new ArgumentNullException("winType");
foreach(var attrib in winType.GetCustomAttributes(false))
{
if(attrib is DefaultTitleAttribute)
{
return (attrib as DefaultTitleAttribute).Title;
}
}
return winType.Name;
}
/// <summary>
/// Current cursor position of the console
/// </summary>
public static int CurrentPosition { get; set; }
/// <summary>
/// We don't know what this does. It may be gone if it does nothing.
/// </summary>
public static int LastLength { get; set; }
/// <summary>
/// Minimize a window.
/// </summary>
/// <param name="form">The window border to minimize.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="form"/> is null.</exception>
/// <exception cref="EngineModuleDisabledException">Thrown if this part of the engine hasn't been enabled.</exception>
public static void Minimize(IWindowBorder form)
{
if (form == null)
throw new ArgumentNullException("form");
if (winmgr == null)
throw new EngineModuleDisabledException();
winmgr.Minimize(form);
}
/// <summary>
/// Maximizes a window.
/// </summary>
/// <param name="form">The window border to maximize.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="form"/> is null.</exception>
/// <exception cref="EngineModuleDisabledException">Thrown if this engine module hasn't been enabled.</exception>
public static void Maximize(IWindowBorder form)
{
if (form == null)
throw new ArgumentNullException("form");
if (winmgr == null)
throw new EngineModuleDisabledException();
winmgr.Maximize(form);
}
/// <summary>
/// Provides a list of all open ShiftOS windows.
/// </summary>
public static List<IWindowBorder> OpenForms = new List<IWindowBorder>();
/// <summary>
/// Decorates a window with a border, then shows the window.
/// </summary>
/// <param name="form">The window to decorate and show.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="form"/> is null. </exception>
/// <exception cref="EngineModuleDisabledException">Thrown if this engine module has not been initiated yet.</exception>
public static void SetupWindow(IShiftOSWindow form)
{
if (form == null)
throw new ArgumentNullException("form");
if (winmgr == null)
throw new EngineModuleDisabledException();
winmgr.SetupWindow(form);
Desktop.ResetPanelButtons();
}
/// <summary>
/// Closes the specified window.
/// </summary>
/// <param name="win">The window to close.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="win"/> is null. </exception>
/// <exception cref="EngineModuleDisabledException">Thrown if this engine module has not been initiated yet.</exception>
public static void Close(IShiftOSWindow win)
{
if (win == null)
throw new ArgumentNullException("win");
if (winmgr == null)
throw new EngineModuleDisabledException();
winmgr.Close(win);
Desktop.ResetPanelButtons();
}
/// <summary>
/// Decorates a window with a border, then shows the window, as a dialog box.
/// </summary>
/// <param name="form">The window to decorate and show.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="form"/> is null. </exception>
/// <exception cref="EngineModuleDisabledException">Thrown if this engine module has not been initiated yet.</exception>
public static void SetupDialog(IShiftOSWindow form)
{
if (form == null)
throw new ArgumentNullException("form");
if (winmgr == null)
throw new EngineModuleDisabledException();
winmgr.SetupDialog(form);
Desktop.ResetPanelButtons();
}
/// <summary>
/// The underlying window manager for this engine module
/// </summary>
private static WindowManager winmgr = null;
/// <summary>
/// Initiate this engine module, and perform mandatory configuration.
/// </summary>
/// <param name="mgr">A working, configured <see cref="WindowManager"/> to use as a backend for this module </param>
public static void Initiate(WindowManager mgr)
{
winmgr = mgr;
}
/// <summary>
/// Raised when the engine is entering its shutdown phase. Save your work!
/// </summary>
public static event EmptyEventHandler OnExit;
/// <summary>
/// Starts the engine's exit routine, firing the OnExit event.
/// </summary>
internal static void Exit()
{
OnExit?.Invoke();
//disconnect from MUD
ServerManager.Disconnect();
}
/// <summary>
/// The current terminal body control.
/// </summary>
public static ITerminalWidget ConsoleOut { get; set; }
/// <summary>
/// Redirects the .NET <see cref="Console"/> to a new <see cref="TerminalTextWriter"/> instance.
/// </summary>
public static void StartConsoleOut()
{
Console.SetOut(new TerminalTextWriter());
}
/// <summary>
/// Invokes an action on the window management thread.
/// </summary>
/// <param name="act">The action to invoke</param>
public static void Invoke(Action act)
{
winmgr.InvokeAction(act);
}
}
/// <summary>
/// Provides the base functionality for a ShiftOS terminal.
/// </summary>
public interface ITerminalWidget
{
/// <summary>
/// Write text to this Terminal.
/// </summary>
/// <param name="text">Text to write</param>
void Write(string text);
/// <summary>
/// Write text to this Terminal, followed by a newline.
/// </summary>
/// <param name="text">Text to write.</param>
void WriteLine(string text);
/// <summary>
/// Clear the contents of this Terminal.
/// </summary>
void Clear();
/// <summary>
/// Move the cursor to the last character in the Terminal.
/// </summary>
void SelectBottom();
}
/// <summary>
/// Provides the base functionality for a ShiftOS window manager.
/// </summary>
public abstract class WindowManager
{
/// <summary>
/// Minimizes a window
/// </summary>
/// <param name="border">The window border to minimize</param>
public abstract void Minimize(IWindowBorder border);
/// <summary>
/// Maximizes a window
/// </summary>
/// <param name="border">The window border to maximize</param>
public abstract void Maximize(IWindowBorder border);
/// <summary>
/// Closes a window
/// </summary>
/// <param name="win">The window to close</param>
public abstract void Close(IShiftOSWindow win);
/// <summary>
/// Decorates a window with a window border, then shows it to the user.
/// </summary>
/// <param name="win">The window to decorate.</param>
public abstract void SetupWindow(IShiftOSWindow win);
/// <summary>
/// Decorates a window with a border, then shows it to the user as a dialog box.
/// </summary>
/// <param name="win">The window to decorate</param>
public abstract void SetupDialog(IShiftOSWindow win);
/// <summary>
/// Invokes an action on the window management thread.
/// </summary>
/// <param name="act">The action to invoke.</param>
public abstract void InvokeAction(Action act);
/// <summary>
/// Sets the title text of a window.
/// </summary>
/// <param name="win">The window to modify.</param>
/// <param name="title">The new title text.</param>
public abstract void SetTitle(IShiftOSWindow win, string title);
}
/// <summary>
/// Provides the base functionality for a typical ShiftOS window border.
/// </summary>
public interface IWindowBorder
{
/// <summary>
/// Closes the border along with its window. Unload events should be invoked here.
/// </summary>
void Close();
/// <summary>
/// Gets or sets the title text for the window border.
/// </summary>
string Text { get; set; }
/// <summary>
/// Gets or sets the underlying <see cref="IShiftOSWindow"/> for this border.
/// </summary>
IShiftOSWindow ParentWindow { get; set; }
}
/// <summary>
/// Provides a way of setting default title text for <see cref="IShiftOSWindow"/> classes.
/// </summary>
public class DefaultTitleAttribute : Attribute
{
/// <summary>
/// Creates a new instance of the <see cref="DefaultTitleAttribute"/>.
/// </summary>
/// <param name="title">A default title to associate with this attribute.</param>
public DefaultTitleAttribute(string title)
{
Title = title;
}
public string Title { get; private set; }
}
/// <summary>
/// An exception that is thrown when mandatory configuration to run a specific method or module hasn't been done yet.
/// </summary>
public class EngineModuleDisabledException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="EngineModuleDisabledException"/>.
/// </summary>
public EngineModuleDisabledException() : base("This engine module has not yet been enabled.")
{
}
}
}

View file

@ -1,134 +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 NOSOUND
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NAudio;
using NAudio.Wave;
namespace ShiftOS.Engine
{
public static class AudioManager
{
private static WaveOut _out = null;
private static AudioFileReader _reader = null;
private static IAudioProvider _provider = null;
/// <summary>
/// Stops the current sound if one is playing and disposes of the sound.
/// </summary>
public static void Stop()
{
_out?.Stop();
_reader?.Dispose();
_out?.Dispose();
}
/// <summary>
/// Initiates this engine module using an <see cref="IAudioProvider"/> as a backend for selecting background soundtrack as well as the volume level for the sound.
/// </summary>
/// <param name="_p">A background soundtrack and volume provider.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="_p"/> is null.</exception>
public static void Init(IAudioProvider _p)
{
if (_p == null)
throw new ArgumentNullException("_p");
_provider = _p;
}
/// <summary>
/// Sets the volume of the audio system.
/// </summary>
/// <param name="volume">The volume to use, from 0 to 1.</param>
public static void SetVolume(float volume)
{
_provider.Volume = volume; //persist between songs
_out.Volume = volume;
}
/// <summary>
/// Plays a specified sound file.
/// </summary>
/// <param name="file">The file to play.</param>
public static void Play(string file)
{
try
{
_reader = new AudioFileReader(file);
_out = new WaveOut();
_out.Init(_reader);
_out.Volume = _provider.Volume;
_out.Play();
_out.PlaybackStopped += (o, a) => { PlayCompleted?.Invoke(); };
}
catch { }
}
/// <summary>
/// Writes the data in the specified <see cref="Stream"/> to a file, and plays it as a sound file.
/// </summary>
/// <param name="str">The stream to read from.</param>
public static void PlayStream(Stream str)
{
var bytes = new byte[str.Length];
str.Read(bytes, 0, bytes.Length);
ShiftOS.Engine.AudioManager.Stop();
if (File.Exists("snd.wav"))
File.Delete("snd.wav");
File.WriteAllBytes("snd.wav", bytes);
ShiftOS.Engine.AudioManager.Play("snd.wav");
}
public static event Action PlayCompleted;
}
public interface IAudioProvider
{
/// <summary>
/// Gets a byte[] array corresponding to an MP3 track given an index.
/// </summary>
/// <param name="index">A track index to use when finding the right track.</param>
/// <returns>The MP3 byte[] array.</returns>
byte[] GetTrack(int index);
/// <summary>
/// Gets the 1-based count of all available tracks.
/// </summary>
int Count { get; }
/// <summary>
/// Gets or sets the track player's volume.
/// </summary>
float Volume { get; set; }
}
}

View file

@ -1,837 +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 DEVEL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ShiftOS.Engine.Properties;
using System.IO;
using Newtonsoft.Json;
using System.IO.Compression;
using ShiftOS.Objects;
using Discoursistency.Base.Models.Authentication;
using ShiftOS.Engine.Scripting;
using ShiftOS.Objects.ShiftFS;
namespace ShiftOS.Engine
{
[Namespace("infobox", hide = true)]
[RequiresUpgrade("desktop;wm_free_placement")]
public static class InfoboxDebugCommands
{
[RequiresArgument("title")]
[RequiresArgument("msg")]
[Command("show")]
public static bool ShowInfo(Dictionary<string, object> args)
{
Desktop.InvokeOnWorkerThread(new Action(() =>
{
Infobox.Show(args["title"].ToString(), args["msg"].ToString());
}));
return true;
}
[RequiresArgument("title")]
[RequiresArgument("msg")]
[Command("yesno")]
public static bool ShowYesNo(Dictionary<string, object> args)
{
bool forwarding = TerminalBackend.IsForwardingConsoleWrites;
var fGuid = TerminalBackend.ForwardGUID;
Action<bool> callback = (result) =>
{
TerminalBackend.IsForwardingConsoleWrites = forwarding;
TerminalBackend.ForwardGUID = (forwarding == true) ? fGuid : null;
string resultFriendly = (result == true) ? "yes" : "no";
Console.WriteLine($"{SaveSystem.CurrentUser.Username} says {resultFriendly}.");
TerminalBackend.IsForwardingConsoleWrites = false;
};
Desktop.InvokeOnWorkerThread(new Action(() =>
{
Infobox.PromptYesNo(args["title"].ToString(), args["msg"].ToString(), callback);
}));
return true;
}
[RequiresArgument("title")]
[RequiresArgument("msg")]
[Command("text")]
public static bool ShowText(Dictionary<string, object> args)
{
bool forwarding = TerminalBackend.IsForwardingConsoleWrites;
var fGuid = TerminalBackend.ForwardGUID;
Action<string> callback = (result) =>
{
TerminalBackend.IsForwardingConsoleWrites = forwarding;
TerminalBackend.ForwardGUID = (forwarding == true) ? fGuid : null;
Console.WriteLine($"{SaveSystem.CurrentSave.Username} says \"{result}\".");
TerminalBackend.IsForwardingConsoleWrites = false;
};
Desktop.InvokeOnWorkerThread(new Action(() =>
{
Infobox.PromptText(args["title"].ToString(), args["msg"].ToString(), callback);
}));
return true;
}
}
[Namespace("audio")]
public static class AudioCommands
{
[Command("setvol", description = "Set the volume of the system audio to anywhere between 0 and 100.")]
[RequiresArgument("value")]
[RequiresUpgrade("audio_volume")]
public static bool SetVolume(Dictionary<string,object> args)
{
int val = Convert.ToInt32(args["value"].ToString());
float volume = (val / 100F);
AudioManager.SetVolume(volume);
return true;
}
[RequiresUpgrade("audio_volume")]
[Command("mute", description = "Sets the volume of the system audio to 0")]
public static bool MuteAudio()
{
AudioManager.SetVolume(0);
return true;
}
}
[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<string, object> 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<string, object> args)
{
ServerManager.SendMessage(args["header"].ToString(), args["body"].ToString());
return true;
}
}
[TutorialLock]
[Namespace("trm")]
public static class TerminalCommands
{
[Command("clear")]
public static bool Clear()
{
AppearanceManager.ConsoleOut.Clear();
return true;
}
[Command("echo")]
[RequiresArgument("text")]
public static bool Echo(Dictionary<string, object> args)
{
Console.WriteLine(args["text"]);
return true;
}
}
#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("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<string, object> 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<string, object> args)
{
Console.WriteLine("Success! "+args.ToString());
return true;
}
[Command("restart")]
public static bool Restart()
{
SaveSystem.CurrentSave.Upgrades = new Dictionary<string, bool>();
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<string, object> args)
{
if (args.ContainsKey("amount"))
try
{
long codepointsToAdd = Convert.ToInt64(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())
{
Shiftorium.Buy(upg.ID, 0);
}
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<string, object> 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
{
[RemoteLock]
[Command("shutdown")]
public static bool Shutdown()
{
TerminalBackend.InvokeCommand("sos.save");
SaveSystem.ShuttingDown = true;
AppearanceManager.Exit();
return true;
}
[Command("lang", "{COMMAND_SOS_LANG_USAGE}", "{COMMAND_SOS_LANG_DESCRIPTION}")]
[RequiresArgument("language")]
public static bool SetLanguage(Dictionary<string, object> userArgs)
{
try
{
string lang = "";
if (userArgs.ContainsKey("language"))
lang = (string)userArgs["language"];
else
throw new Exception("You must specify a valid 'language' value.");
if (Localization.GetAllLanguages().Contains(lang))
{
SaveSystem.CurrentSave.Language = lang;
SaveSystem.SaveGame();
Console.WriteLine("{LANGUAGE_CHANGED}");
return true;
}
throw new Exception($"Couldn't find language with ID: {lang}");
}
catch
{
return false;
}
}
[Command("help", "{COMMAND_HELP_USAGE}", "{COMMAND_HELP_DESCRIPTION}")]
public static bool Help()
{
foreach (var exec in System.IO.Directory.GetFiles(Environment.CurrentDirectory))
{
if (exec.EndsWith(".exe") || exec.EndsWith(".dll"))
{
try
{
var asm = Assembly.LoadFile(exec);
var types = asm.GetTypes();
foreach (var type in types)
{
if (Shiftorium.UpgradeAttributesUnlocked(type))
{
foreach (var a in type.GetCustomAttributes(false))
{
if (a is Namespace)
{
var ns = a as Namespace;
if (!ns.hide)
{
string descp = "{NAMESPACE_" + ns.name.ToUpper() + "_DESCRIPTION}";
if (descp == Localization.Parse(descp))
descp = "";
else
descp = Shiftorium.UpgradeInstalled("help_description") ? Localization.Parse("{SEPERATOR}" + descp) : "";
Console.WriteLine($"{{NAMESPACE}}{ns.name}" + descp);
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
if (Shiftorium.UpgradeAttributesUnlocked(method))
{
foreach (var ma in method.GetCustomAttributes(false))
{
if (ma is Command)
{
var cmd = ma as Command;
if (!cmd.hide)
{
string descriptionparse = "{COMMAND_" + ns.name.ToUpper() + "_" + cmd.name.ToUpper() + "_DESCRIPTION}";
string usageparse = "{COMMAND_" + ns.name.ToUpper() + "_" + cmd.name.ToUpper() + "_USAGE}";
if (descriptionparse == Localization.Parse(descriptionparse))
descriptionparse = "";
else
descriptionparse = Shiftorium.UpgradeInstalled("help_description") ? Localization.Parse("{SEPERATOR}" + descriptionparse) : "";
if (usageparse == Localization.Parse(usageparse))
usageparse = "";
else
usageparse = Shiftorium.UpgradeInstalled("help_usage") ? Localization.Parse("{SEPERATOR}" + usageparse, new Dictionary<string, string>() {
{"%ns", ns.name},
{"%cmd", cmd.name}
}) : "";
Console.WriteLine($"{{COMMAND}}{ns.name}.{cmd.name}" + usageparse + descriptionparse);
}
}
}
}
}
}
}
}
}
}
}
catch { }
}
}
return true;
}
[MultiplayerOnly]
[Command("save")]
public static bool Save()
{
SaveSystem.SaveGame();
return true;
}
[MultiplayerOnly]
[Command("status")]
public static bool Status()
{
string status = $@"ShiftOS version {Assembly.GetExecutingAssembly().GetName().Version.ToString()}
Codepoints: {SaveSystem.CurrentSave.Codepoints}
Upgrades: {SaveSystem.CurrentSave.CountUpgrades()} installed,
{Shiftorium.GetAvailable().Length} available";
if (Shiftorium.UpgradeInstalled("mud_control_centre"))
status += Environment.NewLine + $"Reputation: {SaveSystem.CurrentSave.RawReputation} ({SaveSystem.CurrentSave.Reputation})";
Console.WriteLine(status);
return true;
}
}
[MultiplayerOnly]
[Namespace("shiftorium")]
public static class ShiftoriumCommands
{
[Command("buy")]
[RequiresArgument("upgrade")]
public static bool BuyUpgrade(Dictionary<string, object> userArgs)
{
try
{
string upgrade = "";
if (userArgs.ContainsKey("upgrade"))
upgrade = (string)userArgs["upgrade"];
else
throw new Exception("You must specify a valid 'upgrade' value.");
foreach (var upg in Shiftorium.GetAvailable())
{
if (upg.ID == upgrade)
{
Shiftorium.Buy(upgrade, upg.Cost);
return true;
}
}
throw new Exception($"Couldn't find upgrade with ID: {upgrade}");
}
catch
{
return false;
}
}
[RequiresUpgrade("shiftorium_bulk_buy")]
[Command("bulkbuy")]
[RequiresArgument("upgrades")]
public static bool BuyBulk(Dictionary<string, object> args)
{
if (args.ContainsKey("upgrades"))
{
string[] upgrade_list = (args["upgrades"] as string).Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (var upg in upgrade_list)
{
var dict = new Dictionary<string, object>();
dict.Add("upgrade", upg);
BuyUpgrade(dict);
}
}
else
{
throw new Exception("Please specify a list of upgrades in the 'upgrades' argument. Each upgrade is separated by a comma.");
}
return true;
}
[Command("info")]
public static bool ViewInfo(Dictionary<string, object> userArgs)
{
try
{
string upgrade = "";
if (userArgs.ContainsKey("upgrade"))
upgrade = (string)userArgs["upgrade"];
else
throw new Exception("You must specify a valid 'upgrade' value.");
foreach (var upg in Shiftorium.GetDefaults())
{
if (upg.ID == upgrade)
{
Console.WriteLine($@"Information for {upgrade}:
{upg.Category}: {upg.Name} - {upg.Cost} Codepoints
------------------------------------------------------
{upg.Description}
To buy this upgrade, run:
shiftorium.buy{{upgrade:""{upg.ID}""}}");
return true;
}
}
throw new Exception($"Couldn't find upgrade with ID: {upgrade}");
}
catch
{
return false;
}
}
[Command("categories")]
public static bool ListCategories()
{
foreach(var cat in Shiftorium.GetCategories())
{
Console.WriteLine($"{cat} - {Shiftorium.GetAvailable().Where(x=>x.Category==cat).Count()} upgrades");
}
return true;
}
[Command("list")]
public static bool ListAll(Dictionary<string, object> args)
{
try
{
bool showOnlyInCategory = false;
string cat = "Other";
if (args.ContainsKey("cat"))
{
showOnlyInCategory = true;
cat = args["cat"].ToString();
}
Dictionary<string, long> upgrades = new Dictionary<string, long>();
int maxLength = 5;
IEnumerable<ShiftoriumUpgrade> upglist = Shiftorium.GetAvailable();
if (showOnlyInCategory)
{
if (Shiftorium.IsCategoryEmptied(cat))
{
ConsoleEx.Bold = true;
ConsoleEx.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Shiftorium Query Error");
Console.WriteLine();
ConsoleEx.Bold = false;
ConsoleEx.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("Either there are no upgrades in the category \"" + cat + "\" or the category was not found.");
return true;
}
upglist = Shiftorium.GetAvailable().Where(x => x.Category == cat);
}
if(upglist.Count() == 0)
{
ConsoleEx.Bold = true;
ConsoleEx.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("No upgrades available!");
Console.WriteLine();
ConsoleEx.Bold = false;
ConsoleEx.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("You have installed all available upgrades for your system. Please check back later for more.");
return true;
}
foreach (var upg in upglist)
{
if (upg.ID.Length > maxLength)
{
maxLength = upg.ID.Length;
}
upgrades.Add(upg.ID, upg.Cost);
}
Console.WriteLine("ID".PadRight((maxLength + 5) - 2) + "Cost (Codepoints)");
foreach (var upg in upgrades)
{
Console.WriteLine(upg.Key.PadRight((maxLength + 5) - upg.Key.Length) + " " + upg.Value.ToString());
}
return true;
}
catch (Exception e)
{
CrashHandler.Start(e);
return false;
}
}
}
[Namespace("win")]
public static class WindowCommands
{
[RemoteLock]
[Command("list")]
public static bool List()
{
Console.WriteLine("Window ID\tName");
foreach (var app in AppearanceManager.OpenForms)
{
//Windows are displayed the order in which they were opened.
Console.WriteLine($"{AppearanceManager.OpenForms.IndexOf(app)}\t{app.Text}");
}
return true;
}
[RemoteLock]
[Command("open")]
public static bool Open(Dictionary<string, object> args)
{
try
{
if (args.ContainsKey("app"))
{
var app = args["app"] as string;
//ANNND now we start reflecting...
foreach (var asmExec in System.IO.Directory.GetFiles(Environment.CurrentDirectory))
{
if (asmExec.EndsWith(".exe") || asmExec.EndsWith(".dll"))
{
var asm = Assembly.LoadFile(asmExec);
try
{
foreach (var type in asm.GetTypes())
{
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;
}
}
}
}
}
}
}
catch { }
}
}
}
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 { }
}
}
return true;
}
Console.WriteLine("Couldn't find the specified app on your system.");
return true;
}
catch (Exception ex)
{
Console.WriteLine("Error running script:" + ex);
return false;
}
}
[RemoteLock]
[Command("close", usage = "{win:integer32}", description ="Closes the specified window.")]
[RequiresArgument("win")]
[RequiresUpgrade("close_command")]
public static bool CloseWindow(Dictionary<string, object> args)
{
int winNum = -1;
if (args.ContainsKey("win"))
winNum = Convert.ToInt32(args["win"].ToString());
string err = null;
if (winNum < 0 || winNum >= AppearanceManager.OpenForms.Count)
err = "The window number must be between 0 and " + (AppearanceManager.OpenForms.Count - 1).ToString() + ".";
if (string.IsNullOrEmpty(err))
{
Console.WriteLine($"Closing {AppearanceManager.OpenForms[winNum].Text}...");
AppearanceManager.Close(AppearanceManager.OpenForms[winNum].ParentWindow);
}
else
{
Console.WriteLine(err);
}
return true;
}
}
}

View file

@ -1,217 +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.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Management;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Threading;
using System.IO;
namespace ShiftOS.Engine
{
public class GetHardwareInfo
{
public static string GetProcessorName()
{
string ProcessorName = "";
ManagementObjectSearcher mos
= new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor");
foreach (ManagementObject mo in mos.Get())
ProcessorName = mo["Name"].ToString();
return ProcessorName;
}
public static string GetGPUName()
{
string GPUName = "";
ManagementObjectSearcher mos
= new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController");
foreach (ManagementObject mo in mos.Get())
GPUName = mo["Name"].ToString();
return GPUName;
}
public static string GetRAMAmount()
{
var RAMAmount = "";
ManagementObjectSearcher mos
= new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PhysicalMemory");
foreach (ManagementObject mo in mos.Get())
RAMAmount = mo["Capacity"].ToString();
RAMAmount = (RAMAmount + " B");
return RAMAmount;
}
}
public partial class CrashHandler : Form
{
public CrashHandler()
{
InitializeComponent();
//Send the bug to Debugle
// or alternatively, send to reportbug@shiftos.ml OR narodgaming@shiftos.ml
}
public static Exception HandledException = null;
public static void Start(Exception e)
{
if(SaveSystem.CurrentSave != null)
TerminalBackend.InvokeCommand("sos.save");
ServerManager.Disconnect();
while (Application.OpenForms.Count > 0)
Application.OpenForms[0].Close();
//Set our global exception variable, and show the exception dialog.
HandledException = e;
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.FileInfo fileInfo = new System.IO.FileInfo(assembly.Location);
DateTime lastModified = fileInfo.LastWriteTime;
string rtbcrash_Text = $@" === {AssemblyName} has crashed. ===
Game: {AssemblyName}
Description: {AssemblyDescription}
Basic Information For User:
---------------------------------
When: {DateTime.Now.ToString()}
Why: {HandledException.Message}
What: {HandledException.GetType().Name}
We, at the ShiftOS Development Team, apologise for your game crash,
we will take this bug report seriously - and it has been emailed
to the development team of ShiftOS, thank you for enjoying our game!
Advanced Information (for experts and developers):
----------------------------------------------------
Host system information:
---------------------------------
Operating system: {Environment.OSVersion.Platform.ToString()}
Version: {Environment.OSVersion.VersionString}
Is 64-bit: {Environment.Is64BitOperatingSystem}
ShiftOS exec path: {Application.ExecutablePath}
Advanced Host Information:
---------------------------------
CPU Name: {GetHardwareInfo.GetProcessorName()}
Physical RAM Installed: {GetHardwareInfo.GetRAMAmount()}
GPU Name: {GetHardwareInfo.GetGPUName()}
ShiftOS basic information:
---------------------------------
ShiftOS Version: {Assembly.GetExecutingAssembly().GetName().Version}
ShiftOS Date: {lastModified.ToString()}
ShiftOS environment information:
---------------------------------
Is Save loaded: {(SaveSystem.CurrentSave != null)}
Paths loaded in system: {JsonConvert.SerializeObject(Paths.GetAll())}
Crash: {HandledException.GetType().Name}
--------------------------------------------
Exception message: {HandledException.Message}
HResult (this is technical): {HandledException.HResult}
Has inner exception: {(HandledException.InnerException != null)}
Stack trace:
{HandledException.StackTrace}";
if (HandledException.InnerException != null)
{
var i = HandledException.InnerException;
rtbcrash_Text += $@"
Inner: {i.GetType().Name}
--------------------------------------------
Exception message: {i.Message}
HResult (this is technical): {i.HResult}
Stack trace:
{i.StackTrace}";
}
File.WriteAllText("crash.txt", rtbcrash_Text);
var result = MessageBox.Show(caption: "ShiftOS - Fatal error", text: "ShiftOS has encountered a fatal error and has been shut down. Info about the error has been saved to a file called crash.txt in the same folder as the active executable. Would you like to try and recover the game session?", buttons: MessageBoxButtons.YesNo);
if(result == DialogResult.Yes)
{
Application.Restart();
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnjump_Click(object sender, EventArgs e)
{
this.Close();
Application.Restart();
}
public static string AssemblyName { get; private set; }
public static string AssemblyDescription { get; private set; }
public static void SetGameMetadata(Assembly assembly)
{
AssemblyName = assembly.GetName().Name;
foreach(var attr in assembly.GetCustomAttributes(true))
{
if(attr is AssemblyDescriptionAttribute)
{
AssemblyDescription = (attr as AssemblyDescriptionAttribute).Description;
}
}
}
}
}

View file

@ -1,271 +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.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ShiftOS.Objects.ShiftFS;
using static ShiftOS.Engine.SkinEngine;
namespace ShiftOS.Engine
{
/// <summary>
/// Denotes that this class is launchable from the App Launcher.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class LauncherAttribute : Attribute
{
/// <summary>
/// Marks this form as a launcher item that, when clicked, will open the form.
/// </summary>
/// <param name="name">The text displayed on the launcher item</param>
/// <param name="requiresUpgrade">Whether or not an upgrade must be installed to see the launcher</param>
/// <param name="upgradeID">The ID of the upgrade - leave blank if requiresUpgrade is false.</param>
/// <param name="category">The category that the item will appear in.</param>
public LauncherAttribute(string name, bool requiresUpgrade, string upgradeID = "", string category = "Other")
{
Category = category;
Name = name;
RequiresUpgrade = requiresUpgrade;
ID = upgradeID;
}
/// <summary>
/// Gets or sets the name of the launcher item
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets whether this entry requires a Shiftorium upgrade.
/// </summary>
public bool RequiresUpgrade { get; set; }
/// <summary>
/// Gets or sets the ID of the required upgrade.
/// </summary>
public string ID { get; set; }
/// <summary>
/// Gets or sets this item's category.
/// </summary>
public string Category { get; private set; }
/// <summary>
/// Gets whether or not the required upgrade is installed.
/// </summary>
public bool UpgradeInstalled
{
get
{
if (!RequiresUpgrade)
return true;
return Shiftorium.UpgradeInstalled(ID);
}
}
}
/// <summary>
/// Provides core functionality for a typical ShiftOS desktop.
/// </summary>
public interface IDesktop
{
/// <summary>
/// Gets the name of the desktop.
/// </summary>
string DesktopName { get; }
/// <summary>
/// Performs most of the skinning and layout handling for the desktop.
/// </summary>
void SetupDesktop();
/// <summary>
/// Hides the currently-opened app launcher menu.
/// </summary>
void HideAppLauncher();
/// <summary>
/// Populates the app launcher menu.
/// </summary>
/// <param name="items">All items to be placed in the menu.</param>
void PopulateAppLauncher(LauncherItem[] items);
/// <summary>
/// Handles desktop-specific routines for showing ShiftOS windows.
/// </summary>
/// <param name="border">The calling window.</param>
void ShowWindow(IWindowBorder border);
/// <summary>
/// Handles desktop-specific routines for closing ShiftOS windows.
/// </summary>
/// <param name="border">The calling window.</param>
void KillWindow(IWindowBorder border);
/// <summary>
/// Populates the panel button list with all open windows.
/// </summary>
void PopulatePanelButtons();
/// <summary>
/// Performs desktop-specific routines for minimizing a window.
/// </summary>
/// <param name="brdr">The calling window.</param>
void MinimizeWindow(IWindowBorder brdr);
/// <summary>
/// Performs desktop-specific routines for maximizing a window.
/// </summary>
/// <param name="brdr">The calling window.</param>
void MaximizeWindow(IWindowBorder brdr);
/// <summary>
/// Performs desktop-specific routines for restoring a window to its default state.
/// </summary>
/// <param name="brdr">The calling window.</param>
void RestoreWindow(IWindowBorder brdr);
/// <summary>
/// Invokes an action on the UI thread.
/// </summary>
/// <param name="act">The action to invoke.</param>
void InvokeOnWorkerThread(Action act);
/// <summary>
/// Calculates the screen size of the desktop.
/// </summary>
/// <returns>The desktop's screen size.</returns>
Size GetSize();
/// <summary>
/// Opens the app launcher at a specific point.
/// </summary>
/// <param name="loc">Where the app launcher should be opened.</param>
void OpenAppLauncher(Point loc);
/// <summary>
/// Opens the desktop.
/// </summary>
void Show();
/// <summary>
/// Closes the desktop.
/// </summary>
void Close();
}
public static class Desktop
{
/// <summary>
/// The underlying desktop object.
/// </summary>
private static IDesktop _desktop = null;
public static Size Size
{
get
{
return _desktop.GetSize();
}
}
public static IDesktop CurrentDesktop
{
get
{
return _desktop;
}
}
public static void Init(IDesktop desk, bool show = false)
{
IDesktop deskToClose = null;
if (_desktop != null)
deskToClose = _desktop;
_desktop = desk;
if (show == true)
_desktop.Show();
deskToClose?.Close();
}
public static void MinimizeWindow(IWindowBorder brdr)
{
_desktop.MinimizeWindow(brdr);
}
public static void MaximizeWindow(IWindowBorder brdr)
{
_desktop.MaximizeWindow(brdr);
}
public static void RestoreWindow(IWindowBorder brdr)
{
_desktop.RestoreWindow(brdr);
}
public static void InvokeOnWorkerThread(Action act)
{
_desktop.InvokeOnWorkerThread(act);
}
public static void ResetPanelButtons()
{
_desktop.PopulatePanelButtons();
}
public static void ShowWindow(IWindowBorder brdr)
{
_desktop.ShowWindow(brdr);
}
public static void PopulateAppLauncher()
{
_desktop.PopulateAppLauncher(AppLauncherDaemon.Available().ToArray());
}
public static void OpenAppLauncher(Point loc)
{
_desktop.OpenAppLauncher(loc);
}
public static void HideAppLauncher()
{
_desktop.HideAppLauncher();
}
}
// sorry i almost killed everything :P
}

View file

@ -1,145 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static ShiftOS.Objects.ShiftFS.Utils;
namespace ShiftOS.Engine
{
public static class KernelWatchdog
{
public static void Log(string e, string desc)
{
string line = $"[{DateTime.Now}] <{e}> {desc}";
if (FileExists("0:/system/data/kernel.log"))
{
string contents = ReadAllText("0:/system/data/kernel.log");
contents += Environment.NewLine + line;
WriteAllText("0:/system/data/kernel.log", contents);
}
else
{
WriteAllText("0:/system/data/kernel.log", line);
}
}
private static bool _mudConnected = true;
public static bool InKernelMode { get; private set; }
public static bool MudConnected
{
get
{
return _mudConnected;
}
set
{
if(value == false)
{
foreach(var win in AppearanceManager.OpenForms)
{
foreach(var attr in win.ParentWindow.GetType().GetCustomAttributes(true))
{
if(attr is MultiplayerOnlyAttribute)
{
ConsoleEx.Bold = true;
ConsoleEx.Underline = false;
ConsoleEx.Italic = true;
ConsoleEx.ForegroundColor = ConsoleColor.Red;
Console.Write("Error:");
ConsoleEx.Bold = false;
ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Cannot disconnect from multi-user domain because an app that depends on it is open.");
TerminalBackend.PrintPrompt();
return;
}
}
}
}
_mudConnected = value;
Desktop.PopulateAppLauncher();
}
}
public static bool IsSafe(Type type)
{
if (SaveSystem.CurrentUser.Permissions == Objects.UserPermissions.Root)
return true;
foreach (var attrib in type.GetCustomAttributes(false))
{
if (attrib is KernelModeAttribute)
{
if (SaveSystem.CurrentUser.Permissions == Objects.UserPermissions.Root)
return true;
return false;
}
}
return true;
}
public static bool IsSafe(MethodInfo type)
{
if (SaveSystem.CurrentUser.Permissions == Objects.UserPermissions.Root)
return true;
foreach (var attrib in type.GetCustomAttributes(false))
{
if (attrib is KernelModeAttribute)
{
if (SaveSystem.CurrentUser.Permissions == Objects.UserPermissions.Root)
return true;
return false;
}
}
return true;
}
static string regularUsername = "";
public static void EnterKernelMode()
{
regularUsername = SaveSystem.CurrentUser.Username;
SaveSystem.CurrentUser = SaveSystem.Users.FirstOrDefault(x => x.Username == "root");
}
public static void LeaveKernelMode()
{
var user = SaveSystem.Users.FirstOrDefault(x => x.Username == regularUsername);
if (user == null)
throw new Exception("User not in root mode.");
SaveSystem.CurrentUser = user;
}
internal static bool CanRunOffline(Type method)
{
if (MudConnected)
return true;
foreach (var attr in method.GetCustomAttributes(false))
{
if (attr is MultiplayerOnlyAttribute)
return false;
}
return true;
}
internal static bool CanRunOffline(MethodInfo method)
{
if (MudConnected)
return true;
foreach(var attr in method.GetCustomAttributes(false))
{
if (attr is MultiplayerOnlyAttribute)
return false;
}
return true;
}
}
}

View file

@ -1,219 +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 Newtonsoft.Json;
using ShiftOS.Objects.ShiftFS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShiftOS.Engine
{
public interface ILanguageProvider
{
List<string> GetJSONTranscripts();
void WriteDefaultTranscript();
void WriteTranscript();
string GetCurrentTranscript();
string[] GetAllLanguages();
}
public static class Localization
{
private static ILanguageProvider _provider = null;
private static string _languageid = null;
public static string[] GetAllLanguages()
{
if(_provider == null)
{
return JsonConvert.DeserializeObject<string[]>(Properties.Resources.languages);
}
else
{
return _provider.GetAllLanguages();
}
}
public static void SetupTHETRUEDefaultLocals()
{
if (_provider == null)
{
var lines = Properties.Resources.strings_en;
var path = "english.local";
Utils.WriteAllText(Paths.GetPath(path), lines);
}
else if (SaveSystem.CurrentSave == null)
{
var lines = Properties.Resources.strings_en;
var path = "english.local";
Utils.WriteAllText(Paths.GetPath(path), lines);
}
else
{
_provider.WriteTranscript();
}
}
public static void SetupDefaultLocals(string lines, string path)
{
Utils.WriteAllText(Paths.GetPath(path), lines);
}
/// <summary>
/// Takes in a string and parses localization blocks into text blocks in the current language.
/// </summary>
/// <example>"{CODEPOINTS}: 0" will come out as "Codepoints: 0" if the current language is english.</example>
/// <param name="original">The string to parse</param>
/// <returns>The parsed string.</returns>
///
public static string Parse(string original)
{
return Parse(original, new Dictionary<string, string>());
}
public static string Parse(string original, Dictionary<string, string> replace)
{
Dictionary<string, string> localizationStrings = new Dictionary<string, string>();
try
{
localizationStrings = JsonConvert.DeserializeObject<Dictionary<string, string>>(_provider.GetCurrentTranscript());
}
catch
{
localizationStrings = JsonConvert.DeserializeObject<Dictionary<string, string>>(Utils.ReadAllText(Paths.GetPath("english.local")));
}
foreach (var kv in localizationStrings)
{
original = original.Replace(kv.Key, kv.Value);
}
List<string> orphaned = new List<string>();
if (Utils.FileExists("0:/dev_orphaned_lang.txt"))
{
orphaned = JsonConvert.DeserializeObject<List<string>>(Utils.ReadAllText("0:/dev_orphaned_lang.txt"));
}
int start_index = 0;
int length = 0;
bool indexing = false;
foreach (var c in original)
{
if (c == '{')
{
start_index = original.IndexOf(c);
indexing = true;
}
if (indexing == true)
{
length++;
if (c == '}')
{
indexing = false;
string o = original.Substring(start_index, length);
if (!orphaned.Contains(o))
{
orphaned.Add(o);
}
start_index = 0;
length = 0;
}
}
}
if (orphaned.Count > 0)
{
Utils.WriteAllText("0:/dev_orphaned_lang.txt", JsonConvert.SerializeObject(orphaned, Formatting.Indented));
}
//string original2 = Parse(original);
string usernameReplace = "";
string domainReplace = "";
if (SaveSystem.CurrentSave != null)
{
usernameReplace = SaveSystem.CurrentSave.Username;
domainReplace = SaveSystem.CurrentSave.SystemName;
}
string namespaceReplace = "";
string commandReplace = "";
if (TerminalBackend.latestCommmand != "" && TerminalBackend.latestCommmand.IndexOf('.') > -1)
{
namespaceReplace = TerminalBackend.latestCommmand.Split('.')[0];
commandReplace = TerminalBackend.latestCommmand.Split('.')[1];
}
Dictionary<string, string> defaultReplace = new Dictionary<string, string>() {
{"%username", usernameReplace},
{"%domain", domainReplace},
{"%ns", namespaceReplace},
{"%cmd", commandReplace},
{"%cp", SaveSystem.CurrentSave?.Codepoints.ToString() },
};
foreach (KeyValuePair<string, string> replacement in replace)
{
original = original.Replace(replacement.Key, Parse(replacement.Value));
}
foreach (KeyValuePair<string, string> replacement in defaultReplace)
{
original = original.Replace(replacement.Key, replacement.Value);
}
return original;
}
public static void RegisterProvider(ILanguageProvider p)
{
_provider = p;
}
public static void SetLanguageID(string id)
{
_languageid = id;
}
public static string GetLanguageID()
{
return _languageid;
}
}
}

View file

@ -1,134 +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 Newtonsoft.Json;
using ShiftOS.Objects.ShiftFS;
namespace ShiftOS.Engine
{
public static class NotificationDaemon
{
public static Notification[] GetAllFromFile()
{
Notification[] notes = { };
if (Utils.FileExists(Paths.GetPath("notifications.dat")))
{
notes = JsonConvert.DeserializeObject<Notification[]>(Utils.ReadAllText(Paths.GetPath("notifications.dat")));
}
return notes;
}
internal static void WriteNotes(Notification[] notes)
{
Utils.WriteAllText(Paths.GetPath("notifications.dat"), JsonConvert.SerializeObject(notes, Formatting.Indented));
}
public static event Action<Notification> NotificationMade;
public static void AddNotification(NotificationType note, object data)
{
var lst = new List<Notification>(GetAllFromFile());
lst.Add(new Engine.Notification(note, data));
WriteNotes(lst.ToArray());
NotificationMade?.Invoke(lst[lst.Count - 1]);
}
public static event Action NotificationRead;
public static void MarkAllRead()
{
var notes = GetAllFromFile();
for (int i = 0; i < notes.Length; i++)
MarkRead(i);
}
public static void MarkRead(int note)
{
var notes = GetAllFromFile();
if (note >= notes.Length || note < 0)
throw new ArgumentOutOfRangeException("note", new Exception("You cannot mark a notification that does not exist as read."));
notes[note].Read = true;
WriteNotes(notes);
NotificationRead?.Invoke();
}
public static int GetUnreadCount()
{
int c = 0;
foreach (var note in GetAllFromFile())
if (note.Read == false)
c++; //gahh I hate that programming language.
return c;
}
}
public struct Notification
{
public Notification(NotificationType t, object data)
{
Type = t;
Data = data;
Read = false;
Timestamp = DateTime.Now;
}
public bool Read { get; set; }
public NotificationType Type { get; set; }
public object Data { get; set; }
public DateTime Timestamp { get; set; }
}
public enum NotificationType
{
Generic = 0x00,
MemoReceived = 0x10,
MemoSent = 0x11,
DownloadStarted = 0x20,
DownloadComplete = 0x21,
CodepointsReceived = 0x30,
CodepointsSent = 0x31,
ShopPurchase = 0x40,
LegionInvite = 0x50,
LegionKick = 0x51,
LegionBan = 0x52,
ChatBan = 0x60,
MUDAnnouncement = 0x70,
MUDMaintenance = 0x71,
NewShiftOSUnstable = 0x72,
NewShiftOSStable = 0x73,
NewAppveyor = 0x74,
CriticalBugwatch = 0x75,
NewDeveloper = 0x76,
NewShiftOSVideo = 0x77,
NewShiftOSStream = 0x78,
SavePurge = 0x79,
}
}

View file

@ -1,237 +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 static ShiftOS.Objects.ShiftFS.Utils;
using ShiftOS.Objects.ShiftFS;
using Newtonsoft.Json;
using System.Threading;
namespace ShiftOS.Engine
{
public static class Paths
{
public static void Init()
{
Locations = new Dictionary<string, string>();
Locations.Add("root", "0:");
AddPath("root", "system");
AddPath("root", "home");
AddPath("home", "documents");
AddPath("home", "desktop");
AddPath("home", "pictures");
AddPath("system", "local");
AddPath("local", "english.local");
AddPath("local", "deutsch.local");
AddPath("local", "verbose.local");
AddPath("system", "data");
AddPath("system", "applauncher");
AddPath("data", "save.json");
AddPath("data", "user.dat");
AddPath("data", "notifications.dat");
AddPath("data", "skin");
AddPath("skin", "widgets.dat");
AddPath("system", "programs");
AddPath("system", "kernel.sft");
AddPath("system", "conf.sft");
AddPath("skin", "current");
AddPath("current", "skin.json");
AddPath("current", "images");
CheckPathExistence();
CreateAndMountSharedFolder();
}
/// <summary>
/// Returns all paths in an array of strings.
/// </summary>
/// <returns>The array</returns>
public static string[] GetAll()
{
List<string> strings = new List<string>();
foreach(var str in Locations)
{
strings.Add(str.Key + " = " + str.Value);
}
return strings.ToArray();
}
public static string[] GetAllWithoutKey()
{
List<string> strings = new List<string>();
foreach (var str in Locations)
{
strings.Add(str.Value);
}
return strings.ToArray();
}
public static string GetPath(string id)
{
return Locations[id];
}
private static void CheckPathExistence()
{
foreach(var path in Locations)
{
if (!path.Value.Contains(".") && path.Key != "classic")
{
if (!DirectoryExists(path.Value))
{
Console.WriteLine($"Writing directory: {path.Value.Replace(Locations["root"], "\\")}");
CreateDirectory(path.Value);
}
}
}
}
private static Dictionary<string, string> Locations { get; set; }
public static void CreateAndMountSharedFolder()
{
if (!System.IO.Directory.Exists(SharedFolder))
{
System.IO.Directory.CreateDirectory(SharedFolder);
}
var mount = new Directory();
mount.Name = "Shared";
Utils.Mount(JsonConvert.SerializeObject(mount));
ScanForDirectories(SharedFolder, 1);
//This event-based system allows us to sync the ramdisk from ShiftOS to the host OS.
Utils.DirectoryCreated += (dir) =>
{
try
{
if (dir.StartsWith("1:/"))
{
string real = dir.Replace("/", "\\").Replace("1:", SharedFolder);
if (!System.IO.Directory.Exists(real))
System.IO.Directory.CreateDirectory(real);
}
}
catch { }
};
Utils.DirectoryDeleted += (dir) =>
{
try
{
if (dir.StartsWith("1:/"))
{
string real = dir.Replace("/", "\\").Replace("1:", SharedFolder);
if (System.IO.Directory.Exists(real))
System.IO.Directory.Delete(real, true);
}
}
catch { }
};
Utils.FileWritten += (dir) =>
{
try
{
if (dir.StartsWith("1:/"))
{
string real = dir.Replace("/", "\\").Replace("1:", SharedFolder);
System.IO.File.WriteAllBytes(real, ReadAllBytes(dir));
}
}
catch { }
};
Utils.FileDeleted += (dir) =>
{
try
{
if (dir.StartsWith("1:/"))
{
string real = dir.Replace("/", "\\").Replace("1:", SharedFolder);
if (System.IO.File.Exists(real))
System.IO.File.Delete(real);
}
}
catch { }
};
//This thread will sync the ramdisk from the host OS to ShiftOS.
var t = new Thread(() =>
{
while (!SaveSystem.ShuttingDown)
{
Thread.Sleep(15000);
ScanForDirectories(SharedFolder, 1);
}
});
t.IsBackground = true;
t.Start();
}
public static void ScanForDirectories(string folder, int mount)
{
foreach (var file in System.IO.Directory.GetFiles(folder))
{
string mfsDir = file.Replace(SharedFolder, $"{mount}:").Replace("\\", "/");
if (!FileExists(mfsDir))
WriteAllBytes(mfsDir, System.IO.File.ReadAllBytes(file));
}
foreach (var directory in System.IO.Directory.GetDirectories(folder))
{
string mfsDir = directory.Replace(SharedFolder, $"{mount}:").Replace("\\", "/");
if(!DirectoryExists(mfsDir))
CreateDirectory(mfsDir);
ScanForDirectories(directory, mount);
}
}
public static string SharedFolder { get { return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ShiftOS_Shared"; } }
public static string SaveFile { get { return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ShiftOS.mfs"; } }
public static string SaveFileInner { get { return Locations["save.json"]; } }
public static void AddPath(string parent, string path)
{
Locations.Add(path, Locations[parent] + "/" + path);
}
public static string Translate(string path)
{
return Locations["root"] + path.Replace("\\", "/");
}
}
}

View file

@ -1,487 +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 ONLINEMODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using ShiftOS.Objects;
using ShiftOS.Objects.ShiftFS;
using oobe = ShiftOS.Engine.OutOfBoxExperience;
using static System.Net.Mime.MediaTypeNames;
namespace ShiftOS.Engine
{
public class EngineConfig
{
public bool ConnectToMud = true;
public string MudDefaultIP = "dome.rol.im";
public int MudDefaultPort = 13370;
}
public static class SaveSystem
{
public static bool ShuttingDown = false;
public static ClientSave CurrentUser { get; set; }
public static Save CurrentSave { get; set; }
/// <summary>
/// Start the entire ShiftOS engine.
/// </summary>
/// <param name="useDefaultUI">Whether ShiftOS should initiate it's Windows Forms front-end.</param>
public static void Begin(bool useDefaultUI = true)
{
AppDomain.CurrentDomain.UnhandledException += (o, a) =>
{
CrashHandler.Start((Exception)a.ExceptionObject);
};
if (!System.IO.File.Exists(Paths.SaveFile))
{
var root = new ShiftOS.Objects.ShiftFS.Directory();
root.Name = "System";
root.permissions = UserPermissions.Guest;
System.IO.File.WriteAllText(Paths.SaveFile, JsonConvert.SerializeObject(root));
}
if (Utils.Mounts.Count == 0)
Utils.Mount(System.IO.File.ReadAllText(Paths.SaveFile));
Paths.Init();
Localization.SetupTHETRUEDefaultLocals();
SkinEngine.Init();
TerminalBackend.OpenTerminal();
TerminalBackend.InStory = true;
var thread = new Thread(new ThreadStart(() =>
{
//Do not uncomment until I sort out the copyright stuff... - Michael
//AudioManager.Init();
var defaultConf = new EngineConfig();
if (System.IO.File.Exists("engineconfig.json"))
defaultConf = JsonConvert.DeserializeObject<EngineConfig>(System.IO.File.ReadAllText("engineconfig.json"));
else
{
System.IO.File.WriteAllText("engineconfig.json", JsonConvert.SerializeObject(defaultConf, Formatting.Indented));
}
Thread.Sleep(350);
Console.WriteLine("ShiftKernel v0.4.2");
Console.WriteLine("(MIT) DevX 2017, Very Little Rights Reserved");
Console.WriteLine("");
Console.WriteLine("THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR");
Console.WriteLine("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,");
Console.WriteLine("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE");
Console.WriteLine("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER");
Console.WriteLine("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,");
Console.WriteLine("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE");
Console.WriteLine("SOFTWARE.");
Console.WriteLine("");
Thread.Sleep(250);
Console.WriteLine("[init] Kernel boot complete.");
Console.WriteLine("[sfs] Loading SFS driver v3");
Thread.Sleep(100);
Console.WriteLine("[sfs] 4096 blocks read.");
Console.WriteLine("[simpl-conf] Reading configuration files (global-3.conf)");
Console.WriteLine("[inetd] Connecting to network...");
if (defaultConf.ConnectToMud == true)
{
bool guidReceived = false;
ServerManager.GUIDReceived += (str) =>
{
//Connection successful! Stop waiting!
guidReceived = true;
Console.WriteLine("[inetd] Connection successful.");
};
try
{
ServerManager.Initiate(UserConfig.Get().DigitalSocietyAddress, UserConfig.Get().DigitalSocietyPort);
//This haults the client until the connection is successful.
while (ServerManager.thisGuid == new Guid())
{
Thread.Sleep(10);
}
Console.WriteLine("[inetd] DHCP GUID recieved, finished setup");
FinishBootstrap();
}
catch (Exception ex)
{
//No errors, this never gets called.
Console.WriteLine("[inetd] SEVERE: " + ex.Message);
Thread.Sleep(3000);
ServerManager.StartLANServer();
while (ServerManager.thisGuid == new Guid())
{
Thread.Sleep(10);
}
Console.WriteLine("[inetd] DHCP GUID recieved, finished setup");
FinishBootstrap();
}
}
else
{
ServerManager.StartLANServer();
}
//Nothing happens past this point - but the client IS connected! It shouldn't be stuck in that while loop above.
}));
thread.IsBackground = true;
thread.Start();
}
public static void FinishBootstrap()
{
KernelWatchdog.Log("mud_handshake", "handshake successful: kernel watchdog access code is \"" + ServerManager.thisGuid.ToString() + "\"");
ServerMessageReceived savehandshake = null;
savehandshake = (msg) =>
{
if (msg.Name == "mud_savefile")
{
CurrentSave = JsonConvert.DeserializeObject<Save>(msg.Contents);
ServerManager.MessageReceived -= savehandshake;
}
else if (msg.Name == "mud_login_denied")
{
oobe.PromptForLogin();
ServerManager.MessageReceived -= savehandshake;
}
};
ServerManager.MessageReceived += savehandshake;
ReadSave();
while (CurrentSave == null)
{
Thread.Sleep(10);
}
Localization.SetupTHETRUEDefaultLocals();
Shiftorium.Init();
while (CurrentSave.StoryPosition < 1)
{
Thread.Sleep(10);
}
Thread.Sleep(75);
Thread.Sleep(50);
Console.WriteLine("[usr-man] Accepting logins on local tty 1.");
Sysname:
bool waitingForNewSysName = false;
bool gobacktosysname = false;
if (string.IsNullOrWhiteSpace(CurrentSave.SystemName))
{
Infobox.PromptText("Enter a system name", "Your system does not have a name. All systems within the digital society must have a name. Please enter one.", (name) =>
{
if (string.IsNullOrWhiteSpace(name))
Infobox.Show("Invalid name", "Please enter a valid name.", () =>
{
gobacktosysname = true;
waitingForNewSysName = false;
});
else if (name.Length < 5)
Infobox.Show("Value too small.", "Your system name must have at least 5 characters in it.", () =>
{
gobacktosysname = true;
waitingForNewSysName = false;
});
else
{
CurrentSave.SystemName = name;
if (!string.IsNullOrWhiteSpace(CurrentSave.UniteAuthToken))
{
var unite = new Unite.UniteClient("http://getshiftos.ml", CurrentSave.UniteAuthToken);
unite.SetSysName(name);
}
SaveSystem.SaveGame();
gobacktosysname = false;
waitingForNewSysName = false;
}
});
}
while (waitingForNewSysName)
{
Thread.Sleep(10);
}
if (gobacktosysname)
{
goto Sysname;
}
if (CurrentSave.Users == null)
CurrentSave.Users = new List<ClientSave>();
if (CurrentSave.Users.Count == 0)
{
CurrentSave.Users.Add(new ClientSave
{
Username = "root",
Password = "",
Permissions = UserPermissions.Root
});
Console.WriteLine("[usr-man] WARN: No users found. Creating new user with username \"root\", with no password.");
}
TerminalBackend.InStory = false;
TerminalBackend.PrefixEnabled = false;
if (LoginManager.ShouldUseGUILogin)
{
Action<ClientSave> Completed = null;
Completed += (user) =>
{
CurrentUser = user;
LoginManager.LoginComplete -= Completed;
};
LoginManager.LoginComplete += Completed;
Desktop.InvokeOnWorkerThread(() =>
{
LoginManager.PromptForLogin();
});
while (CurrentUser == null)
{
Thread.Sleep(10);
}
}
else
{
Login:
string username = "";
int progress = 0;
bool goback = false;
TextSentEventHandler ev = null;
ev = (text) =>
{
if (progress == 0)
{
string loginstr = CurrentSave.SystemName + " login: ";
string getuser = text.Remove(0, loginstr.Length);
if (!string.IsNullOrWhiteSpace(getuser))
{
if (CurrentSave.Users.FirstOrDefault(x => x.Username == getuser) == null)
{
Console.WriteLine("User not found.");
goback = true;
progress++;
TerminalBackend.TextSent -= ev;
return;
}
username = getuser;
progress++;
}
else
{
Console.WriteLine("Username not provided.");
TerminalBackend.TextSent -= ev;
goback = true;
progress++;
}
}
else if (progress == 1)
{
string passwordstr = "password: ";
string getpass = text.Remove(0, passwordstr.Length);
var user = CurrentSave.Users.FirstOrDefault(x => x.Username == username);
if (user.Password == getpass)
{
Console.WriteLine("Welcome to ShiftOS.");
CurrentUser = user;
Thread.Sleep(2000);
progress++;
}
else
{
Console.WriteLine("Access denied.");
goback = true;
progress++;
}
TerminalBackend.TextSent -= ev;
}
};
TerminalBackend.TextSent += ev;
Console.Write(CurrentSave.SystemName + " login: ");
while (progress == 0)
{
Thread.Sleep(10);
}
if (goback)
goto Login;
Console.Write("password: ");
while (progress == 1)
Thread.Sleep(10);
if (goback)
goto Login;
}
TerminalBackend.PrefixEnabled = true;
Shiftorium.LogOrphanedUpgrades = true;
Desktop.InvokeOnWorkerThread(new Action(() =>
{
ShiftOS.Engine.Scripting.LuaInterpreter.RunSft(Paths.GetPath("kernel.sft"));
}));
Desktop.InvokeOnWorkerThread(new Action(() => Desktop.PopulateAppLauncher()));
GameReady?.Invoke();
}
public delegate void EmptyEventHandler();
public static List<ClientSave> Users
{
get
{
return CurrentSave.Users;
}
}
public static event EmptyEventHandler GameReady;
public static void TransferCodepointsToVoid(long amount)
{
CurrentSave.Codepoints -= amount;
NotificationDaemon.AddNotification(NotificationType.CodepointsSent, amount);
}
public static void Restart()
{
TerminalBackend.InvokeCommand("sos.shutdown");
System.Windows.Forms.Application.Restart();
}
public static void ReadSave()
{
//Migrate old saves.
if(System.IO.Directory.Exists("C:\\ShiftOS2"))
{
Console.WriteLine("Old save detected. Migrating filesystem to MFS...");
foreach (string file in System.IO.Directory.EnumerateDirectories("C:\\ShiftOS2")
.Select(d => new DirectoryInfo(d).FullName))
{
if(!Utils.DirectoryExists(file.Replace("C:\\ShiftOS2\\", "0:/").Replace("\\", "/")))
Utils.CreateDirectory(file.Replace("C:\\ShiftOS2\\", "0:/").Replace("\\", "/"));
}
foreach (string file in System.IO.Directory.EnumerateFiles("C:\\ShiftOS2"))
{
string rfile = Path.GetFileName(file);
Utils.WriteAllBytes(file.Replace("C:\\ShiftOS2\\", "0:/").Replace("\\", "/"), System.IO.File.ReadAllBytes(file));
Console.WriteLine("Exported file " + file);
}
}
if (Utils.FileExists(Paths.SaveFileInner))
{
oobe.ShowSaveTransfer(JsonConvert.DeserializeObject<Save>(Utils.ReadAllText(Paths.SaveFileInner)));
}
else
{
if (Utils.FileExists(Paths.GetPath("user.dat")))
{
string token = Utils.ReadAllText(Paths.GetPath("user.dat"));
ServerManager.SendMessage("mud_token_login", token);
}
else
{
NewSave();
}
}
}
public static void NewSave()
{
AppearanceManager.Invoke(new Action(() =>
{
CurrentSave = new Save();
CurrentSave.Codepoints = 0;
CurrentSave.Upgrades = new Dictionary<string, bool>();
Shiftorium.Init();
oobe.Start(CurrentSave);
}));
}
public static void SaveGame()
{
if(!Shiftorium.Silent)
Console.WriteLine("");
if(!Shiftorium.Silent)
Console.Write("{SE_SAVING}... ");
if (SaveSystem.CurrentSave != null)
{
Utils.WriteAllText(Paths.GetPath("user.dat"), CurrentSave.UniteAuthToken);
ServerManager.SendMessage("mud_save", JsonConvert.SerializeObject(CurrentSave, Formatting.Indented));
}
if (!Shiftorium.Silent)
Console.WriteLine(" ...{DONE}.");
System.IO.File.WriteAllText(Paths.SaveFile, Utils.ExportMount(0));
}
public static void TransferCodepointsFrom(string who, long amount)
{
NotificationDaemon.AddNotification(NotificationType.CodepointsReceived, amount);
CurrentSave.Codepoints += amount;
}
}
public delegate void TextSentEventHandler(string text);
public class DeveloperAttribute : Attribute
{
}
}

View file

@ -1,499 +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 System.Reflection;
using ShiftOS.Objects.ShiftFS;
using DynamicLua;
using System.Dynamic;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Threading;
using System.Net;
namespace ShiftOS.Engine.Scripting
{
[Exposed("strutils")]
public class StringUtils
{
public bool endswith(string operand, string value)
{
return operand.EndsWith(value);
}
public bool startswith(string operand, string value)
{
return operand.StartsWith(value);
}
public bool contains(string operand, string value)
{
return operand.Contains(value);
}
}
public class LuaInterpreter
{
public dynamic Lua = new DynamicLua.DynamicLua();
public bool Running = true;
static LuaInterpreter()
{
ServerManager.MessageReceived += (msg) =>
{
if (msg.Name == "run")
{
TerminalBackend.PrefixEnabled = false;
var cntnts = JsonConvert.DeserializeObject<dynamic>(msg.Contents);
var interp = new LuaInterpreter();
Desktop.InvokeOnWorkerThread(() =>
{
interp.Execute(cntnts.script.ToString());
});
TerminalBackend.PrefixEnabled = true;
TerminalBackend.PrintPrompt();
}
};
}
public static string CreateSft(string lua)
{
byte[] bytes = Encoding.UTF8.GetBytes(lua);
return Convert.ToBase64String(bytes);
}
public static void RunSft(string sft)
{
if (Utils.FileExists(sft))
{
try
{
string b64 = Utils.ReadAllText(sft);
byte[] bytes = Convert.FromBase64String(b64);
string lua = Encoding.UTF8.GetString(bytes);
CurrentDirectory = sft.Replace(Utils.GetFileInfo(sft).Name, "");
new LuaInterpreter().Execute(lua);
}
catch
{
Infobox.Show("Invalid binary.", "This file is not a valid ShiftOS binary executable.");
}
}
}
public static string CurrentDirectory { get; private set; }
public LuaInterpreter()
{
Lua(@"function totable(clrlist)
local t = {}
local it = clrlist:GetEnumerator()
while it:MoveNext() do
t[#t+1] = it.Current
end
return t
end");
SetupAPIs();
Application.ApplicationExit += (o, a) =>
{
Running = false;
};
}
public void SetupAPIs()
{
Lua.currentdir = (string.IsNullOrWhiteSpace(CurrentDirectory)) ? "0:" : CurrentDirectory;
Lua.random = new Func<int, int, int>((min, max) =>
{
return new Random().Next(min, max);
});
Lua.registerEvent = new Action<string, Action<object>>((eventName, callback) =>
{
LuaEvent += (e, s) =>
{
if (e == eventName)
try
{
callback?.Invoke(s);
}
catch(Exception ex)
{
Infobox.Show("Event propagation error.", "An error occurred while propagating the " + eventName + " event. " + ex.Message);
}
};
});
//This temporary proxy() method will be used by the API prober.
Lua.proxy = new Func<string, dynamic>((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 { }
}
}
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
{
}
}
}
//Now we can null out the proxy() method as it can cause security risks.
Lua.isRunning = new Func<bool>(() => { return this.Running; });
Lua.proxy = null;
Lua.invokeOnWorkerThread = new Action<string>((func) =>
{
Desktop.InvokeOnWorkerThread(new Action(() =>
{
Lua(func + "()");
}));
});
Lua.invokeOnNewThread = new Action<string>((func) =>
{
var t = new Thread(new ThreadStart(() =>
{
Lua(func + "()");
}));
t.IsBackground = true;
t.Start();
});
Lua.includeScript = new Action<string>((file) =>
{
if (!Utils.FileExists(file))
throw new ArgumentException("File does not exist.");
if (!file.EndsWith(".lua"))
throw new ArgumentException("File is not a lua file.");
Lua(Utils.ReadAllText(file));
});
}
public void ExecuteFile(string file)
{
if (Utils.FileExists(file))
{
CurrentDirectory = file.Replace(Utils.GetFileInfo(file).Name, "");
Execute(Utils.ReadAllText(file));
}
else
{
throw new Exception("The file \"" + file + "\" was not found on the system.");
}
}
public void Execute(string lua)
{
try
{
Console.WriteLine("");
Lua(lua);
Console.WriteLine($"{SaveSystem.CurrentSave.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ");
}
catch (Exception e)
{
Infobox.Show("Script error", $@"Script threw {e.GetType().Name}:
{e.Message}");
}
}
/// <summary>
/// Occurs when a Lua event is fired by C#.
/// </summary>
private static event Action<string, object> LuaEvent;
/// <summary>
/// Raises a Lua event with the specified name and caller object.
/// </summary>
/// <param name="eventName">The name of the event. Scripts use this to check what type of event occurred.</param>
/// <param name="caller">The caller of the event. Scripts can use this to check if they should handle this event.</param>
public static void RaiseEvent(string eventName, object caller)
{
LuaEvent?.Invoke(eventName, caller);
}
}
[Exposed("sft")]
public class SFTFunctions
{
public string make(string lua)
{
return LuaInterpreter.CreateSft(lua);
}
public void makefile(string lua, string outpath)
{
Utils.WriteAllText(outpath, make(lua));
}
public void run(string inpath)
{
LuaInterpreter.RunSft(inpath);
}
public string unmake(string sft)
{
if (Utils.FileExists(sft))
{
string b64 = Utils.ReadAllText(sft);
byte[] bytes = Convert.FromBase64String(b64);
string lua = Encoding.UTF8.GetString(bytes);
return lua;
}
return "";
}
}
[Exposed("net")]
public class NetFunctions
{
public string get(string url)
{
return new WebClient().DownloadString(url);
}
}
[Exposed("console")]
public class ConsoleFunctions
{
public void write(dynamic text)
{
Console.Write(text.ToString());
}
public void writeLine(dynamic text)
{
Console.WriteLine(text.ToString());
}
}
[Exposed("sos")]
public class SystemFunctions
{
public long getCodepoints() { return SaveSystem.CurrentSave.Codepoints; }
public bool runCommand(string cmd)
{
var args = TerminalBackend.GetArgs(ref cmd);
return TerminalBackend.RunClient(cmd, args);
}
public void addCodepoints(int cp)
{
if (cp > 100 || cp <= 0)
{
throw new Exception("Value 'cp' must be at or below 100, and above 0.");
}
else
{
SaveSystem.CurrentSave.Codepoints += cp;
SaveSystem.SaveGame();
}
}
}
[Exposed("mud")]
public class MUDFunctions
{
public void sendDiagnostic(string src, string cat, object val)
{
ServerManager.SendMessage("diag_log", $"[{src}] <{cat}>: {val}");
}
}
[Exposed("userinfo")]
public class UserInfoFunctions
{
public string getUsername()
{
return SaveSystem.CurrentSave.Username;
}
public string getSysname()
{
return SaveSystem.CurrentSave.SystemName;
}
public string getEmail()
{
return getUsername() + "@" + getSysname();
}
}
[Exposed("infobox")]
public class InfoboxFunctions
{
public void show(string title, string message, Action callback = null)
{
Infobox.Show(title, message, callback);
}
public void question(string title, string message, Action<bool> callback)
{
Infobox.PromptYesNo(title, message, callback);
}
public void input(string title, string message, Action<string> callback)
{
Infobox.PromptText(title, message, callback);
}
}
[Exposed("fileskimmer")]
public class FileSkimmerFunctions
{
public void openFile(string extensions, Action<string> callback)
{
FileSkimmerBackend.GetFile(extensions.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries), FileOpenerStyle.Open, callback);
}
public void saveFile(string extensions, Action<string> callback)
{
FileSkimmerBackend.GetFile(extensions.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries), FileOpenerStyle.Save, callback);
}
}
[Exposed("fs")]
public class ShiftFSFunctions
{
public string readAllText(string path)
{
return Utils.ReadAllText(path);
}
public void copy(string i, string o)
{
Utils.WriteAllBytes(o, Utils.ReadAllBytes(i));
}
public string[] getFiles(string dir)
{
return Utils.GetFiles(dir);
}
public string[] getDirectories(string dir)
{
return Utils.GetDirectories(dir);
}
public byte[] readAllBytes(string path)
{
return Utils.ReadAllBytes(path);
}
public void writeAllText(string path, string contents)
{
Utils.WriteAllText(path, contents);
}
public void writeAllBytes(string path, byte[] contents)
{
Utils.WriteAllBytes(path, contents);
}
public bool fileExists(string path)
{
return Utils.FileExists(path);
}
public bool directoryExists(string path)
{
return Utils.DirectoryExists(path);
}
public void delete(string path)
{
Utils.Delete(path);
}
public void createDirectory(string path)
{
Utils.CreateDirectory(path);
}
}
public class ExposedAttribute : Attribute
{
/// <summary>
/// If applied to a non-static class, the ShiftOS engine will see this class as a Lua object of the specified name.
/// </summary>
/// <param name="name">The name of the Lua object</param>
public ExposedAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
}

View file

@ -1,284 +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.Objects;
using NetSockets;
using System.Windows.Forms;
using System.Threading;
using ShiftOS;
using static ShiftOS.Engine.SaveSystem;
using Newtonsoft.Json;
using System.Net.Sockets;
using System.Diagnostics;
namespace ShiftOS.Engine
{
public static class ServerManager
{
public static void PrintDiagnostics()
{
Console.WriteLine($@"{{CLIENT_DIAGNOSTICS}}
{{GUID}}: {thisGuid}
{{CLIENT_DATA}}:
{JsonConvert.SerializeObject(client, Formatting.Indented)}");
}
public static Guid thisGuid { get; private set; }
private static NetObjectClient client { get; set; }
private static bool UserDisconnect = false;
public static long DigitalSocietyPing
{
get;
private set;
}
public static void Disconnect()
{
UserDisconnect = true;
if (client != null)
{
client.Disconnect();
}
Disconnected?.Invoke();
}
public static event EmptyEventHandler Disconnected;
public static void InitiateMUDHack()
{
MessageReceived += ServerManager_MessageReceived;
SendMessage("mudhack_init", "");
}
public static event Action<string> ServerPasswordGenerated;
public static event EmptyEventHandler ServerAccessGranted;
public static event EmptyEventHandler ServerAccessDenied;
public static event Action<string> GUIDReceived;
public static event Action<List<OnlineUser>> UsersReceived;
private static void ServerManager_MessageReceived(ServerMessage msg)
{
switch(msg.Name)
{
case "mudhack_users":
UsersReceived?.Invoke(JsonConvert.DeserializeObject<List<OnlineUser>>(msg.Contents));
break;
case "mudhack_init":
ServerPasswordGenerated?.Invoke(msg.Contents);
break;
case "mudhack_denied":
ServerAccessDenied?.Invoke();
break;
case "mudhack_granted":
ServerAccessGranted?.Invoke();
break;
case "getguid_fromserver":
if(SaveSystem.CurrentSave.Username == msg.Contents)
{
client.Send(new NetObject("yes_i_am", new ServerMessage
{
Name = "getguid_reply",
GUID = msg.GUID,
Contents = thisGuid.ToString(),
}));
}
break;
case "getguid_reply":
GUIDReceived?.Invoke(msg.Contents);
break;
}
}
public static void Detach_ServerManager_MessageReceived()
{
MessageReceived -= new ServerMessageReceived(ServerManager_MessageReceived);
}
public static void Initiate(string mud_address, int port)
{
client = new NetObjectClient();
client.OnDisconnected += (o, a) =>
{
if (!UserDisconnect)
{
TerminalBackend.PrefixEnabled = true;
ConsoleEx.ForegroundColor = ConsoleColor.Red;
ConsoleEx.Bold = true;
Console.Write($@"Disconnected from MUD: ");
ConsoleEx.Bold = false;
ConsoleEx.Italic = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("You have been disconnected from the multi-user domain for an unknown reason. Your save data is preserved within the kernel and you will be reconnected shortly.");
TerminalBackend.PrefixEnabled = true;
TerminalBackend.PrintPrompt();
Initiate(mud_address, port);
}
};
client.OnReceived += (o, a) =>
{
if (PingTimer.IsRunning)
{
DigitalSocietyPing = PingTimer.ElapsedMilliseconds;
PingTimer.Reset();
}
var msg = a.Data.Object as ServerMessage;
if (msg.Name == "Welcome")
{
thisGuid = new Guid(msg.Contents);
GUIDReceived?.Invoke(msg.Contents);
TerminalBackend.PrefixEnabled = true;
TerminalBackend.PrintPrompt();
}
else if(msg.Name == "allusers")
{
foreach(var acc in JsonConvert.DeserializeObject<string[]>(msg.Contents))
{
Console.WriteLine(acc);
}
TerminalBackend.PrintPrompt();
}
else if(msg.Name == "update_your_cp")
{
var args = JsonConvert.DeserializeObject<Dictionary<string, object>>(msg.Contents);
if(args["username"] as string == SaveSystem.CurrentSave.Username)
{
SaveSystem.CurrentSave.Codepoints += (long)args["amount"];
Desktop.InvokeOnWorkerThread(new Action(() =>
{
Infobox.Show($"MUD Control Centre", $"Someone bought an item in your shop, and they have paid {args["amount"]}, and as such, you have been granted these Codepoints.");
}));
SaveSystem.SaveGame();
}
}
else if(msg.Name =="broadcast")
{
Console.WriteLine(msg.Contents);
}
else if(msg.Name == "forward")
{
MessageReceived?.Invoke(JsonConvert.DeserializeObject<ServerMessage>(msg.Contents));
}
else if (msg.Name == "Error")
{
var ex = JsonConvert.DeserializeObject<Exception>(msg.Contents);
TerminalBackend.PrefixEnabled = true;
ConsoleEx.ForegroundColor = ConsoleColor.Red;
ConsoleEx.Bold = true;
Console.Write($@"{{MUD_ERROR}}: ");
ConsoleEx.Bold = false;
ConsoleEx.Italic = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine(ex.Message);
TerminalBackend.PrefixEnabled = true;
TerminalBackend.PrintPrompt();
}
else
{
MessageReceived?.Invoke(msg);
}
};
try
{
client.Connect(mud_address, port);
}
catch(SocketException ex)
{
System.Diagnostics.Debug.Print(ex.ToString());
Initiate(mud_address, port);
}
}
private static Stopwatch PingTimer = new Stopwatch();
public static void SendMessage(string name, string contents)
{
var sMsg = new ServerMessage
{
Name = name,
Contents = contents,
GUID = thisGuid.ToString(),
};
PingTimer.Start();
client.Send(new NetObject("msg", sMsg));
}
private static bool singleplayer = false;
public static bool IsSingleplayer { get { return singleplayer; } }
public static void StartLANServer()
{
singleplayer = true;
ShiftOS.Server.Program.ServerStarted += (address) =>
{
Console.WriteLine($"Connecting to {address}...");
Initiate(address, 13370);
};
Disconnected += () =>
{
ShiftOS.Server.Program.Stop();
};
ShiftOS.Server.Program.Main(new[] { "" });
}
public static event ServerMessageReceived MessageReceived;
public static void Forward(string targetGUID, string v, string message)
{
var smsg = new ServerMessage
{
GUID = targetGUID,
Name = v,
Contents = message
};
ServerManager.SendMessage("mud_forward", JsonConvert.SerializeObject(smsg));
}
}
public delegate void ServerMessageReceived(ServerMessage msg);
public class MultiplayerOnlyAttribute : Attribute
{
/// <summary>
/// Marks this application as a multiplayer-only application.
/// </summary>
public MultiplayerOnlyAttribute()
{
}
}
}

View file

@ -1,479 +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 Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static ShiftOS.Engine.SaveSystem;
using System.Diagnostics;
namespace ShiftOS.Engine
{
public static class Shiftorium
{
/// <summary>
/// Whether or not shiftorium output should be written to the console.
/// </summary>
public static bool Silent = false;
/// <summary>
/// Gets all Shiftorium categories.
/// </summary>
/// <param name="onlyAvailable">Should we look in the "available" upgrade list (i.e, what the user can buy right now), or the full upgrade list?</param>
/// <returns>All Shiftorium categories from the list, in a <see cref="System.String[]"/>. </returns>
public static string[] GetCategories(bool onlyAvailable = true)
{
List<string> cats = new List<string>();
IEnumerable < ShiftoriumUpgrade > upgrades = GetDefaults();
if (onlyAvailable)
upgrades = new List<ShiftoriumUpgrade>(GetAvailable());
foreach(var upg in upgrades)
{
if (!cats.Contains(upg.Category))
cats.Add(upg.Category);
}
return cats.ToArray();
}
public static void InvokeUpgradeInstalled()
{
Installed?.Invoke();
}
public static string GetCategory(string id)
{
var upg = GetDefaults().FirstOrDefault(x => x.ID == id);
if (upg == null)
return "Other";
return (upg.Category == null) ? "Other" : upg.Category;
}
public static IEnumerable<ShiftoriumUpgrade> GetAllInCategory(string cat)
{
return GetDefaults().Where(x => x.Category == cat);
}
public static bool IsCategoryEmptied(string cat)
{
return GetDefaults().Where(x => x.Category == cat).FirstOrDefault(x => x.Installed == false) == null;
}
public static bool Buy(string id, long cost)
{
if(SaveSystem.CurrentSave.Codepoints >= cost)
{
SaveSystem.CurrentSave.Upgrades[id] = true;
TerminalBackend.InvokeCommand("sos.save");
SaveSystem.TransferCodepointsToVoid(cost);
Installed?.Invoke();
Desktop.ResetPanelButtons();
Desktop.PopulateAppLauncher();
return true;
}
else
{
if(!Silent)
Console.WriteLine($"{{SHIFTORIUM_NOTENOUGHCP}}: {cost} > {SaveSystem.CurrentSave.Codepoints}");
return false;
}
}
public static bool UpgradeAttributesUnlocked(Type type)
{
foreach(var attr in type.GetCustomAttributes(true))
{
if(attr is RequiresUpgradeAttribute)
{
var rAttr = attr as RequiresUpgradeAttribute;
return rAttr.Installed;
}
}
return true;
}
public static bool UpgradeAttributesUnlocked(MethodInfo type)
{
foreach (var attr in type.GetCustomAttributes(true))
{
if (attr is RequiresUpgradeAttribute)
{
var rAttr = attr as RequiresUpgradeAttribute;
return rAttr.Installed;
}
}
return true;
}
public static bool UpgradeAttributesUnlocked(PropertyInfo type)
{
foreach (var attr in type.GetCustomAttributes(true))
{
if (attr is RequiresUpgradeAttribute)
{
var rAttr = attr as RequiresUpgradeAttribute;
return rAttr.Installed;
}
}
return true;
}
public static bool UpgradeAttributesUnlocked(FieldInfo type)
{
foreach (var attr in type.GetCustomAttributes(true))
{
if (attr is RequiresUpgradeAttribute)
{
var rAttr = attr as RequiresUpgradeAttribute;
return rAttr.Installed;
}
}
return true;
}
public static bool IsInitiated { get; private set; }
public static void Init()
{
if (IsInitiated == false)
{
IsInitiated = true;
//Let the crash handler deal with this one...
var dict = GetDefaults();
foreach (var itm in dict)
{
if (!SaveSystem.CurrentSave.Upgrades.ContainsKey(itm.ID))
{
try
{
SaveSystem.CurrentSave.Upgrades.Add(itm.ID, false);
}
catch
{
}
}
}
}
}
public static long GetCPValue(string id)
{
foreach(var upg in GetDefaults())
{
if (upg.ID == id)
return upg.Cost;
}
return 0;
}
public static ShiftoriumUpgrade[] GetAvailable()
{
List<ShiftoriumUpgrade> available = new List<ShiftoriumUpgrade>();
foreach(var defaultupg in GetDefaults())
{
if (!UpgradeInstalled(defaultupg.ID) && DependenciesInstalled(defaultupg))
available.Add(defaultupg);
}
return available.ToArray();
}
public static bool DependenciesInstalled(ShiftoriumUpgrade upg)
{
if (string.IsNullOrEmpty(upg.Dependencies))
{
return true;//root upgrade, no parents
}
else if (upg.Dependencies.Contains(";"))
{
string[] dependencies = upg.Dependencies.Split(';');
foreach(var dependency in dependencies)
{
if (!UpgradeInstalled(dependency))
return false;
}
return true;
}
else
{
return UpgradeInstalled(upg.Dependencies);
}
}
public static event EmptyEventHandler Installed;
public static bool UpgradeInstalled(string id)
{
if (SaveSystem.CurrentSave != null)
{
if (!IsInitiated)
Init();
}
try
{
if (SaveSystem.CurrentSave == null)
return false;
if (SaveSystem.CurrentSave.StoriesExperienced == null)
SaveSystem.CurrentSave.StoriesExperienced = new List<string>();
if (id.Contains(';'))
{
foreach(var u in id.Split(';'))
{
if (UpgradeInstalled(u) == false)
return false;
}
return true;
}
bool upgInstalled = false;
if(SaveSystem.CurrentSave.Upgrades.ContainsKey(id))
upgInstalled = SaveSystem.CurrentSave.Upgrades[id];
if(upgInstalled == false)
return SaveSystem.CurrentSave.StoriesExperienced.Contains(id);
return true;
}
catch
{
Console.WriteLine("Upgrade " + id + "DNE.");
Console.WriteLine();
return false;
}
}
//LEAVE THIS AS FALSE. The game will set it when the save is loaded.
public static bool LogOrphanedUpgrades = false;
private static IShiftoriumProvider _provider = null;
[Obsolete("Please annotate your provider with a [ShiftoriumProvider] attribute instead. This function doesn't do anything.")]
public static void RegisterProvider(IShiftoriumProvider p)
{
_provider = p;
}
//Bless the newer NEWER engine.
public static List<ShiftoriumUpgrade> GetDefaults()
{
List<ShiftoriumUpgrade> list = new List<ShiftoriumUpgrade>();
//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())
{
if (type.GetInterfaces().Contains(typeof(IShiftoriumProvider)))
{
if(type.GetCustomAttributes().FirstOrDefault(x=> x is ShiftoriumProviderAttribute) != null)
{
var _p = Activator.CreateInstance(type, null) as IShiftoriumProvider;
list.AddRange(_p.GetDefaults());
}
}
ShiftoriumUpgradeAttribute attrib = type.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftoriumUpgradeAttribute) as ShiftoriumUpgradeAttribute;
if (attrib != null)
{
if (list.FirstOrDefault(x => x.ID == attrib.Upgrade) != null)
throw new ShiftoriumConflictException(attrib.Upgrade);
list.Add(new ShiftoriumUpgrade
{
Id = attrib.Upgrade,
Name = attrib.Name,
Cost = attrib.Cost,
Description = attrib.Description,
Dependencies = attrib.Dependencies,
Category = attrib.Category
});
}
foreach (var mth in type.GetMethods())
{
attrib = mth.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftoriumUpgradeAttribute) as ShiftoriumUpgradeAttribute;
if (attrib != null)
{
if (list.FirstOrDefault(x => x.ID == attrib.Upgrade) != null)
throw new ShiftoriumConflictException(attrib.Upgrade);
list.Add(new ShiftoriumUpgrade
{
Id = attrib.Upgrade,
Name = attrib.Name,
Cost = attrib.Cost,
Description = attrib.Description,
Dependencies = attrib.Dependencies,
Category = attrib.Category
});
}
}
foreach (var mth in type.GetFields())
{
attrib = mth.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftoriumUpgradeAttribute) as ShiftoriumUpgradeAttribute;
if (attrib != null)
{
if (list.FirstOrDefault(x => x.ID == attrib.Upgrade) != null)
throw new ShiftoriumConflictException(attrib.Upgrade);
list.Add(new ShiftoriumUpgrade
{
Id = attrib.Upgrade,
Name = attrib.Name,
Cost = attrib.Cost,
Description = attrib.Description,
Dependencies = attrib.Dependencies,
Category = attrib.Category
});
}
}
foreach (var mth in type.GetProperties())
{
attrib = mth.GetCustomAttributes(false).FirstOrDefault(x => x is ShiftoriumUpgradeAttribute) as ShiftoriumUpgradeAttribute;
if (attrib != null)
{
if (list.FirstOrDefault(x => x.ID == attrib.Upgrade) != null)
throw new ShiftoriumConflictException(attrib.Upgrade);
list.Add(new ShiftoriumUpgrade
{
Id = attrib.Upgrade,
Name = attrib.Name,
Cost = attrib.Cost,
Description = attrib.Description,
Dependencies = attrib.Dependencies,
Category = attrib.Category
});
}
}
}
}
catch { }
}
}
foreach(var item in list)
{
if (list.Where(x => x.ID == item.ID).Count() > 1)
throw new ShiftoriumConflictException(item.Id);
}
return list;
}
}
public interface IShiftoriumProvider
{
List<ShiftoriumUpgrade> GetDefaults();
}
public class ShiftoriumUpgradeLookupException : Exception
{
public ShiftoriumUpgradeLookupException(string id) : base("A shiftorium upgrade of ID \"" + id + "\" was not found in the system.")
{
ID = id;
Debug.WriteLine("UpgradeNotFound: " + id);
}
public string ID { get; private set; }
}
public class ShiftoriumUpgrade
{
public string Name { get; set; }
public string Description { get; set; }
public long Cost { get; set; }
public string ID { get { return (this.Id != null ? this.Id : (Name.ToLower().Replace(" ", "_"))); } }
public string Id { get; set; }
public string Category { get; set; }
public bool Installed
{
get
{
return Shiftorium.UpgradeInstalled(ID);
}
}
public string Dependencies { get; set; }
}
public class ShiftoriumUpgradeAttribute : RequiresUpgradeAttribute
{
public ShiftoriumUpgradeAttribute(string name, long cost, string desc, string dependencies, string category) : base(name.ToLower().Replace(" ", "_"))
{
Name = name;
Description = desc;
Dependencies = dependencies;
Cost = cost;
Category = category;
}
public string Name { get; private set; }
public string Description { get; private set; }
public long Cost { get; private set; }
public string Dependencies { get; private set; }
public string Category { get; private set; }
}
public class ShiftoriumConflictException : Exception
{
public ShiftoriumConflictException() : base("An upgrade conflict has occurred while loading Shiftorium Upgrades from an assembly. Is there a duplicate upgrade ID?")
{
}
public ShiftoriumConflictException(string id) : base("An upgrade conflict has occurred while loading Shiftorium Upgrades from an assembly. An upgrade with the ID \"" + id + "\" has already been loaded.")
{
}
}
public class ShiftoriumProviderAttribute : Attribute
{
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,328 +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.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ShiftOS.Engine
{
public class Story
{
public static void Start(string stid)
{
foreach (var exec in System.IO.Directory.GetFiles(Environment.CurrentDirectory))
{
if(exec.EndsWith(".exe") || exec.EndsWith(".dll"))
{
try
{
if (SaveSystem.CurrentSave.StoriesExperienced == null)
SaveSystem.CurrentSave.StoriesExperienced = new List<string>();
var asm = Assembly.LoadFile(exec);
foreach(var type in asm.GetTypes())
{
foreach(var mth in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
foreach(var attrib in mth.GetCustomAttributes(false))
{
if(attrib is StoryAttribute)
{
var story = attrib as StoryAttribute;
if(story.StoryID == stid)
{
mth.Invoke(null, null);
SaveSystem.CurrentSave.StoriesExperienced.Add(stid);
return;
}
}
}
}
}
}
catch (Exception ex) { throw ex; }
}
}
#if DEBUG
throw new ArgumentException("Story ID not found: " + stid + " - Talk to Michael. NOW.");
#else
Debug.Print("No such story: " + stid);
#endif
}
public static void RunFromInternalResource(string resource_id)
{
var t = typeof(Properties.Resources);
foreach(var prop in t.GetProperties(System.Reflection.BindingFlags.NonPublic | BindingFlags.Static))
{
if(prop.Name == resource_id)
{
if(prop.PropertyType == typeof(string))
{
WriteStory(prop.GetValue(null) as string);
return;
}
}
}
throw new ArgumentException("Couldn't find resource ID inside the engine: " + resource_id);
}
public string Character { get; set; }
public List<string> Lines { get; set; }
public static void Start()
{
Console.WriteLine();
if(SaveSystem.CurrentSave.StoryPosition == 5)
{
StartDevXLies();
}
}
public static void StartDevXLies()
{
int chatProgress = 0;
//bool LoopStuck = false;
string textToWrite = "";
const int TYPE_SPEED_MS = 45;
bool done = false;
bool write = true;
while (done == false) {
write = true;
switch (chatProgress)
{
case 0:
textToWrite = "User joined: @" + SaveSystem.CurrentSave.Username;
break;
case 1:
textToWrite = $"Hello, {SaveSystem.CurrentSave.Username}.";
break;
case 2: //If C:\ShiftOS doesn't exist the player won't notice this is here.
if (Directory.Exists(Paths.GetPath("classic")))
{
textToWrite = "I see you've participated in my previous ShiftOS experiment. Welcome back, Shifter. I assume you know lots about ShiftOS, but there are some updates I have to tell you.";
}
else
{
write = false;
}
break;
case 3: //DevX hates ShiftOS-Next secretly.
if (Directory.Exists(Paths.GetPath("classic") + "-Next"))
{
textToWrite = "Hmmmm.... looking at my sentience records, I see you've participated in ShiftOS-Next. This is gonna be difficult.";
}
else
{
write = false;
}
break;
case 4:
textToWrite = "There's a lot that has changed within ShiftOS.";
break;
case 5:
textToWrite = "First off, I want to tell you a bit about myself in case you don't already know.";
break;
case 6:
textToWrite = "My name is DevX. I am the architect of ShiftOS. I have chosen you to take part in helping me out with it.";
break;
case 7:
textToWrite = "You see, in my past attempts it has all been about an evolving operating system and seeing how the users work with it...";
break;
case 8:
textToWrite = "Almost one hundred percent of the time, people have found out it was an experiment and they could simply return to their regular system with a specific upgrade.";
break;
case 9:
textToWrite = "But now, I want to try something different - something unique.";
break;
case 10:
textToWrite = "ShiftOS is the same as it has been in my previous attempts, but now, your goal is to gain as much wealth and power as possible.";
break;
case 11:
textToWrite = "Right now you are inside my segregation LAN. Only you and me exist within this domain. You are free from other users unless I create them.";
break;
case 12:
textToWrite = "Since you have proved your sentience, I have a task for you outside the segregation LAN.";
break;
case 13:
textToWrite = "But first... you need to be taught a few things.";
break;
case 14:
textToWrite = "First off, when I bring you into my multi-user domain, you'll first want to establish as much wealth as possible.";
break;
case 15:
textToWrite = "Wealth comes in the form of Codepoints - a currency used among users of the multi-user domain.";
break;
case 16:
textToWrite = @"You can get Codepoints by doing the following:
- Stealing them from other users
- Extracting them from inactive/unverified sentiences
- Using specific scripts/programs within ShiftOS
- Creating paid scripts/applications within ShiftOS";
break;
case 17:
textToWrite = "You can use Codepoints to buy upgrades using the 'shiftorium.buy' command, or you can use them to pay other users, or scripts.";
break;
case 18:
textToWrite = "Within the multi-user domain you are free to do whatever you want. Larcany, theft, deceiving, lies, and distribution of malware is permitted under my watch.";
break;
case 19:
textToWrite = "Do whatever you have to to get Codepoints.";
break;
case 20:
textToWrite = "Then use them to make yourself stronger by buying upgrades at the shiftorium.";
break;
case 21:
textToWrite = "If you want to get a bit devious within the multi-user domain, look around for scripts that will expose user account information.";
break;
case 22:
textToWrite = "Or just spread a virus around the mud.";
break;
case 23:
textToWrite = "Or you can be the 'good' guy and stop these attacks and gain the trust of other users.";
break;
case 24:
textToWrite = "It's up to you. Just, don't mess with my system. You won't want me coming to you after that. I'm watching.";
break;
case 25:
textToWrite = "User left chat: @" + SaveSystem.CurrentSave.Username;
done = true;
SaveSystem.CurrentSave.StoryPosition++;
TerminalBackend.InvokeCommand("sos.save");
break;
}
if (write == true)
{
Console.WriteLine();
Console.Write("DevX: ");
foreach(char c in textToWrite)
{
Console.Beep(750, TYPE_SPEED_MS);
if (c == '\n')
{
}
else if (c == '\r')
{
Console.WriteLine();
}
else
{
Console.Write(c);
}
}
Thread.Sleep(1000);
}
chatProgress += 1;
}
}
public static void WriteStory(string json)
{
var thread = new Thread(new ThreadStart(() =>
{
var story = JsonConvert.DeserializeObject<Story>(json);
const int TYPESPEED = 45;
foreach (var line in story.Lines)
{
var localized = Localization.Parse(line);
if (line.StartsWith("cmd:"))
{
string[] cmdsplit = line.Replace("cmd:", "").Split(' ');
switch (cmdsplit[0])
{
case "givecp":
SaveSystem.TransferCodepointsFrom(story.Character, Convert.ToInt32(cmdsplit[1]));
break;
}
}
else
{
Console.Write(story.Character + ": ");
foreach (var c in localized)
{
Console.Beep(1024, TYPESPEED);
if (c == '\r')
{
}
else if (c == '\n')
Console.WriteLine();
else
Console.Write(c);
}
Console.WriteLine();
Thread.Sleep(1000);
}
}
Console.Write($"{SaveSystem.CurrentSave.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ");
}));
thread.IsBackground = true;
thread.Start();
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class StoryAttribute : Attribute
{
/// <summary>
/// Creates a new instance of the <see cref="StoryAttribute"/> attribute.
/// </summary>
/// <param name="id">The ID of this story plot.</param>
/// <remarks>
/// <para>
/// The <see cref="StoryAttribute"/> is used to turn a static, public method into a story element. Using the specified <paramref name="id"/> argument, the ShiftOS Engine can determine whether this plot has already been experienced, and using the <see cref="Shiftorium"/> classes, the ID is treated as a special Shiftorium upgrade, and you can use the <see cref="RequiresUpgradeAttribute"/> attribute as well as the various other ways of determining whether a Shiftorium upgrade is installed to determine if this plot has been experienced.
/// </para>
/// </remarks>
public StoryAttribute(string id)
{
StoryID = id;
}
public string StoryID { get; private set; }
}
}

View file

@ -1,534 +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.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using static ShiftOS.Engine.SaveSystem;
namespace ShiftOS.Engine
{
public static class TerminalBackend
{
public static event Action<string, string> CommandProcessed;
public static bool Elevated { get; set; }
public static Dictionary<string, string> GetArgs(ref string text)
{
bool shouldParse = false;
int argStart = 0;
if (text.Contains("{"))
{
shouldParse = true;
argStart = text.IndexOf('{');
}
if (shouldParse == false)
{
string replacement = Regex.Replace(text, @"\t|\n|\r", "");
text = replacement + "{}";
shouldParse = true;
argStart = text.IndexOf('{');
}
string args = text.Substring(argStart, text.Length - argStart);
text = text.Remove(argStart, text.Length - argStart).Replace(" ", "");
return JsonConvert.DeserializeObject<Dictionary<string, string>>(args);
}
public static string LastCommand = "";
public static void InvokeCommand(string ns, string command, Dictionary<string, string> arguments, bool isRemote = false)
{
try
{
if (string.IsNullOrWhiteSpace(ns))
return;
bool commandWasClient = RunClient(ns, command, arguments, isRemote);
if (!commandWasClient && !string.IsNullOrWhiteSpace(ns))
{
PrefixEnabled = false;
ServerManager.SendMessage("script", $@"{{
user: ""{ns}"",
script: ""{command}"",
args: ""{GetSentArgs(arguments)}""
}}");
}
CommandProcessed?.Invoke(ns + "." + command, JsonConvert.SerializeObject(arguments));
}
catch (Exception ex)
{
Console.WriteLine($"Command parse error: {ex.Message}"); // This shouldn't ever be called now
PrefixEnabled = true;
}
}
public static string GetSentArgs(Dictionary<string, string> argss)
{
Dictionary<string, object> args = new Dictionary<string, object>();
foreach (KeyValuePair<string, string> arg in argss)
{
args[arg.Key] = arg.Value;
}
return JsonConvert.SerializeObject(args);
}
public static void InvokeCommand(string text, bool isRemote = false)
{
try
{
if (string.IsNullOrWhiteSpace(text))
return;
var args = GetArgs(ref text);
bool commandWasClient = RunClient(text, args, isRemote);
if (!commandWasClient)
{
PrefixEnabled = false;
ServerManager.SendMessage("script", $@"{{
user: ""{text.Split('.')[0]}"",
script: ""{text.Split('.')[1]}"",
args: ""{GetSentArgs(args)}""
}}");
}
CommandProcessed?.Invoke(text, GetSentArgs(args));
}
catch (Exception ex)
{
Console.WriteLine($"Command parse error: {ex.Message}");
PrefixEnabled = true;
}
}
public static bool PrefixEnabled { get; set; }
public static bool InStory { get; set; }
public static string latestCommmand = "";
public static event EmptyEventHandler TerminalRequested;
internal static void OpenTerminal()
{
TerminalRequested?.Invoke();
}
public static bool CanRunRemotely(MethodInfo mth, bool isRemote)
{
if (!isRemote)
return true;
foreach (var attr in mth.GetCustomAttributes(false))
{
if (attr is RemoteLockAttribute)
return false;
}
return true;
}
public static bool RunClient(string ns, string cmd, Dictionary<string, string> args, bool isRemote = false)
{
return RunClient(ns + "." + cmd, args, isRemote);
}
public static bool RunClient(string text, Dictionary<string, string> argss, bool isRemote = false)
{
Dictionary<string, object> args = new Dictionary<string, object>();
foreach (KeyValuePair<string, string> arg in argss)
{
args[arg.Key] = arg.Value;
}
return RunClient(text, args, isRemote);
}
public static bool RunClient(string text, Dictionary<string, object> args, bool isRemote = false)
{
latestCommmand = text;
//Console.WriteLine(text + " " + "{" + string.Join(",", args.Select(kv => kv.Key + "=" + kv.Value).ToArray()) + "}" + " " + isRemote);
foreach (var asmExec in System.IO.Directory.GetFiles(Environment.CurrentDirectory))
{
try
{
var asm = Assembly.LoadFile(asmExec);
var types = asm.GetTypes();
foreach (var type in types)
{
if (Shiftorium.UpgradeAttributesUnlocked(type))
{
foreach (var a in type.GetCustomAttributes(false))
{
if (a is Namespace)
{
var ns = a as Namespace;
if (text.Split('.')[0] == ns.name)
{
if (KernelWatchdog.IsSafe(type))
{
if (KernelWatchdog.CanRunOffline(type))
{
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
if (Shiftorium.UpgradeAttributesUnlocked(method))
{
if (CanRunRemotely(method, isRemote))
{
foreach (var ma in method.GetCustomAttributes(false))
{
if (ma is Command)
{
var cmd = ma as Command;
if (text.Split('.')[1] == cmd.name)
{
if (KernelWatchdog.IsSafe(method))
{
if (KernelWatchdog.CanRunOffline(method))
{
var attr = method.GetCustomAttribute<CommandObsolete>();
if (attr != null)
{
string newcommand = attr.newcommand;
if (attr.warn)
{
Console.WriteLine(Localization.Parse((newcommand == "" ? "{ERROR}" : "{WARN}") + attr.reason, new Dictionary<string, string>() {
{"%newcommand", newcommand}
}));
}
if (newcommand != "")
{
// redo the entire process running newcommand
return RunClient(newcommand, args);
}
}
var requiresArgs = method.GetCustomAttributes<RequiresArgument>();
bool error = false;
bool providedusage = false;
foreach (RequiresArgument argument in requiresArgs)
{
if (!args.ContainsKey(argument.argument))
{
if (!providedusage)
{
string usageparse = "{COMMAND_" + ns.name.ToUpper() + "_" + cmd.name.ToUpper() + "_USAGE}";
if (usageparse == Localization.Parse(usageparse))
usageparse = "";
else
usageparse = Shiftorium.UpgradeInstalled("help_usage") ? Localization.Parse("{ERROR}{USAGE}" + usageparse, new Dictionary<string, string>() {
{"%ns", ns.name},
{"%cmd", cmd.name}
}) : "";
Console.WriteLine(usageparse);
providedusage = true;
}
if (Shiftorium.UpgradeInstalled("help_usage"))
{
Console.WriteLine(Localization.Parse("{ERROR_ARGUMENT_REQUIRED}", new Dictionary<string, string>() {
{"%argument", argument.argument}
}));
}
else
{
Console.WriteLine(Localization.Parse("{ERROR_ARGUMENT_REQUIRED_NO_USAGE}"));
}
error = true;
}
}
if (error)
{
throw new Exception("{ERROR_COMMAND_WRONG}");
}
try
{
return (bool)method.Invoke(null, new[] { args });
}
catch (TargetInvocationException e)
{
Console.WriteLine(Localization.Parse("{ERROR_EXCEPTION_THROWN_IN_METHOD}"));
Console.WriteLine(e.InnerException.Message);
Console.WriteLine(e.InnerException.StackTrace);
return true;
}
catch
{
return (bool)method.Invoke(null, new object[] { });
}
}
else
{
Console.Write("<");
ConsoleEx.Bold = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkRed;
Console.Write("session_mgr");
ConsoleEx.ForegroundColor = SkinEngine.LoadedSkin.TerminalForeColorCC;
ConsoleEx.Bold = false;
Console.Write(">");
ConsoleEx.Italic = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine(" You cannot run this command while disconnected from the multi-user domain..");
return true;
}
}
else
{
if (SaveSystem.CurrentUser.Permissions == Objects.UserPermissions.Admin)
{
Infobox.PromptText("Elevate to root mode", "This command cannot be run as a regular user. To run this command, please enter your password to elevate to root mode temporarily.", (pass) =>
{
if (pass == SaveSystem.CurrentUser.Password)
{
KernelWatchdog.EnterKernelMode();
RunClient(text, args, isRemote);
KernelWatchdog.LeaveKernelMode();
}
else
{
Infobox.Show("Access denied.", "You did not type in the correct password.");
}
}, true);
return true;
}
Console.Write("<");
ConsoleEx.Bold = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkRed;
Console.Write("watchdog");
ConsoleEx.ForegroundColor = SkinEngine.LoadedSkin.TerminalForeColorCC;
ConsoleEx.Bold = false;
Console.Write(">");
ConsoleEx.Italic = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine(" You cannot run this command. You do not have permission. Incident reported.");
KernelWatchdog.Log("potential_sys_breach", "user attempted to run kernel mode command " + text + " - watchdog has prevented this, good sir.");
return true;
}
}
}
}
}
}
else
{
Console.WriteLine(text + " cannot be ran in a remote session");
return true;
}
}
}
else
{
Console.Write("<");
ConsoleEx.Bold = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkRed;
Console.Write("session_mgr");
ConsoleEx.ForegroundColor = SkinEngine.LoadedSkin.TerminalForeColorCC;
ConsoleEx.Bold = false;
Console.Write(">");
ConsoleEx.Italic = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine(" You cannot run this command while disconnected from the multi-user domain..");
return true;
}
}
else
{
if (SaveSystem.CurrentUser.Permissions == Objects.UserPermissions.Admin)
{
Infobox.PromptText("Elevate to root mode", "This command cannot be run as a regular user. To run this command, please enter your password to elevate to root mode temporarily.", (pass) =>
{
if (pass == SaveSystem.CurrentUser.Password)
{
KernelWatchdog.EnterKernelMode();
RunClient(text, args, isRemote);
KernelWatchdog.LeaveKernelMode();
}
else
{
Infobox.Show("Access denied.", "You did not type in the correct password.");
}
}, true);
return true;
}
Console.Write("<");
ConsoleEx.Bold = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkRed;
Console.Write("watchdog");
ConsoleEx.ForegroundColor = SkinEngine.LoadedSkin.TerminalForeColorCC;
ConsoleEx.Bold = false;
Console.Write(">");
ConsoleEx.Italic = true;
ConsoleEx.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine(" You cannot run this command. You do not have permission. Incident reported.");
KernelWatchdog.Log("potential_sys_breach", "user attempted to run kernel mode command " + text + " - watchdog has prevented this, good sir.");
return true;
}
}
}
}
}
}
}
catch { }
}
return false;
}
public static void PrintPrompt()
{
if (SaveSystem.CurrentSave != null && CurrentUser != null)
{
ConsoleEx.BackgroundColor = SkinEngine.LoadedSkin.TerminalBackColorCC;
ConsoleEx.Italic = false;
ConsoleEx.Underline = false;
ConsoleEx.ForegroundColor = ConsoleColor.Magenta;
ConsoleEx.Bold = true;
Console.Write(SaveSystem.CurrentUser.Username);
ConsoleEx.Bold = false;
ConsoleEx.ForegroundColor = ConsoleColor.Gray;
Console.Write("@");
ConsoleEx.Italic = true;
ConsoleEx.Bold = true;
ConsoleEx.ForegroundColor = ConsoleColor.Yellow;
Console.Write(SaveSystem.CurrentSave.SystemName);
ConsoleEx.Italic = false;
ConsoleEx.Bold = false;
ConsoleEx.ForegroundColor = ConsoleColor.Gray;
Console.Write(":~");
Console.ForegroundColor = ConsoleColor.White;
ConsoleEx.Italic = true;
if (KernelWatchdog.InKernelMode == true)
Console.Write("#");
else
Console.Write("$");
ConsoleEx.Italic = false;
ConsoleEx.Bold = false;
ConsoleEx.ForegroundColor = SkinEngine.LoadedSkin.TerminalForeColorCC;
Console.Write(" ");
}
}
static TerminalBackend()
{
ServerMessageReceived onMessageReceived = (msg) =>
{
if (msg.Name == "trm_invokecommand")
{
string text3 = "";
string text4 = msg.Contents;
if (TerminalBackend.PrefixEnabled)
{
text3 = text4.Remove(0, $"{SaveSystem.CurrentSave.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ".Length);
}
IsForwardingConsoleWrites = true;
if (TerminalBackend.InStory == false)
{
TerminalBackend.InvokeCommand(text3, true);
}
if (TerminalBackend.PrefixEnabled)
{
Console.Write($"{SaveSystem.CurrentSave.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ");
}
IsForwardingConsoleWrites = false;
}
else if (msg.Name == "pleasewrite")
{
Console.Write(msg.Contents);
}
else if (msg.Name == "handshake_from")
{
var a = JsonConvert.DeserializeObject<Dictionary<string, object>>(msg.Contents);
string uName = a["username"] as string;
string pass = a["password"] as string;
string sys = a["sysname"] as string;
string guid = msg.GUID;
if (SaveSystem.CurrentSave.Username == uName && SaveSystem.CurrentSave.Password == pass && CurrentSave.SystemName == sys)
{
ForwardGUID = guid;
ServerManager.SendMessage("trm_handshake_accept", $@"{{
guid: ""{ServerManager.thisGuid}"",
target: ""{guid}""
}}");
IsForwardingConsoleWrites = true;
InvokeCommand("sos.status");
Console.Write($"{SaveSystem.CurrentSave.Username}@{SaveSystem.CurrentSave.SystemName}:~$ ");
IsForwardingConsoleWrites = false;
}
}
};
ServerManager.MessageReceived += onMessageReceived;
}
public static bool IsForwardingConsoleWrites { get; internal set; }
public static string ForwardGUID { get; internal set; }
public static event TextSentEventHandler TextSent;
public static void SendText(string text)
{
TextSent?.Invoke(text);
}
}
}

View file

@ -1,131 +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 System.IO;
using System.Windows.Forms;
namespace ShiftOS.Engine
{
public class TerminalTextWriter : TextWriter
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool LockWindowUpdate(IntPtr hWndLock);
public override Encoding Encoding
{
get
{
return Encoding.Unicode;
}
}
public ITerminalWidget UnderlyingControl
{
get
{
return AppearanceManager.ConsoleOut;
}
}
public void select()
{
Desktop.InvokeOnWorkerThread(new Action(() =>
{
UnderlyingControl?.SelectBottom();
}));
}
public override void Write(char value)
{
if (TerminalBackend.IsForwardingConsoleWrites)
{
ServerManager.SendMessage("write", $@"{{
guid: ""{TerminalBackend.ForwardGUID}"",
text: ""{value}""
}}");
}
else
{
Desktop.InvokeOnWorkerThread(new Action(() =>
{
UnderlyingControl?.Write(value.ToString());
select();
}));
}
}
public override void WriteLine(string value)
{
if (TerminalBackend.IsForwardingConsoleWrites)
{
ServerManager.SendMessage("write", $@"{{
guid: ""{TerminalBackend.ForwardGUID}"",
text: ""{value + Environment.NewLine}""
}}");
}
else
{
Desktop.InvokeOnWorkerThread(new Action(() =>
{
UnderlyingControl?.WriteLine(value);
select();
}));
}
}
public void SetLastText()
{
}
public override void Write(string value)
{
if (TerminalBackend.IsForwardingConsoleWrites)
{
ServerManager.SendMessage("write", $@"{{
guid: ""{TerminalBackend.ForwardGUID}"",
text: ""{value}""
}}");
}
else
{
Desktop.InvokeOnWorkerThread(new Action(() =>
{
UnderlyingControl?.Write(value.ToString());
select();
}));
}
}
}
}

View file

@ -1,135 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using ShiftOS.Objects;
namespace ShiftOS.Unite
{
public class UniteClient
{
public string Token { get; private set; }
public string BaseURL
{
get
{
return UserConfig.Get().UniteUrl;
}
}
public string GetDisplayNameId(string id)
{
return MakeCall("/API/GetDisplayName/" + id);
}
public PongHighscoreModel GetPongHighscores()
{
return JsonConvert.DeserializeObject<PongHighscoreModel>(MakeCall("/API/GetPongHighscores"));
}
public UniteClient(string baseurl, string usertoken)
{
//Handled by the servers.json file
//BaseURL = baseurl;
Token = usertoken;
}
internal string MakeCall(string url)
{
var webrequest = WebRequest.Create(BaseURL + url);
webrequest.Headers.Add("Authentication: Token " + Token);
using (var response = webrequest.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new System.IO.StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
public int GetPongCP()
{
return Convert.ToInt32(MakeCall("/API/GetPongCP"));
}
public int GetPongLevel()
{
return Convert.ToInt32(MakeCall("/API/GetPongLevel"));
}
public void SetPongLevel(int value)
{
MakeCall("/API/SetPongLevel/" + value.ToString());
}
public void SetPongCP(int value)
{
MakeCall("/API/SetPongCP/" + value.ToString());
}
public string GetEmail()
{
return MakeCall("/API/GetEmail");
}
public string GetSysName()
{
return MakeCall("/API/GetSysName");
}
public void SetSysName(string value)
{
MakeCall("/API/SetSysName/" + value);
}
public string GetDisplayName()
{
return MakeCall("/API/GetDisplayName");
}
public void SetDisplayName(string value)
{
MakeCall("/API/SetDisplayName/" + value.ToString());
}
public string GetFullName()
{
return MakeCall("/API/GetFullName");
}
public void SetFullName(string value)
{
MakeCall("/API/SetFullName/" + value.ToString());
}
public long GetCodepoints()
{
return Convert.ToInt64(MakeCall("/API/GetCodepoints"));
}
public void SetCodepoints(long value)
{
MakeCall("/API/SetCodepoints/" + value.ToString());
}
}
public class PongHighscoreModel
{
public int Pages { get; set; }
public PongHighscore[] Highscores { get; set; }
}
public class PongHighscore
{
public string UserId { get; set; }
public int Level { get; set; }
public long CodepointsCashout { get; set; }
}
}

View file

@ -1,201 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShiftOS.Objects;
namespace ShiftOS.Engine
{
[Namespace("admin")]
[KernelMode]
[RequiresUpgrade("mud_fundamentals")]
public static class AdminUserManagementCommands
{
[Command("add", description = "Add a user to the system.", usage ="name:")]
[RequiresArgument("name")]
public static bool AddUser(Dictionary<string, object> args)
{
string name = args["name"].ToString();
if(SaveSystem.CurrentSave.Users.FirstOrDefault(x=>x.Username==name) != null)
{
Console.WriteLine("Error: User already exists.");
return true;
}
var user = new ClientSave
{
Username = name,
Password = "",
Permissions = UserPermissions.User
};
SaveSystem.CurrentSave.Users.Add(user);
Console.WriteLine($"Creating new user \"{name}\" with no password and User permissions.");
SaveSystem.SaveGame();
return true;
}
[Command("remove", description = "Remove a user from the system.", usage = "name:")]
[RequiresArgument("name")]
public static bool RemoveUser(Dictionary<string, object> args)
{
string name = args["name"].ToString();
if (SaveSystem.CurrentSave.Users.FirstOrDefault(x => x.Username == name) == null)
{
Console.WriteLine("Error: User doesn't exist.");
return true;
}
var user = SaveSystem.CurrentSave.Users.FirstOrDefault(x => x.Username == name);
if(user.Username != SaveSystem.CurrentUser.Username)
{
Console.WriteLine("Error: Cannot remove yourself.");
return true;
}
SaveSystem.CurrentSave.Users.Remove(user);
Console.WriteLine($"Removing user \"{name}\" from system...");
SaveSystem.SaveGame();
return true;
}
[Command("set_acl")]
[RequiresArgument("user")]
[RequiresArgument("val")]
public static bool SetUserPermission(Dictionary<string, object> args)
{
int permission = 0;
string username = args["user"].ToString();
try
{
permission = Convert.ToInt32(args["val"].ToString());
}
catch
{
Console.WriteLine("Error: Permission value must be an integer.");
return true;
}
if(SaveSystem.CurrentSave.Users.FirstOrDefault(x=>x.Username==username) == null)
{
Console.WriteLine("Error: User not found.");
return true;
}
UserPermissions uperm = UserPermissions.Guest;
switch (permission)
{
case 0:
uperm = UserPermissions.Guest;
break;
case 1:
uperm = UserPermissions.User;
break;
case 2:
uperm = UserPermissions.Admin;
break;
case 3:
uperm = UserPermissions.Root;
break;
default:
Console.WriteLine("Permission value must be between 0 and 4.");
return true;
}
//Permissions are backwards... oops...
if(uperm < SaveSystem.CurrentUser.Permissions)
{
Console.WriteLine("Error: Cannot set user permissions to values greater than your own!");
return true;
}
var oldperm = SaveSystem.Users.FirstOrDefault(x => x.Username == username).Permissions;
if (SaveSystem.CurrentUser.Permissions > oldperm)
{
Console.WriteLine("Error: Can't set the permission of this user. They have more rights than you.");
return true;
}
SaveSystem.CurrentSave.Users.FirstOrDefault(x => x.Username == username).Permissions = uperm;
Console.WriteLine("User permissions updated.");
return true;
}
[Command("users", description = "Get a list of all users on the system.")]
public static bool GetUsers()
{
foreach (var u in SaveSystem.CurrentSave.Users)
{
if (u.Username == SaveSystem.CurrentUser.Username)
{
ConsoleEx.ForegroundColor = ConsoleColor.Magenta;
ConsoleEx.Bold = true;
}
else
{
ConsoleEx.ForegroundColor = ConsoleColor.Gray;
ConsoleEx.Bold = false;
}
Console.WriteLine(u.Username);
}
return true;
}
}
[Namespace("user")]
[RequiresUpgrade("mud_fundamentals")]
public static class UserManagementCommands
{
[Command("login", description = "Log in as another user.")]
[RequiresArgument("user")]
[RequiresArgument("pass")]
public static bool Login(Dictionary<string, object> args)
{
string user = args["user"].ToString();
string pass = args["pass"].ToString();
var usr = SaveSystem.CurrentSave.Users.FirstOrDefault(x => x.Username == user);
if(usr==null)
{
Console.WriteLine("Error: No such user.");
return true;
}
if (usr.Password != pass)
{
Console.WriteLine("Access denied.");
return true;
}
SaveSystem.CurrentUser = usr;
Console.WriteLine("Access granted.");
return true;
}
[Command("setpass", description ="Allows you to set your password to a new value.", usage ="old:,new:")]
[RequiresArgument("old")]
[RequiresArgument("new")]
public static bool SetPassword(Dictionary<string, object> args)
{
string old = args["old"].ToString();
string newpass = args["new"].ToString();
if(old == SaveSystem.CurrentUser.Password)
{
SaveSystem.CurrentUser.Password = newpass;
SaveSystem.CurrentSave.Users.FirstOrDefault(x => x.Username == SaveSystem.CurrentUser.Username).Password = newpass;
Console.WriteLine("Password set successfully.");
SaveSystem.SaveGame();
}
else
{
Console.WriteLine("Passwords do not match.");
}
return true;
}
}
}