private void lutBox_Click(object sender, EventArgs e) { if (lutLoadDialog.ShowDialog() == DialogResult.OK) { LockControls(); try { UIConsole.Log($"Selected {lutLoadDialog.FileName} for new LUT"); var ifile = Bitmap.FromFile(lutLoadDialog.FileName); if (ifile.Width != 256 || ifile.Height != 256) { throw new ArgumentException($"The image size should be 256x256 pixels. Got {ifile.Width}x{ifile.Height}"); } lutBmp = new Bitmap(ifile); lutBmp = lutBmp.ToFormat(System.Drawing.Imaging.PixelFormat.Format32bppPArgb, true); UIConsole.Log("New LUT loaded"); Monitor.Enter(lutLocker); LUTChanged = true; LUTLoaded = false; Monitor.Exit(lutLocker); ParametersChanged = true; } catch (Exception ex) { MessageBox.Show($"There was an error loading the file:{Environment.NewLine}{ex.Message}"); } UnlockControls(); } }
public static void HandleFile(string filename, GRBGenericHeader header) { string dir = Path.GetDirectoryName(filename); string ofilename = header.filename ?? Path.GetFileName(filename); if (Tools.IsXML(filename)) { ofilename = ofilename.Replace(".grb", ".xml"); } string productFolder = Products.GetFolderByAPID(header.apid); string f = Path.Combine(FileHandler.FinalFileFolder, productFolder); try { Directory.CreateDirectory(f); } catch (IOException e) { UIConsole.Error($"Cannot create directory {f}: {e}"); } f = Path.Combine(f, ofilename); if (File.Exists(f)) { string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff"); string ext = Path.GetExtension(f); string append = $"--dup-{timestamp}{ext}"; f = f.Replace(ext, append); } try { File.Move(filename, f); } catch (IOException e) { UIConsole.Error($"Error moving file {filename} to {f}: {e}"); } }
private void DisplayDirectoriesLargerThan(string[] parts) { if (parts.Length < 2) { UIConsole.WriteLine("Invalid parameters for 'greater'. (greater [size] [b/kb/mb/gb])"); return; } long value; if (!long.TryParse(parts[1], out value)) { UIConsole.WriteLine("Invalid input. Should be \"greater [size] [b/kb/mb/gb]\""); return; } Size size; if (parts.Length < 4) { // Default to GB size = Size.GigaBytes(value); } else { var inputParts = string.Join(" ", parts.Skip(1).Take(2)); if (!Size.TryParse(inputParts, out size)) { UIConsole.WriteLine("Invalid input. Should be \"greater [size] [b/kb/mb/gb]\""); return; } } _controller.DirectoriesLargerThan(size); }
private string GetInput() { var availableDrives = string.Join(",", _controller.AvailableDrives()); UIConsole.Write($"Which drive do you want to read ({availableDrives}): "); return(UIConsole.ReadLine()); }
void ThreadLoop() { UIConsole.Debug("File Handler started"); while (running) { Tuple <string, object> fileToHandle; if (packets.TryDequeue(out fileToHandle)) { string filename = fileToHandle.Item1; object obj = fileToHandle.Item2; if (obj.GetType() == typeof(GRBImageHeader)) { HandleImage(filename, (GRBImageHeader)obj); } else if (obj.GetType() == typeof(GRBGenericHeader)) { HandleGeneric(filename, (GRBGenericHeader)obj); } else { UIConsole.Error($"Invalid Type: {obj.GetType().Name}"); } } // Thread.Yield(); // This might be better Thread.Sleep(5); } UIConsole.Debug("File Handler stopped"); }
/// <summary> /// Called at first-time load, loads required resources. /// </summary> /// <param name="sender">The sending object</param> /// <param name="e">The empty event args object</param> static void Window_Load(object sender, EventArgs e) { SysConsole.Output(OutputType.INIT, "Loading texture engine..."); Texture.InitTextureSystem(); SysConsole.Output(OutputType.INIT, "Loading shader engine..."); Shader.InitShaderSystem(); SysConsole.Output(OutputType.INIT, "Loading text engine..."); GLFont.Init(); SysConsole.Output(OutputType.INIT, "Loading font-set engine..."); FontSet.Init(); SysConsole.Output(OutputType.INIT, "Loading 3D model engine..."); Model.Init(); SysConsole.Output(OutputType.INIT, "Loading rendering helper engine..."); Renderer.Init(); SysConsole.Output(OutputType.INIT, "Adjusting OpenGL settings..."); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.Blend); GL.Enable(EnableCap.Texture2D); GL.Viewport(0, 0, Window.Width, Window.Height); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Front); SysConsole.Output(OutputType.INIT, "Loading material->texture map..."); MaterialTexture.Init(); SysConsole.Output(OutputType.INIT, "Loading keyboard handling engine..."); KeyHandler.Init(); SysConsole.Output(OutputType.INIT, "Loading interactive console engine..."); UIConsole.InitConsole(); SysConsole.Output(OutputType.INIT, "Loading world..."); InitWorld(); SysConsole.Output(OutputType.INIT, "Displaying window..."); }
/// <summary> /// Retrieves the user's information (nation name, email, ...) from the configuration file. If said file /// doesn't exist or doesn't contain that information, ask the user and store the response in the config file. /// </summary> public static string GetUserInfo() { // Open file, or create if it doesn't exist yet using (var file = File.Open(ConfigPath, FileMode.OpenOrCreate, FileAccess.Read)) { // Read configuration using var reader = new StreamReader(file, Encoding.UTF8); var config = reader.ReadToEnd(); var configLines = config.Split("\n"); var userInfo = ""; foreach (var line in configLines) { if (line.Contains(UserInfo)) { userInfo = line.Replace($"{UserInfo}: ", ""); break; } } // Return user info if it was present. if (userInfo.Length > 0) { return(userInfo); } } // If no user info present (didn't return), ask the user, and save it to the config file using (var fileWrite = File.Open(ConfigPath, FileMode.Append, FileAccess.Write)) { using var writer = new StreamWriter(fileWrite, Encoding.UTF8); var userInfo = UIConsole.GetUserInfo(); writer.WriteAsync($"{UserInfo}: {userInfo}\n"); return(userInfo); } }
/// <summary> Entry point for the console application </summary> private static async Task Main(string[] args) { var version = GetVersion(); // Greeting UIConsole.Show($"Kronos, at your service.\n{version}\n"); var lu = LatestUpdate(); if (!lu.Equals(version)) { UIConsole.Show( $"The latest release of Kronos is {lu}. You can find it here: https://github.com/Krypton-Nova/Kronos/releases \n"); } // Read settings var unusedUserAgent = Shared.UserAgent; var unusedUserTags = Shared.UserTags; // Run until Quit command is given. while (true) { // Pass initial options to Program, or request user input var commands = UIConsole.UserCommandInput(args); // Run commands sequentially foreach (var command in commands) { await command.Run(); } // Reset initial options args = new string[0]; } }
public SingleplayerMenuScreen(Client tclient) : base(tclient) { ResetOnRender = false; AddChild(new UIButton("ui/menus/buttons/basic", "Back", TheClient.FontSets.SlightlyBigger, () => TheClient.ShowMainMenu(), UIAnchor.BOTTOM_LEFT, () => 350, () => 70, () => 10, () => - 100)); int start = 150; IEnumerable <string> found = Directory.EnumerateDirectories(Environment.CurrentDirectory); HashSet <string> fullList = new HashSet <string>(); foreach (string fnd in found) { string str = fnd.Substring(Environment.CurrentDirectory.Length).Replace('\\', '/').Replace("/", ""); fullList.Add(str); } fullList.Add("server_default"); fullList.Remove("server_menu"); foreach (string fnd in fullList) { string str = fnd; int curr = start; if (str.StartsWith("server_")) { str = str.Substring("server_".Length); AddChild(new UIButton("ui/menus/buttons/sp", "== " + str + " ==", TheClient.FontSets.Standard, () => { UIConsole.WriteLine("Opening singleplayer game: " + str); TheClient.Network.Disconnect(TheClient.Network.ConnectionThread, TheClient.Network.ConnectionSocket, TheClient.Network.ChunkSocket); if (TheClient.LocalServer != null) { UIConsole.WriteLine("Shutting down pre-existing server."); TheClient.LocalServer.ShutDown(); TheClient.LocalServer = null; } TheClient.LocalServer = new Server(28010); Server.Central = TheClient.LocalServer; TheClient.ShowLoading(); TheClient.Schedule.StartAsyncTask(() => { try { TheClient.LocalServer.StartUp(str, () => { TheClient.Schedule.ScheduleSyncTask(() => { TheClient.Network.Connect("localhost", "28010", false, str); }, 1.0); }); } catch (Exception ex) { Utilities.CheckException(ex); SysConsole.Output("Running singleplayer game server", ex); } }); }, UIAnchor.TOP_LEFT, () => 600, () => 70, () => 10, () => curr)); start += 100; } } AddChild(new UILabel("^!^e^0 Voxalia\nSingleplayer", TheClient.FontSets.SlightlyBigger, UIAnchor.TOP_CENTER, () => 0, () => 0)); }
/// <summary> Quit Kronos </summary> public async Task Run() { UIConsole.Show( $"Kronos downloaded {Math.Ceiling(Shared.BytesDownloaded / 1000.0):0} KiB of data in total.\n"); UIConsole.Show("Goodbye!\n"); await Task.Delay(100); Environment.Exit(0); }
private void ReadDrive(string[] parts) { if (parts.Length < 2) { UIConsole.WriteLine("Invalid parameters for 'read'. (read [drive letter])"); return; } _controller.ReadDrive(parts[1].ToLower()[0]); }
/// <summary> /// Connects to a server. /// </summary> /// <param name="host">The hostname to connect to</param> /// <param name="port">The port on the host to connect to</param> public static void Connect(string host, string port) { Disconnect(); CurrentHost = host; CurrentPort = Utilities.StringToUShort(port); ConnectionThread = new Thread(new ThreadStart(ConnectInternal)); UIConsole.WriteLine("^r^7Connected to " + host + "^r^7:" + port); ConnectionThread.Start(); }
void OnDisable() { if (instance == this) { instance = null; } Application.logMessageReceived -= HandleLog; }
public void AddMetadataFrom(GrbData grbData) { Metadata = grbData.Metadata; try { ParseMetadataFromText(Metadata); } catch (Exception e) { UIConsole.Error($"Error parsing metadata: {e.Message}"); } }
public void Write(string text) { UIConsole?.Print(text); if (!startedPrinting) { startedPrinting = true; } LastOutput = text; }
public DirectoryController(ILog log, ISizeConversion sizeConversion) { _log = log; _sizeConversion = sizeConversion; // TODO - have one handler and just fill it with necessary commands _driveReaderCommandHandler = new DriveReaderCommandHandler(this); _currentCommandHandler = new DriveLetterCommandHandler(this); _view = new DirectoryView(); UIConsole.SetTitle("Directory Sizes Tool"); }
private void ThreadLoop() { UIConsole.Log("MultiImage Thread running."); while (running) { imageManagers.ForEach(ManageImageManager); Thread.Sleep(2); } UIConsole.Log("MultiImage Thread stopped."); }
public static void HandleFile(string filename, GRBImageHeader header) { string dir = Path.GetDirectoryName(filename); string ofilename = header.filename ?? Path.GetFileName(filename); // Separate DQF string dqfFilename = $"{filename}.dqf"; try { byte[] buffer = File.ReadAllBytes(filename); buffer = buffer.Skip((int)header.dqfOffset).ToArray(); File.WriteAllBytes(dqfFilename, buffer); } catch (Exception) { } string productFolder = Products.GetFolderByAPID(header.apid); string bPath = productFolder; string zPath = Path.Combine(bPath, $"{header.epoch:D16}", $"{header.sequence:D8}"); string f = Path.Combine(FileHandler.FinalFileFolder, zPath); try { Directory.CreateDirectory(Path.Combine(FileHandler.FinalFileFolder, bPath, $"{header.epoch:D16}")); } catch (IOException e) { UIConsole.Error($"Cannot create directory {bPath}: {e}"); } if (!ImageCache.ContainsKey(zPath)) { ImageCache.Add(zPath, new ImageAssembler((int)header.width, (int)header.height)); DQFCache.Add(zPath, new ImageAssembler((int)header.width, (int)header.height)); } ImageCache[zPath].AppendJ2K(filename); DQFCache[zPath].AppendJ2K(dqfFilename); try { File.Delete(filename); File.Delete(dqfFilename); } catch (IOException e) { UIConsole.Error($"Error erasing file {filename}: {e}"); } if (ImageCache[zPath].Done) { // UIConsole.Log ($"New image at {f}"); // ImageCache [zPath].SavePGM ($"{f}.pgm"); // ImageCache [zPath].SaveJPG ($"{f}.jpg"); // File.WriteAllText($"{f}.txt", header.ToString()); ProcessBigImage(bPath, ImageCache[zPath], header); ImageCache.Remove(zPath); // FIXME: Discarding DQF // DQFCache[zPath].SavePGM($"{f}.dqf.pgm"); DQFCache.Remove(zPath); } }
/// <summary> /// Stores plain data /// </summary> /// <param name="filename">Filename.</param> /// <param name="header">Header.</param> public void ParseData(string filename, GRBGenericHeader header) { lock (syncLock) { try { Data = File.ReadAllBytes(filename); } catch (Exception e) { UIConsole.Error($"Error parsing data file {filename}: {e.Message}"); UIConsole.Debug($"{e}"); } } }
/// <summary> /// Generates the land map using GeoConverter /// </summary> /// <returns>The land map.</returns> /// <param name="gc">Gc.</param> /// <param name="width">Width.</param> /// <param name="height">Height.</param> /// <param name="fixCrop">If set to <c>true</c> fix crop.</param> public Bitmap GenerateLandMap(GeoConverter gc, int width, int height, bool fixCrop = false) { if (shapeFile == null) { UIConsole.Error("Trying to draw a LandMap without a loaded shapefile!"); return(null); } var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb); Brush bgBrush = new SolidBrush(Color.Black); Brush polyBrush = new SolidBrush(Color.White); using (var graphics = Graphics.FromImage(bmp)) { graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.FillRectangle(bgBrush, 0, 0, width, height); lock (shapeFile) { // TODO: This is BAD, SO BAD, PLEASE FIX ME // Thats because for some reason running this in multiple // threads is causing Features to be modified (wtf?) foreach (var f in shapeFile.Features.ToList()) { for (int i = 0; i < f.NumGeometries; i++) { var geom = f.GetBasicGeometryN(i); var k = geom.Coordinates; var points = new List <PointF> (); foreach (var z in k) { float lon = (float)z.X; float lat = (float)z.Y; var xy = gc.latlon2xy(lat, lon); float cx = (float)xy.Item1; float cy = (float)xy.Item2; if (fixCrop) { cx -= gc.CropLeft; } points.Add(new PointF(cx, cy)); } // Search if any of the points are inside the image foreach (var p in points) { if (p.X >= 0 && p.X < bmp.Width && p.Y >= 0 && p.Y < bmp.Height) { graphics.FillPolygon(polyBrush, points.ToArray()); break; } } } } } } return(bmp); }
public MapDrawer(string shapeFile) { this.shapeFile = null; UIConsole.Debug($"MapDrawer -- Loading ShapeFile {shapeFile}"); try { this.shapeFile = Shapefile.OpenFile(shapeFile); UIConsole.Debug("MapDrawer -- ShapeFile Loaded at MapDrawer"); } catch (Exception e) { UIConsole.Error($"MapDrawer -- Cannot load ShapeFile at {shapeFile}: {e}"); } }
public async Task <T> LoadUIAsync <T>() where T : class { string path = UIPath.GetPath <T>(); GameObject go = await Addressables.LoadAssetAsync <GameObject>(path).Task; go = MonoBehaviour.Instantiate(go); UIConsole.InsertUI(go.transform); T ui = go.GetComponent <T>(); UIs.Add(typeof(T), go); return(ui); }
private void ChangeDirectory(IEnumerable <string> name) { if (!name.Any()) { UIConsole.WriteLine("Invalid parameters for 'cd'. (cd [subdirectory name])"); return; } var directoryName = string.Join(" ", name); _controller.ChangeDirectory(directoryName); }
/// <summary> /// Disconnects any active connection. /// </summary> public static void Disconnect() { bool HadToDisco = false; try { if (ConnectionThread != null && ConnectionThread.IsAlive) { HadToDisco = true; ConnectionThread.Abort(); } } catch (Exception ex) { if (ex is ThreadAbortException) { throw ex; } SysConsole.Output(OutputType.ERROR, "Network / Disconnect / ThreadClose: " + ex.ToString()); } try { if (Connection != null) { if (Connection.Connected && Connected) { // TODO: Send disconnect packet within a try/catch. } HadToDisco = true; Connection.Close(5); } if (ChunkConnection != null) { HadToDisco = true; Connection.Close(5); } } catch (Exception ex) { if (ex is ThreadAbortException) { throw ex; } SysConsole.Output(OutputType.ERROR, "Network / Disconnect / SocketClose: " + ex.ToString()); } ConnectionThread = null; Connection = null; Connected = false; if (HadToDisco) { UIConsole.WriteLine("^3Disconnected from server."); } }
/// <summary> /// Parses a metadata file /// </summary> /// <param name="filename">Filename.</param> public void ParseMetadata(string filename) { lock (syncLock) { try { Metadata = File.ReadAllText(filename); ParseMetadataFromText(Metadata); } catch (Exception e) { UIConsole.Error($"Error parsing metadata file {filename}: {e.Message}"); // UIConsole.Debug($"{e}"); } } }
private void Awake() { if (!Instance) { Instance = this; } else { Destroy(this); } _scrollrect = GetComponentInParent <ScrollRect>(); }
void OnEnable() { if (instance == null) { instance = this; } else { gameObject.SetActive(false); } Application.logMessageReceived += HandleLog; }
public void NewFile(Tuple <string, object> file) { if (running) { if (packets.Count >= MAX_QUEUE_LENGTH) { Tuple <string, object> f; UIConsole.Warn("File Handler Queue is full!!!! Files might be discarded!"); packets.TryDequeue(out f); } packets.Enqueue(file); } }
public void FinishMSDU(OpenSatelliteProject.GRB.MSDU msdu) { if (running) { if (packets.Count >= MAX_QUEUE_LENGTH) { OpenSatelliteProject.GRB.MSDU lmsdu; UIConsole.Warn("MSDU Manager Queue is full!!!! Some MSDU might be discarded!"); packets.TryDequeue(out lmsdu); } packets.Enqueue(msdu); } }
public void Stop() { if (running) { UIConsole.Log("Stopping Thread"); running = false; channelThread.Join(); } else { UIConsole.Error("MSDU Manager already stopped!"); } }