public static bool SendToEDDN(HistoryEntry he) { EDDNClass eddn = new EDDNClass(); JournalEntry je = JournalEntry.Get(he.Journalid); JObject msg = null; if (je.EventTypeID == JournalTypeEnum.FSDJump) { msg = eddn.CreateEDDNMessage(je as JournalFSDJump); } else if (je.EventTypeID == JournalTypeEnum.Docked) { msg = eddn.CreateEDDNMessage(je as JournalDocked, he.System.x, he.System.y, he.System.z); } else if (je.EventTypeID == JournalTypeEnum.Scan) { msg = eddn.CreateEDDNMessage(je as JournalScan, he.System.name, he.System.x, he.System.y, he.System.z); } if (msg != null) { if (eddn.PostMessage(msg)) return true; } return false; }
public void AddToTable(HistoryEntry historyEntry) { int premature = 0; int idle = 0; int working = 0; int retired = 0; int dead = 0; historyEntry.totalCitizenStates.TryGetValue(CitizenState.Premature, out premature); historyEntry.totalCitizenStates.TryGetValue(CitizenState.Idle, out idle); historyEntry.totalCitizenStates.TryGetValue(CitizenState.Working, out working); historyEntry.totalCitizenStates.TryGetValue(CitizenState.Retired, out retired); historyEntry.totalCitizenStates.TryGetValue(CitizenState.Dead, out dead); ListViewItem lvi = new ListViewItem(new string[] { id.ToString(), historyEntry.livingCitizens.ToString(), premature.ToString(), idle.ToString(), working.ToString(), retired.ToString(), dead.ToString(), historyEntry.totalCitizens.ToString(), historyEntry.totalPaid.ToString(), historyEntry.totalGet.ToString(), historyEntry.totalCash.ToString(), }); Invoke(new Action(() => lvHistoryTable.Items.Add(lvi))); id++; }
public void Data_age_filter_removes_data_older_than_the_limit_and_keeps_data_more_recent_than_the_limit() { var now = new HistoryEntry { EventTimeUTC = DateTime.UtcNow }; var fourDaysAgo = new HistoryEntry { EventTimeUTC = DateTime.UtcNow.Subtract(TimeSpan.FromDays(4))}; var input = new HistoryList { fourDaysAgo, now }; Check.That(TravelHistoryFilter.FromDays(2).Filter(input)).ContainsExactly(now); }
public void Last_2_items_filter_returns_the_2_most_recent_items_sorted_by_most_recent_and_removes_the_older_items() { var twentyDaysAgo = new HistoryEntry { EventTimeUTC = DateTime.UtcNow.Subtract(TimeSpan.FromDays(20)) }; var tenDaysAgo = new HistoryEntry { EventTimeUTC = DateTime.UtcNow.Subtract(TimeSpan.FromDays(10)) }; var thirtyDaysAgo = new HistoryEntry { EventTimeUTC = DateTime.UtcNow.Subtract(TimeSpan.FromDays(30)) }; var input = new HistoryList { twentyDaysAgo, tenDaysAgo, thirtyDaysAgo }; Check.That(TravelHistoryFilter.Last(2).Filter(input)).ContainsExactly(tenDaysAgo, twentyDaysAgo); }
// when user clicks around.. public void Display(HistoryEntry he, HistoryList hl) { StarScan.SystemNode newnode = (he != null) ? hl.starscan.FindSystem(he.System) : null; if (newnode != last_sn) { last_sn = newnode; DrawSystem(last_sn); } }
// (verified with EDSM 29/9/2016, seen UTC time being sent, and same UTC time on ESDM). public static bool SendEDDNEvent(HistoryEntry he) { Task taskEDSM = Task.Factory.StartNew(() => { // LOCAL time, there is a UTC converter inside this call if (SendToEDDN(he)) he.SetEddnSync(); }); return true; }
public static RemotingPackageManifestEntry FromEntry(HistoryEntry entry, string databaseName) { var manifest = new RemotingPackageManifestEntry(); manifest.Action = entry.Action; manifest.ItemId = entry.ItemId.Guid; manifest.ItemPath = entry.ItemPath; manifest.Database = databaseName; return manifest; }
// (verified with EDSM 29/9/2016, seen UTC time being sent, and same UTC time on ESDM). public static void SendTravelLog(HistoryEntry he) { EDSMClass edsm = new EDSMClass(); if (!edsm.IsApiKeySet) return; string errmsg; Task taskEDSM = Task.Factory.StartNew(() => { // LOCAL time, there is a UTC converter inside this call if (edsm.SendTravelLog(he.System.name, he.EventTimeUTC, he.System.HasCoordinate, he.System.x, he.System.y, he.System.z, out errmsg)) he.SetEdsmSync(); }); }
// (verified with EDSM 29/9/2016, seen UTC time being sent, and same UTC time on ESDM). public static void SendTravelLog(HistoryEntry he) { if (!EDDConfig.Instance.CheckCommanderEDSMAPI) return; EDSMClass edsm = new EDSMClass(); string errmsg; Task taskEDSM = Task.Factory.StartNew(() => { // LOCAL time, there is a UTC converter inside this call if (edsm.SendTravelLog(he.System.name, he.EventTimeUTC, he.System.HasCoordinate, he.System.x, he.System.y, he.System.z, out errmsg)) he.SetEdsmSync(); }); }
internal void Add(string text) { var entry = new HistoryEntry { Text = text }; _live = false; if (Length == 0 || Last.Text != text) { _history.Add(entry); } if (_history[InternalPosition].Text != text) { _pos = -1; } if (Length > MaxLength) { _history.RemoveAt(0); if (_pos > 0) { _pos--; } } }
private void AddNewEntry(HistoryEntry he, HistoryList hl) { Stats(he,hl); }
public void Display(HistoryEntry he, HistoryList hl) { Display(he?.MaterialCommodity.Sort(!materials)); }
void DrawHistoryEntry(HistoryEntry he, int rowpos, Point3D tpos , Color textcolour , Color backcolour ) { List<string> coldata = new List<string>(); // First we accumulate the strings List<int> tooltipattach = new List<int>(); if (Config(Configuration.showTime)) coldata.Add((EDDiscoveryForm.EDDConfig.DisplayUTC ? he.EventTimeUTC : he.EventTimeLocal).ToString("HH:mm.ss")); if (Config(Configuration.showDescription)) { tooltipattach.Add(coldata.Count); coldata.Add(he.EventSummary.Replace("\r\n", " ")); } if (Config(Configuration.showInformation)) { tooltipattach.Add(coldata.Count); coldata.Add(he.EventDescription.Replace("\r\n", " ")); } if (layoutorder == 0 && Config(Configuration.showNotes)) { SystemNoteClass snc = SystemNoteClass.GetNoteOnJournalEntry(he.Journalid); if (snc == null && he.IsFSDJump) snc = SystemNoteClass.GetNoteOnSystem(he.System.name, he.System.id_edsm); coldata.Add((snc != null) ? snc.Note.Replace("\r\n", " ") : ""); } bool showdistance = !Config(Configuration.showDistancesOnFSDJumpsOnly) || he.IsFSDJump; if (layoutorder == 2 && Config(Configuration.showDistancePerStar)) coldata.Add(showdistance ? DistToStar(he, tpos) : ""); if (Config(Configuration.showXYZ)) { coldata.Add((he.System.HasCoordinate && showdistance) ? he.System.x.ToString("0.00") : ""); coldata.Add((he.System.HasCoordinate && showdistance) ? he.System.y.ToString("0.00") : ""); coldata.Add((he.System.HasCoordinate && showdistance) ? he.System.z.ToString("0.00") : ""); } if (layoutorder > 0 && Config(Configuration.showNotes)) { SystemNoteClass snc = SystemNoteClass.GetNoteOnJournalEntry(he.Journalid); if (snc == null && he.IsFSDJump) snc = SystemNoteClass.GetNoteOnSystem(he.System.name, he.System.id_edsm); coldata.Add((snc != null) ? snc.Note.Replace("\r\n", " ") : ""); } if (layoutorder < 2 && Config(Configuration.showDistancePerStar)) coldata.Add(showdistance ? DistToStar(he, tpos) : ""); int colnum = 0; if (Config(Configuration.showEDSMButton)) { Image edsm = EDDiscovery.Properties.Resources.edsm; pictureBox.AddImage(new Rectangle(scanpostextoffset.X+columnpos[colnum++], rowpos, edsm.Width, edsm.Height), edsm, he, "Click to view information on EDSM"); } string tooltip = he.EventSummary + Environment.NewLine + he.EventDescription + Environment.NewLine + he.EventDetailedInfo; for (int i = 0; i < coldata.Count; i++) // then we draw them, allowing them to overfill columns if required { int nextfull = i+1; for (; nextfull < coldata.Count && Config(Configuration.showExpandOverColumns) && coldata[nextfull].Length == 0; nextfull++) { } AddColText(colnum + i, colnum + nextfull , rowpos, coldata[i], textcolour, backcolour, tooltipattach.Contains(i) ? tooltip : null); } }
private void dataGridViewJournal_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) // right click on travel map, get in before the context menu { rightclicksystem = null; rightclickrow = -1; } if (e.Button == MouseButtons.Left) // right click on travel map, get in before the context menu { leftclicksystem = null; leftclickrow = -1; } if (dataGridViewJournal.SelectedCells.Count < 2 || dataGridViewJournal.SelectedRows.Count == 1) // if single row completely selected, or 1 cell or less.. { DataGridView.HitTestInfo hti = dataGridViewJournal.HitTest(e.X, e.Y); if (hti.Type == DataGridViewHitTestType.Cell) { dataGridViewJournal.ClearSelection(); // select row under cursor. dataGridViewJournal.Rows[hti.RowIndex].Selected = true; if (e.Button == MouseButtons.Right) // right click on travel map, get in before the context menu { rightclickrow = hti.RowIndex; rightclicksystem = (HistoryEntry)dataGridViewJournal.Rows[hti.RowIndex].Cells[JournalHistoryColumns.HistoryTag].Tag; } if (e.Button == MouseButtons.Left) // right click on travel map, get in before the context menu { leftclickrow = hti.RowIndex; leftclicksystem = (HistoryEntry)dataGridViewJournal.Rows[hti.RowIndex].Cells[JournalHistoryColumns.HistoryTag].Tag; } } } }
private void UpdateSystemRow(int rowindex) { const int idxVisits = 5; const int idxScans = 6; const int idxPriStar = 7; const int idxInfo = 8; const int idxNote = 9; if (hl == null) { hl = discoveryform.history; } HistoryEntry last = hl.GetLast; if (last == null) { return; } ISystem currentSystem = last.System; if (rowindex < dataGridViewExplore.Rows.Count && dataGridViewExplore[0, rowindex].Value != null) { string sysname = dataGridViewExplore[0, rowindex].Value.ToString(); ISystem sys = (ISystem)dataGridViewExplore[0, rowindex].Tag; if (sys == null) { sys = GetSystem(sysname); } if (sys != null && currentSystem != null) { double dist = sys.Distance(currentSystem); string strdist = dist >= 0 ? ((double)dist).ToString("0.00") : ""; dataGridViewExplore[1, rowindex].Value = strdist; } dataGridViewExplore[0, rowindex].Tag = sys; dataGridViewExplore.Rows[rowindex].DefaultCellStyle.ForeColor = (sys != null && sys.HasCoordinate) ? discoveryform.theme.VisitedSystemColor : discoveryform.theme.NonVisitedSystemColor; if (sys != null) { if (sys.HasCoordinate) { dataGridViewExplore[2, rowindex].Value = sys.X.ToString("0.00"); dataGridViewExplore[3, rowindex].Value = sys.Y.ToString("0.00"); dataGridViewExplore[4, rowindex].Value = sys.Z.ToString("0.00"); } dataGridViewExplore[idxVisits, rowindex].Value = hl.GetVisitsCount(sysname).ToString(); List <JournalScan> scans = hl.GetScans(sysname); dataGridViewExplore[idxScans, rowindex].Value = scans.Count.ToString(); string pristar = ""; // Search for primary star foreach (var scan in scans) { if (scan.IsStar && scan.DistanceFromArrivalLS == 0.0) { pristar = scan.StarType; break; } } dataGridViewExplore[idxPriStar, rowindex].Value = pristar; string info = ""; foreach (var scan in scans) { if (scan.IsStar) { if (scan.StarTypeID == EDStar.AeBe) { info = info + " " + "AeBe"; } if (scan.StarTypeID == EDStar.N) { info = info + " " + "NS"; } if (scan.StarTypeID == EDStar.H) { info = info + " " + "BH"; } } else { if (scan.PlanetTypeID == EDPlanet.Earthlike_body) { info = info + " " + "ELW"; } if (scan.PlanetTypeID == EDPlanet.Water_world) { info = info + " " + "WW"; } } } dataGridViewExplore[idxInfo, rowindex].Value = info.Trim(); string note = ""; SystemNoteClass sn = SystemNoteClass.GetNoteOnSystem(sys.Name, sys.EDSMID); if (sn != null && !string.IsNullOrWhiteSpace(sn.Note)) { note = sn.Note; } else { BookmarkClass bkmark = BookmarkClass.bookmarks.Find(x => x.StarName != null && x.StarName.Equals(sys.Name)); if (bkmark != null && !string.IsNullOrWhiteSpace(bkmark.Note)) { note = bkmark.Note; } else { var gmo = discoveryform.galacticMapping.Find(sys.Name); if (gmo != null && !string.IsNullOrWhiteSpace(gmo.description)) { note = gmo.description; } } } dataGridViewExplore[idxNote, rowindex].Value = note.WordWrap(60); } if (sys == null && sysname != "") { dataGridViewExplore.Rows[rowindex].ErrorText = "System not known"; } else { dataGridViewExplore.Rows[rowindex].ErrorText = ""; } } }
private void Sync(EDSMClass edsm, HistoryList hl) { try { // Make sure the EDSM class has this history's commander set int cmdrid = hl.CommanderId; EDCommander cmdr = EDCommander.GetCommander(cmdrid); if (cmdr != null) { edsm.commanderName = cmdr.EdsmName ?? cmdr.Name; edsm.apiKey = cmdr.APIKey; } logout("EDSM sync begin"); List <HistoryEntry> hlfsdunsyncedlist = hl.FilterByNotEDSMSyncedAndFSD; // first entry is oldest if (_syncTo && hlfsdunsyncedlist.Count > 0) // send systems to edsm (verified with dates, 29/9/2016, utc throughout) { DateTime logstarttime = DateTime.MinValue; DateTime logendtime = DateTime.MinValue; logout("EDSM: Sending " + hlfsdunsyncedlist.Count.ToString() + " flightlog entries"); List <HistoryEntry> edsmsystemlog = null; int edsmsystemssent = 0; foreach (var he in hlfsdunsyncedlist) { if (Exit) { running = false; return; } if (edsmsystemlog == null || he.EventTimeUTC >= logendtime.AddDays(-1)) { edsm.GetLogs(he.EventTimeUTC.AddDays(-1), null, out edsmsystemlog, out logstarttime, out logendtime); // always returns a log, time is in UTC as per HistoryEntry and JournalEntry } if (logendtime < logstarttime) { running = false; return; } if (edsmsystemlog == null) { running = false; return; } HistoryEntry ps2 = (from c in edsmsystemlog where c.System.name == he.System.name && c.EventTimeUTC.Ticks == he.EventTimeUTC.Ticks select c).FirstOrDefault(); if (ps2 != null) // it did, just make sure EDSM sync flag is set.. { he.SetEdsmSync(); } else { string errmsg; // (verified with EDSM 29/9/2016) int errno; bool firstdiscover; int edsmid; if (edsm.SendTravelLog(he.System.name, he.EventTimeUTC, he.System.HasCoordinate && !he.IsStarPosFromEDSM, he.System.x, he.System.y, he.System.z, out errmsg, out errno, out firstdiscover, out edsmid)) { if (edsmid != 0 && he.System.id_edsm <= 0) { he.System.id_edsm = edsmid; JournalEntry.UpdateEDSMIDPosJump(he.Journalid, he.System, false, -1); } if (firstdiscover) { he.SetFirstDiscover(); } he.SetEdsmSync(); edsmsystemssent++; } if (errmsg.Length > 0) { logout(errmsg); if (errno != 303 && errno != 304) // Skip the system if EDSM rejects the system { break; } } } } logout(string.Format("EDSM Systems sent {0}", edsmsystemssent)); } // TBD Comments to edsm? if (_syncFrom) // Verified ok with time 29/9/2016 { var json = edsm.GetComments(new DateTime(2011, 1, 1)); if (json != null) { JObject msg = JObject.Parse(json); int msgnr = msg["msgnum"].Value <int>(); JArray comments = (JArray)msg["comments"]; if (comments != null) { int commentsadded = 0; foreach (JObject jo in comments) { string name = jo["system"].Value <string>(); string note = jo["comment"].Value <string>(); string utctime = jo["lastUpdate"].Value <string>(); int edsmid = 0; if (!Int32.TryParse(jo["systemId"].Str("0"), out edsmid)) { edsmid = 0; } DateTime localtime = DateTime.ParseExact(utctime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToLocalTime(); SystemNoteClass curnote = SystemNoteClass.GetNoteOnSystem(name, edsmid); if (curnote != null) // curnote uses local time to store { if (localtime.Ticks > curnote.Time.Ticks) // if newer, add on (verified with EDSM 29/9/2016) { curnote.UpdateNote(curnote.Note + ". EDSM: " + note, true, localtime, edsmid, true); commentsadded++; } } else { SystemNoteClass.MakeSystemNote(note, localtime, name, 0, edsmid, true); // new one! its an FSD one as well commentsadded++; } } logout(string.Format("EDSM Comments downloaded/updated {0}", commentsadded)); } } } logout("EDSM sync Done"); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message); logout("EDSM sync Exception " + ex.Message); } }
private void Uctg_OnTravelSelectionChanged(HistoryEntry he, HistoryList hl, bool selectedEntry) { Display(he); }
private static void SyncThread() { running = 1; //mainForm.LogLine("Starting EDDN sync thread"); while (hlscanunsyncedlist.Count != 0) { HistoryEntry he = null; int eventcount = 0; while (hlscanunsyncedlist.TryDequeue(out he)) { try { hlscanevent.Reset(); TimeSpan age = he.AgeOfEntry(); if (age.Days >= 1 && he.EntryType != EliteDangerousCore.JournalTypeEnum.Scan) { System.Diagnostics.Debug.WriteLine("EDDN: Ignoring entry due to age"); } else { bool?res = EDDNSync.SendToEDDN(he); if (res != null) // if attempted to send { if (res.Value == true) { logger?.Invoke($"Sent {he.EntryType.ToString()} event to EDDN ({he.EventSummary})"); eventcount++; } else { logger?.Invoke($"Failed sending {he.EntryType.ToString()} event to EDDN ({he.EventSummary})"); } } else { continue; // skip the 1 second delay if nothing was sent } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message); System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.StackTrace); logger?.Invoke("EDDN sync Exception " + ex.Message + Environment.NewLine + ex.StackTrace); } if (Exit) { running = 0; return; } Thread.Sleep(1000); // Throttling to 1 per second to not kill EDDN network } SentEvents?.Invoke(eventcount); // tell the system.. if (hlscanunsyncedlist.IsEmpty) // if nothing there.. { hlscanevent.WaitOne(60000); // Wait up to 60 seconds for another EDDN event to come in } if (Exit) { break; } } running = 0; }
static public Action <int> SentEvents; // called in thread when sync thread has finished and is terminating public static bool SendEDDNEvent(Action <string> logger, HistoryEntry helist) { return(SendEDDNEvents(logger, new[] { helist })); }
static public bool?SendToEDDN(HistoryEntry he) { EDDNClass eddn = new EDDNClass(); if (he.Commander != null) { eddn.commanderName = he.Commander.EdsmName; if (string.IsNullOrEmpty(eddn.commanderName)) { eddn.commanderName = he.Commander.Name; } if (he.Commander.Name.StartsWith("[BETA]", StringComparison.InvariantCultureIgnoreCase)) { eddn.isBeta = true; } } if (he.IsBetaMessage) { eddn.isBeta = true; } JournalEntry je = he.journalEntry; if (je == null) { je = JournalEntry.Get(he.Journalid); } JObject msg = null; if (je.EventTypeID == JournalTypeEnum.FSDJump) { msg = eddn.CreateEDDNMessage(je as JournalFSDJump); } else if (je.EventTypeID == JournalTypeEnum.Location) { msg = eddn.CreateEDDNMessage(je as JournalLocation); } else if (je.EventTypeID == JournalTypeEnum.Docked) { msg = eddn.CreateEDDNMessage(je as JournalDocked, he.System); } else if (je.EventTypeID == JournalTypeEnum.Scan) { msg = eddn.CreateEDDNMessage(je as JournalScan, he.System); } else if (je.EventTypeID == JournalTypeEnum.SAASignalsFound) { msg = eddn.CreateEDDNMessage(je as JournalSAASignalsFound, he.System); } else if (je.EventTypeID == JournalTypeEnum.Outfitting) { msg = eddn.CreateEDDNOutfittingMessage(je as JournalOutfitting, he.System); } else if (je.EventTypeID == JournalTypeEnum.Shipyard) { msg = eddn.CreateEDDNShipyardMessage(je as JournalShipyard, he.System); } else if (je.EventTypeID == JournalTypeEnum.Market) { JournalMarket jm = je as JournalMarket; msg = eddn.CreateEDDNCommodityMessage(jm.Commodities, jm.StarSystem, jm.Station, jm.MarketID, jm.EventTimeUTC); // if its devoid of data, null returned } if (msg != null) { if (eddn.PostMessage(msg)) { he.journalEntry.SetEddnSync(); return(true); } else { return(false); } } else { return(null); } }
public static void PaintEventColumn(DataGridView grid, DataGridViewRowPostPaintEventArgs e, int totalentries, HistoryEntry he, int hpos, int colwidth, bool showfsdmapcolour) { System.Diagnostics.Debug.Assert(he != null); // Trip for debug builds if something is wrong, if (he == null) // otherwise, ignore it and return. { return; } string rowIdx; if (EDDConfig.Instance.OrderRowsInverted) { rowIdx = he.Indexno.ToString(); // oldest has the highest index } else { rowIdx = (totalentries - he.Indexno + 1).ToString(); } var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height); // right alignment might actually make more sense for numbers using (var centerFormat = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }) using (Brush br = new SolidBrush(grid.RowHeadersDefaultCellStyle.ForeColor)) e.Graphics.DrawString(rowIdx, grid.RowHeadersDefaultCellStyle.Font, br, headerBounds, centerFormat); int noicons = (he.IsFSDJump && showfsdmapcolour) ? 2 : 1; if (he.StartMarker || he.StopMarker) { noicons++; } int padding = 4; int size = 24; if (size * noicons > (colwidth - 2)) { size = (colwidth - 2) / noicons; } int hstart = (hpos + colwidth / 2) - size / 2 * noicons - padding / 2 * (noicons - 1); int top = (e.RowBounds.Top + e.RowBounds.Bottom) / 2 - size / 2; e.Graphics.DrawImage(he.GetIcon, new Rectangle(hstart, top, size, size)); hstart += size + padding; if (he.IsFSDJump && showfsdmapcolour) { using (Brush b = new SolidBrush(Color.FromArgb(he.MapColour))) { e.Graphics.FillEllipse(b, new Rectangle(hstart + 2, top + 2, size - 6, size - 6)); } hstart += size + padding; } if (he.StartMarker) { e.Graphics.DrawImage(Icons.Controls.TravelGrid_FlagStart, new Rectangle(hstart, top, size, size)); } else if (he.StopMarker) { e.Graphics.DrawImage(Icons.Controls.TravelGrid_FlagStop, new Rectangle(hstart, top, size, size)); } }
public bool WouldAddEntry(HistoryEntry he) // do we filter? if its not in the journal event filter, or it is in the field filter { return(he.IsJournalEventInEventFilter(SQLiteDBClass.GetSettingString(DbFilterSave, "All")) && FilterHelpers.FilterHistory(he, fieldfilter, discoveryform.Globals)); }
private void buttonExtExcel_Click(object sender, EventArgs e) { Forms.ExportForm frm = new Forms.ExportForm(); frm.Init(new string[] { "View", "FSD Jumps only", "With Notes only", "With Notes, no repeat" }); if (frm.ShowDialog(FindForm()) == DialogResult.OK) { BaseUtils.CSVWriteGrid grd = new BaseUtils.CSVWriteGrid(); grd.SetCSVDelimiter(frm.Comma); List <SystemNoteClass> sysnotecache = new List <SystemNoteClass>(); string[] colh = null; grd.GetLineStatus += delegate(int r) { if (r < dataGridViewTravel.Rows.Count) { HistoryEntry he = (HistoryEntry)dataGridViewTravel.Rows[r].Cells[TravelHistoryColumns.HistoryTag].Tag; return((dataGridViewTravel.Rows[r].Visible && he.EventTimeLocal.CompareTo(frm.StartTime) >= 0 && he.EventTimeLocal.CompareTo(frm.EndTime) <= 0) ? BaseUtils.CSVWriteGrid.LineStatus.OK : BaseUtils.CSVWriteGrid.LineStatus.Skip); } else { return(BaseUtils.CSVWriteGrid.LineStatus.EOF); } }; if (frm.SelectedIndex == 1) // export fsd jumps { colh = new string[] { "Time", "Name", "X", "Y", "Z", "Distance", "Fuel Used", "Fuel Left", "Boost", "Note" }; grd.VerifyLine += delegate(int r) // addition qualifier for FSD jump { HistoryEntry he = (HistoryEntry)dataGridViewTravel.Rows[r].Cells[TravelHistoryColumns.HistoryTag].Tag; return(he.EntryType == JournalTypeEnum.FSDJump); }; grd.GetLine += delegate(int r) { HistoryEntry he = (HistoryEntry)dataGridViewTravel.Rows[r].Cells[TravelHistoryColumns.HistoryTag].Tag; EliteDangerousCore.JournalEvents.JournalFSDJump fsd = he.journalEntry as EliteDangerousCore.JournalEvents.JournalFSDJump; return(new Object[] { fsd.EventTimeLocal, fsd.StarSystem, fsd.StarPos.X, fsd.StarPos.Y, fsd.StarPos.Z, fsd.JumpDist, fsd.FuelUsed, fsd.FuelLevel, fsd.BoostUsed, he.snc != null ? he.snc.Note : "", }); }; } else { colh = new string[] { "Time", "Event", "System", "Body", //0 "Ship", "Summary", "Description", "Detailed Info", //4 "Note", "Travel Dist", "Travel Time", "Travel Jumps", //8 "Travelled MisJumps", "X", "Y", "Z", //12 "JID", "EDSMID", "EDDBID" }; //16 grd.GetLine += delegate(int r) { HistoryEntry he = (HistoryEntry)dataGridViewTravel.Rows[r].Cells[TravelHistoryColumns.HistoryTag].Tag; return(new Object[] { dataGridViewTravel.Rows[r].Cells[0].Value, he.journalEntry.EventTypeStr, (he.System != null) ? he.System.Name : "Unknown", // paranoia he.WhereAmI, he.ShipInformation != null ? he.ShipInformation.Name : "Unknown", he.EventSummary, he.EventDescription, he.EventDetailedInfo, dataGridViewTravel.Rows[r].Cells[4].Value, he.isTravelling ? he.TravelledDistance.ToString("0.0") : "", he.isTravelling ? he.TravelledSeconds.ToString() : "", he.isTravelling ? he.Travelledjumps.ToStringInvariant() : "", he.isTravelling ? he.TravelledMissingjump.ToStringInvariant() : "", he.System.X, he.System.Y, he.System.Z, he.Journalid, he.System.EDSMID, he.System.EDDBID, }); }; if (frm.SelectedIndex == 2 || frm.SelectedIndex == 3) // export notes { grd.VerifyLine += delegate(int r) // second hook to reject line { HistoryEntry he = (HistoryEntry)dataGridViewTravel.Rows[r].Cells[TravelHistoryColumns.HistoryTag].Tag; if (he.snc != null) { if (sysnotecache.Contains(he.snc)) { return(false); } else { if (frm.SelectedIndex == 3) { sysnotecache.Add(he.snc); } return(true); } } else { return(false); } }; } } grd.GetHeader += delegate(int c) { return((c < colh.Length && frm.IncludeHeader) ? colh[c] : null); }; if (grd.WriteCSV(frm.Path)) { if (frm.AutoOpen) { System.Diagnostics.Process.Start(frm.Path); } } else { ExtendedControls.MessageBoxTheme.Show(FindForm(), "Failed to write to " + frm.Path, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }
public int GetLogs(DateTime starttimeutc, out List<HistoryEntry> log) { log = new List<HistoryEntry>(); if (!IsApiKeySet) return 0; string query = "get-logs?showId=1&startdatetime=" + HttpUtility.UrlEncode(starttimeutc.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)) + "&apiKey=" + apiKey + "&commanderName=" + HttpUtility.UrlEncode(commanderName); //string query = "get-logs?apiKey=" + apiKey + "&commanderName=" + HttpUtility.UrlEncode(commanderName); var response = RequestGet("api-logs-v1/" + query, handleException: true); if (response.Error) return 0; var json = response.Body; if (json == null) return 0; JObject msg = JObject.Parse(json); int msgnr = msg["msgnum"].Value<int>(); JArray logs = (JArray)msg["logs"]; if (logs != null) { using (SQLiteConnectionSystem cn = new SQLiteConnectionSystem()) { foreach (JObject jo in logs) { string name = jo["system"].Value<string>(); string ts = jo["date"].Value<string>(); long id = jo["systemId"].Value<long>(); DateTime etutc = DateTime.ParseExact(ts, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal|DateTimeStyles.AssumeUniversal); // UTC time SystemClass sc = SystemClass.GetSystem(id, cn, SystemClass.SystemIDType.EdsmId); if (sc == null) sc = new SystemClass(name) { id_edsm = id }; HistoryEntry he = new HistoryEntry(); he.MakeVSEntry(sc, etutc, EDDConfig.Instance.DefaultMapColour, "", ""); // FSD jump entry log.Add(he); } } } return msgnr; }
public override void InitialDisplay() // on start up, this will have an empty history { last_he = discoveryform.history.GetLast; PopulateBookmarkCombo(); DisplayCompass(); }
// called thru CalLWithConverter in UI main class.. that pases a ImageConverter to us // sysname and or ss can be null if it was picked up by a watcher not the new journal screenshot entry private void ProcessScreenshot(string filename, string sysname, JournalScreenshot ss, int cmdrid, ImageConverter cp) { System.Threading.Timer timer = null; if (sysname == null) { if (LastJournalLoc != null) { sysname = LastJournalLoc.StarSystem; } else if (cmdrid >= 0) { LastJournalLoc = JournalEntry.GetLast <JournalLocOrJump>(cmdrid, DateTime.UtcNow); if (LastJournalLoc != null) { sysname = LastJournalLoc.StarSystem; } } } if (sysname == null) { HistoryEntry he = _discoveryForm.history.GetLastFSD; sysname = (he != null) ? he.System.name : "Unknown System"; } try { cp.InputFilename = filename; cp.SystemName = sysname; cp.JournalScreenShot = ss; cp.CommanderID = cmdrid; bool converted = false; using (Bitmap bmp = cp.GetScreenshot(ref filename)) { // Don't run if OnScreenshot has already run for this image if ((ScreenshotTimers.TryGetValue(filename, out timer) && timer == null) || (!ScreenshotTimers.TryAdd(filename, null) && !ScreenshotTimers.TryUpdate(filename, null, timer))) { return; } if (timer != null) { timer.Dispose(); } converted = cp.Convert(bmp); } if (converted && cp.RemoveInputFile) // if remove, delete original picture { ScreenshotTimers.TryRemove(filename, out timer); try { File.Delete(filename); } catch { System.Diagnostics.Trace.WriteLine($"Unable to remove file {filename}"); } } this.OnScreenshot?.Invoke(cp); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception watcher: " + ex.Message); System.Diagnostics.Trace.WriteLine("Trace: " + ex.StackTrace); _discoveryForm.LogLineHighlight("Error in executing image conversion, try another screenshot, check output path settings. (Exception " + ex.Message + ")"); } }
// true if it should be included public bool FilterHistory(HistoryEntry he) { List<FilterEvent> list = null; // don't want it return CheckFilterTrueOut(he.journalEntry.EventDataString, he.journalEntry.EventTypeStr, ref list); // true it should be included }
private void Display(HistoryEntry he, HistoryList hl) => Display(he, hl, true);
// add if in event filter, and not in field filter.. private void AddNewEntry(HistoryEntry he, HistoryList hl) { if (he.IsJournalEventInEventFilter(SQLiteDBClass.GetSettingString(DbFilterSave, "All")) && fieldfilter.FilterHistory(he) ) { AddNewJournalRow(true, he); } }
private void AddNewEntry(HistoryEntry he, HistoryList hl) { Stats(he, hl); }
static public bool?SendToEDDN(HistoryEntry he, bool debugonly = false) { EDDNClass eddn = new EDDNClass(); if (he.Commander != null) { eddn.commanderName = he.Commander.EdsmName; if (string.IsNullOrEmpty(eddn.commanderName)) { eddn.commanderName = he.Commander.Name; } if (he.Commander.Name.StartsWith("[BETA]", StringComparison.InvariantCultureIgnoreCase)) { eddn.isBeta = true; } } if (he.journalEntry.IsBeta) { eddn.isBeta = true; } JournalEntry je = he.journalEntry; if (je == null) { je = JournalEntry.Get(he.Journalid); } BaseUtils.JSON.JObject msg = null; if (je.EventTypeID == JournalTypeEnum.FSDJump) { msg = eddn.CreateEDDNMessage(je as JournalFSDJump); } else if (je.EventTypeID == JournalTypeEnum.Location) { msg = eddn.CreateEDDNMessage(je as JournalLocation); } else if (je.EventTypeID == JournalTypeEnum.CarrierJump) { msg = eddn.CreateEDDNMessage(je as JournalCarrierJump); } else if (je.EventTypeID == JournalTypeEnum.Docked) { msg = eddn.CreateEDDNMessage(je as JournalDocked, he.System); } else if (je.EventTypeID == JournalTypeEnum.Scan) { msg = eddn.CreateEDDNMessage(je as JournalScan, he.System); } else if (je.EventTypeID == JournalTypeEnum.SAASignalsFound) { msg = eddn.CreateEDDNMessage(je as JournalSAASignalsFound, he.System); } else if (je.EventTypeID == JournalTypeEnum.Outfitting) { msg = eddn.CreateEDDNOutfittingMessage(je as JournalOutfitting); } else if (je.EventTypeID == JournalTypeEnum.Shipyard) { msg = eddn.CreateEDDNShipyardMessage(je as JournalShipyard); } else if (je.EventTypeID == JournalTypeEnum.Market) { JournalMarket jm = je as JournalMarket; msg = eddn.CreateEDDNCommodityMessage(jm.Commodities, jm.IsOdyssey, jm.IsHorizons, jm.StarSystem, jm.Station, jm.MarketID, jm.EventTimeUTC); // if its devoid of data, null returned } else if (je.EventTypeID == JournalTypeEnum.EDDCommodityPrices) { JournalEDDCommodityPrices jm = je as JournalEDDCommodityPrices; msg = eddn.CreateEDDNCommodityMessage(jm.Commodities, jm.IsOdyssey, jm.IsHorizons, jm.StarSystem, jm.Station, jm.MarketID, jm.EventTimeUTC); // if its devoid of data, null returned } if (msg != null) { System.Diagnostics.Debug.WriteLine("Send to EDDN " + msg.ToString(true)); if (!debugonly && eddn.PostMessage(msg)) { he.journalEntry.SetEddnSync(); return(true); } else { return(false); } } else { return(null); } }
public void SelectionChanged(HistoryEntry he, HistoryList hl) { Stats(he, hl); }
// DEBUGGING ONLY.. click on a scan and it will trigger it private void Travelhistorycontrol_OnTravelSelectionChanged(HistoryEntry he, HistoryList hl) { if (he.journalEntry.EventTypeID == EliteDangerous.JournalTypeEnum.Scan) // if scan, see if it needs to be displayed { ShowScanData(he.journalEntry as EliteDangerous.JournalEvents.JournalScan); } else HideScanData(null,null); }
private void Stats(HistoryEntry he, HistoryList hl) { dataGridViewStats.Rows.Clear(); if (he != null) { StatToDGV("Visits", hl.GetVisitsCount(he.System.name, he.System.id_edsm) + " to system " + he.System.name); StatToDGV("Jumps Before System", hl.GetFSDJumpsBeforeUTC(he.EventTimeUTC)); } int totaljumps = hl.GetFSDJumps(new TimeSpan(10000, 0, 0, 0)); StatToDGV("Total No of jumps: ", totaljumps); if (totaljumps > 0) { StatToDGV("Jump History", "24 Hours: " + hl.GetFSDJumps(new TimeSpan(1, 0, 0, 0)) + ", One Week: " + hl.GetFSDJumps(new TimeSpan(7, 0, 0, 0)) + ", 30 Days: " + hl.GetFSDJumps(new TimeSpan(30, 0, 0, 0)) + ", One Year: " + hl.GetFSDJumps(new TimeSpan(365, 0, 0, 0)) ); HistoryEntry north = hl.GetConditionally(Double.MinValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.z > l; if (v) { l = s.System.z; } return(v); }); HistoryEntry south = hl.GetConditionally(Double.MaxValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.z < l; if (v) { l = s.System.z; } return(v); }); HistoryEntry east = hl.GetConditionally(Double.MinValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.x > l; if (v) { l = s.System.x; } return(v); }); HistoryEntry west = hl.GetConditionally(Double.MaxValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.x < l; if (v) { l = s.System.x; } return(v); }); HistoryEntry up = hl.GetConditionally(Double.MinValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.y > l; if (v) { l = s.System.y; } return(v); }); HistoryEntry down = hl.GetConditionally(Double.MaxValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.y < l; if (v) { l = s.System.y; } return(v); }); StatToDGV("Most North", north.System.name + " @ " + north.System.x.ToString("0.0") + "," + north.System.y.ToString("0.0") + "," + north.System.z.ToString("0.0")); StatToDGV("Most South", south.System.name + " @ " + south.System.x.ToString("0.0") + "," + south.System.y.ToString("0.0") + "," + south.System.z.ToString("0.0")); StatToDGV("Most East", east.System.name + " @ " + east.System.x.ToString("0.0") + "," + east.System.y.ToString("0.0") + "," + east.System.z.ToString("0.0")); StatToDGV("Most West", west.System.name + " @ " + west.System.x.ToString("0.0") + "," + west.System.y.ToString("0.0") + "," + west.System.z.ToString("0.0")); StatToDGV("Most Highest", up.System.name + " @ " + up.System.x.ToString("0.0") + "," + up.System.y.ToString("0.0") + "," + up.System.z.ToString("0.0")); StatToDGV("Most Lowest", down.System.name + " @ " + down.System.x.ToString("0.0") + "," + down.System.y.ToString("0.0") + "," + down.System.z.ToString("0.0")); var groupeddata = from data in hl.OrderByDate where data.IsFSDJump group data by data.System.name into grouped select new { Title = grouped.Key, Count = grouped.Count() }; mostVisited.Visible = true; Color GridC = discoveryform.theme.GridCellText; Color TextC = discoveryform.theme.VisitedSystemColor; mostVisited.Titles.Clear(); mostVisited.Titles.Add(new Title("Most Visited", Docking.Top, discoveryform.theme.GetFont, TextC)); mostVisited.Series[0].Points.Clear(); mostVisited.ChartAreas[0].AxisX.LabelStyle.ForeColor = TextC; mostVisited.ChartAreas[0].AxisY.LabelStyle.ForeColor = TextC; mostVisited.ChartAreas[0].AxisX.MajorGrid.LineColor = GridC; mostVisited.ChartAreas[0].AxisX.MinorGrid.LineColor = GridC; mostVisited.ChartAreas[0].AxisY.MajorGrid.LineColor = GridC; mostVisited.ChartAreas[0].AxisY.MinorGrid.LineColor = GridC; mostVisited.ChartAreas[0].BorderColor = GridC; mostVisited.ChartAreas[0].BorderDashStyle = ChartDashStyle.Solid; mostVisited.ChartAreas[0].BorderWidth = 2; mostVisited.ChartAreas[0].BackColor = Color.Transparent; mostVisited.Series[0].Color = GridC; mostVisited.BorderlineColor = Color.Transparent; int i = 0; foreach (var data in from a in groupeddata orderby a.Count descending select a) { if (data.Count <= 1 || i == 10) { break; } mostVisited.Series[0].Points.Add(new DataPoint(i, data.Count)); mostVisited.Series[0].Points[i].AxisLabel = data.Title; mostVisited.Series[0].Points[i].LabelForeColor = TextC; i++; } } else { mostVisited.Visible = false; } SizeControls(); }
public void SelectionChanged(HistoryEntry he, HistoryList hl) { Stats(he, hl); }
private void Uctg_OnTravelSelectionChanged(HistoryEntry he, HistoryList hl, bool selectedEntry) { KickComputation(he); }
private void Stats(HistoryEntry he, HistoryList hl) { dataGridViewStats.Rows.Clear(); if (he != null) { StatToDGV("Visits", hl.GetVisitsCount(he.System.name, he.System.id_edsm) + " to system " + he.System.name); StatToDGV("Jumps Before System", hl.GetFSDJumpsBeforeUTC(he.EventTimeUTC)); } int totaljumps = hl.GetFSDJumps(new TimeSpan(10000, 0, 0, 0)); StatToDGV("Total No of jumps: ", totaljumps); if (totaljumps > 0) { StatToDGV("Jump History", "24 Hours: " + hl.GetFSDJumps(new TimeSpan(1, 0, 0, 0)) + ", One Week: " + hl.GetFSDJumps(new TimeSpan(7, 0, 0, 0)) + ", 30 Days: " + hl.GetFSDJumps(new TimeSpan(30, 0, 0, 0)) + ", One Year: " + hl.GetFSDJumps(new TimeSpan(365, 0, 0, 0)) ); HistoryEntry north = hl.GetConditionally(Double.MinValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.z > l; if (v) l = s.System.z; return v; }); HistoryEntry south = hl.GetConditionally(Double.MaxValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.z < l; if (v) l = s.System.z; return v; }); HistoryEntry east = hl.GetConditionally(Double.MinValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.x > l; if (v) l = s.System.x; return v; }); HistoryEntry west = hl.GetConditionally(Double.MaxValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.x < l; if (v) l = s.System.x; return v; }); HistoryEntry up = hl.GetConditionally(Double.MinValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.y > l; if (v) l = s.System.y; return v; }); HistoryEntry down = hl.GetConditionally(Double.MaxValue, (HistoryEntry s, ref double l) => { bool v = s.IsFSDJump && s.System.HasCoordinate && s.System.y < l; if (v) l = s.System.y; return v; }); StatToDGV("Most North", north.System.name + " @ " + north.System.x.ToString("0.0") + "," + north.System.y.ToString("0.0") + "," + north.System.z.ToString("0.0")); StatToDGV("Most South", south.System.name + " @ " + south.System.x.ToString("0.0") + "," + south.System.y.ToString("0.0") + "," + south.System.z.ToString("0.0")); StatToDGV("Most East", east.System.name + " @ " + east.System.x.ToString("0.0") + "," + east.System.y.ToString("0.0") + "," + east.System.z.ToString("0.0")); StatToDGV("Most West", west.System.name + " @ " + west.System.x.ToString("0.0") + "," + west.System.y.ToString("0.0") + "," + west.System.z.ToString("0.0")); StatToDGV("Most Highest", up.System.name + " @ " + up.System.x.ToString("0.0") + "," + up.System.y.ToString("0.0") + "," + up.System.z.ToString("0.0")); StatToDGV("Most Lowest", down.System.name + " @ " + down.System.x.ToString("0.0") + "," + down.System.y.ToString("0.0") + "," + down.System.z.ToString("0.0")); var groupeddata = from data in hl.OrderByDate where data.IsFSDJump group data by data.System.name into grouped select new { Title = grouped.Key, Count = grouped.Count() }; mostVisited.Visible = true; Color GridC = discoveryform.theme.GridCellText; Color TextC = discoveryform.theme.VisitedSystemColor; mostVisited.Titles.Clear(); mostVisited.Titles.Add(new Title("Most Visited", Docking.Top, discoveryform.theme.GetFont, TextC)); mostVisited.Series[0].Points.Clear(); mostVisited.ChartAreas[0].AxisX.LabelStyle.ForeColor = TextC; mostVisited.ChartAreas[0].AxisY.LabelStyle.ForeColor = TextC; mostVisited.ChartAreas[0].AxisX.MajorGrid.LineColor = GridC; mostVisited.ChartAreas[0].AxisX.MinorGrid.LineColor = GridC; mostVisited.ChartAreas[0].AxisY.MajorGrid.LineColor = GridC; mostVisited.ChartAreas[0].AxisY.MinorGrid.LineColor = GridC; mostVisited.ChartAreas[0].BorderColor = GridC; mostVisited.ChartAreas[0].BorderDashStyle = ChartDashStyle.Solid; mostVisited.ChartAreas[0].BorderWidth = 2; mostVisited.ChartAreas[0].BackColor = Color.Transparent; mostVisited.Series[0].Color = GridC; mostVisited.BorderlineColor = Color.Transparent; int i = 0; foreach (var data in from a in groupeddata orderby a.Count descending select a) { if (data.Count <= 1 || i == 10) break; mostVisited.Series[0].Points.Add(new DataPoint(i, data.Count)); mostVisited.Series[0].Points[i].AxisLabel = data.Title; mostVisited.Series[0].Points[i].LabelForeColor = TextC; i++; } } else mostVisited.Visible = false; SizeControls(); }
public override bool ExecuteAction(ActionProgramRun ap) { string res; if (ap.Functions.ExpandString(UserData, out res) != Functions.ExpandResult.Failed) { HistoryList hl = (ap.ActionController as ActionController).HistoryList; StringParser sp = new StringParser(res); string prefix = "EC_"; string cmdname = sp.NextWordLCInvariant(" "); if (cmdname != null && cmdname.Equals("prefix")) { prefix = sp.NextWord(); if (prefix == null) { ap.ReportError("Missing name after Prefix in Event"); return(true); } cmdname = sp.NextWordLCInvariant(" "); } int jidindex = -1; if (cmdname != null && (cmdname.Equals("from") || cmdname.Equals("thpos"))) { long?jid; if (cmdname.Equals("thpos")) { HistoryEntry he = (ap.ActionController as ActionController).DiscoveryForm.PrimaryCursor.GetCurrentHistoryEntry; if (he == null) { ReportEntry(ap, null, 0, prefix); return(true); } jid = he.Journalid; } else { jid = sp.NextWord().InvariantParseLongNull(); if (!jid.HasValue) { ap.ReportError("Non integer JID after FROM in Event"); return(true); } } jidindex = hl.GetIndex(jid.Value); if (jidindex == -1) { ReportEntry(ap, null, 0, prefix); return(true); } cmdname = sp.NextWordLCInvariant(" "); } if (cmdname == null) { if (jidindex != -1) { ReportEntry(ap, hl.EntryOrder(), jidindex, prefix); } else { ap.ReportError("No commands in Event"); } return(true); } bool fwd = cmdname.Equals("forward") || cmdname.Equals("first"); bool back = cmdname.Equals("backward") || cmdname.Equals("last"); if (fwd || back) { List <string> eventnames = sp.NextOptionallyBracketedList(); // single entry, list of events bool not = eventnames.Count == 1 && eventnames[0].Equals("NOT", StringComparison.InvariantCultureIgnoreCase); // if it goes NOT if (not) { eventnames = sp.NextOptionallyBracketedList(); // then get another list } // is it "WHERE" bool whereasfirst = eventnames.Count == 1 && eventnames[0].Equals("WHERE", StringComparison.InvariantCultureIgnoreCase); ConditionLists cond = new ConditionLists(); string nextword; // if WHERE cond, or eventname WHERE cond if (whereasfirst || ((nextword = sp.NextWord()) != null && nextword.Equals("WHERE", StringComparison.InvariantCultureIgnoreCase))) { if (whereasfirst) // clear out event names if it was WHERE cond.. { eventnames.Clear(); } string resc = cond.Read(sp.LineLeft); // rest of it is the condition.. if (resc != null) { ap.ReportError(resc + " in Where of Event"); return(true); } } List <HistoryEntry> hltest; if (jidindex == -1) // if no JID given.. { hltest = hl.EntryOrder(); // the whole list } else if (fwd) { hltest = hl.EntryOrder().GetRange(jidindex + 1, hl.Count - (jidindex + 1)); // cut down list, excluding this entry } else { hltest = hl.EntryOrder().GetRange(0, jidindex); } if (eventnames.Count > 0) // screen out event names { hltest = (from h in hltest where eventnames.Contains(h.journalEntry.EventTypeStr, StringComparer.OrdinalIgnoreCase) == !not select h).ToList(); } if (cond.Count > 0) // if we have filters, apply, filter out, true only stays { hltest = UserControls.FilterHelpers.CheckFilterTrue(hltest, cond, new Variables()); // apply filter.. } if (fwd) { ReportEntry(ap, hltest, 0, prefix); } else { ReportEntry(ap, hltest, hltest.Count - 1, prefix); } return(true); } else { if (jidindex == -1) { ap.ReportError("Valid JID must be given for command " + cmdname + " in Event"); } else { HistoryEntry he = hl.EntryOrder()[jidindex]; ap[prefix + "JID"] = jidindex.ToStringInvariant(); if (cmdname.Equals("action")) { int count = (ap.ActionController as ActionController).ActionRunOnEntry(he, Actions.ActionEventEDList.EventCmd(he), now: true); ap[prefix + "Count"] = count.ToString(System.Globalization.CultureInfo.InvariantCulture); } else if (cmdname.Equals("edsm")) { EliteDangerousCore.EDSM.EDSMClass edsm = new EliteDangerousCore.EDSM.EDSMClass(); string url = edsm.GetUrlCheckSystemExists(he.System.Name); ap[prefix + "URL"] = url; if (url.Length > 0) // may pass back empty string if not known, this solves another exception { BaseUtils.BrowserInfo.LaunchBrowser(url); } } else if (cmdname.Equals("ross")) { ap.ReportError("Not implemented"); } else if (cmdname.Equals("eddb")) { string url = Properties.Resources.URLEDDBSystemName + System.Web.HttpUtility.UrlEncode(he.System.Name); BaseUtils.BrowserInfo.LaunchBrowser(url); ap[prefix + "URL"] = url; } else if (cmdname.Equals("info")) { ActionVars.SystemVarsFurtherInfo(ap, hl, he.System, prefix); ActionVars.ShipModuleInformation(ap, he.ShipInformation, prefix); } else if (cmdname.Equals("missions")) { ActionVars.MissionInformation(ap, hl.MissionListAccumulator.GetMissionList(he.MissionList), prefix); } else if (cmdname.Equals("setstartmarker")) { he.journalEntry.SetStartFlag(); } else if (cmdname.Equals("setstopmarker")) { he.journalEntry.SetEndFlag(); } else if (cmdname.Equals("clearstartstopmarker")) { he.journalEntry.ClearStartEndFlag(); } else if (cmdname.Equals("note")) { string note = sp.NextQuotedWord(); if (note != null && sp.IsEOL) { he.SetJournalSystemNoteText(note, true, EDCommander.Current.SyncToEdsm); (ap.ActionController as ActionController).DiscoveryForm.NoteChanged(this, he, true); } else { ap.ReportError("Missing note text or unquoted text in Event NOTE"); } } else { ap.ReportError("Unknown command " + cmdname + " in Event"); } } } } else { ap.ReportError(res); } return(true); }
public void AddNewEntry(HistoryEntry he) { AddNewJournalRow(true, he); }
private void Display(HistoryList hl) // when user clicks around.. HE may be null here { currentHE = hl.GetLastFSD; Display(); }
// called when a new entry is made.. check to see if its a scan update public void NewEntry(HistoryEntry he, HistoryList hl) { // affecting our system StarScan.SystemNode newnode = (he != null) ? hl.starscan.FindSystem(he.System) : null; // find node.. if ( newnode == last_sn && he.EntryType == EliteDangerous.JournalTypeEnum.Scan ) // if on same star system, and its a scan, it may have been updated.. { DrawSystem(last_sn); } }
private void NewEntry(HistoryEntry l, HistoryList hl) { currentHE = hl.GetLastFSD; Display(); }
private void Display(HistoryEntry he, HistoryList hl, bool selectedEntry) // when user clicks around.. { UpdateSystemRows(); }
private void NewEntry(HistoryEntry he, HistoryList hl) { DrawSystem(he, he.EntryType == JournalTypeEnum.Scan); }
/// <summary> /// The add entry. /// </summary> /// <param name="entry"> /// The entry. /// </param> public override void AddEntry(HistoryEntry entry) { }
internal void Add(string text) { var entry = new HistoryEntry { Text = text }; _live = false; if (Length == 0 || Last.Text != text) { _history.Add(entry); var handler = ItemAdded; if (handler != null) { handler(this, new HistoryEventArgs(entry)); } } if (_history[InternalPosition].Text != text) { _pos = -1; } if (Length > MaxLength) { _history.RemoveAt(0); if (_pos > 0) { _pos--; } } }
public void No_filter_does_not_filter_anything() { var veryOldData = new HistoryEntry { EventTimeUTC = DateTime.UtcNow.Subtract(TimeSpan.FromDays(500000)) }; var input = new HistoryList { veryOldData }; Check.That(TravelHistoryFilter.NoFilter.Filter(input)).ContainsExactly(veryOldData); }
/// <summary> /// Saves all history entries in the Entries list to file. /// </summary> public void SaveEntries() { if (FileCompressed()) // -- Need to make sure the file is decompressed just as a sanity check before editing any data. GZip.DecompressFile(_baseName + ".hch"); var indexTableSize = (_thisMap.CWMap.SizeX*_thisMap.CWMap.SizeY*_thisMap.CWMap.SizeZ)*4; using (var fs = new FileStream(_baseName + ".hch", FileMode.Open)) { lock (_eLock) { foreach (var h in Entries) { var temp = new byte[4]; var index = (h.Y*_thisMap.CWMap.SizeZ + h.Z)*_thisMap.CWMap.SizeX + h.X; fs.Seek(index*4, SeekOrigin.Begin); fs.Read(temp, 0, 4); var entryIndex = BitConverter.ToInt32(temp, 0); if (entryIndex == 0) { // -- There are no entries for this block yet. fs.Seek(0, SeekOrigin.End); // -- Seek to the end of the file. var endLocation = ((int) fs.Position - indexTableSize); // -- Store the index for this entry fs.WriteByte(1); // -- There is now 1 entry fs.Write(h.ToByteArray(), 0, 10); // -- And this is the data. fs.Seek(index*4, SeekOrigin.Begin); // -- Seek back to the Int for this block. fs.Write(BitConverter.GetBytes(endLocation), 0, 4); // -- Write in the location for that block's entries. continue; // -- Move on to the next HistoryEntry. } // -- There is already one or more entries for this block. fs.Seek(indexTableSize + entryIndex, SeekOrigin.Begin); // -- Seek to the position for this block var numEntries = fs.ReadByte(); // -- And get the number of entries. // -- Before adding anything, we'll check to see if this user already has an entry. var tempArray = new HistoryEntry[numEntries]; var shift = false; for (var i = 0; i < numEntries; i++) // -- Modify the timestamp and block if so.. { // -- Load the entries for checking. var thisEntry = new byte[10]; fs.Read(thisEntry, 0, 10); tempArray[i] = HistoryEntry.FromByteArray(thisEntry, h.X, h.Y, h.Z); if (tempArray[i].Player == h.Player) { // -- If there is a player, update the new block, and the change time. tempArray[i].Timestamp = h.Timestamp; tempArray[i].NewBlock = h.NewBlock; shift = true; // -- This entry now needs to be shifted. } } if (shift) { tempArray = tempArray.OrderBy(o => o.Timestamp).ToArray(); // -- If there was an entry, order the array... fs.Seek((indexTableSize + entryIndex) + 1, SeekOrigin.Begin); // -- Seek to the beginning of the entries.. foreach (var z in tempArray) // -- Write the newly ordered entries fs.Write(z.ToByteArray(), 0, 10); continue; // -- Move to the next iteration. } // -- If the user did not have any previous entries... // -- Now We'll handle the easy case first, if we've already reached the maximum. if (numEntries == ServerCore.MaxHistoryEntries) { tempArray[0] = h; // -- Overwrite the old entry with the newest one. tempArray = tempArray.OrderBy(o => o.Timestamp).ToArray(); // -- Order the array by timestamp, so that our new entry is at the end. fs.Seek((indexTableSize + entryIndex) + 1, SeekOrigin.Begin); // -- Seek to the beginning of the entries.. foreach (var z in tempArray) // -- Write the newly ordered entries fs.Write(z.ToByteArray(), 0, 10); continue; // -- Move on to the next iteration. } // -- And finally, the condition that causes fragmentation :( Actually creating an entry. fs.Seek(0, SeekOrigin.End); var endPosition = ((int) fs.Position - indexTableSize); fs.WriteByte((byte) (numEntries + 1)); foreach (var z in tempArray) fs.Write(z.ToByteArray(), 0, 10); fs.Write(h.ToByteArray(), 0, 10); fs.Seek(index*4, SeekOrigin.Begin); // -- Seek back to the Int for this block. fs.Write(BitConverter.GetBytes(endPosition), 0, 4); // -- Write in the location for that block's entries. _fragmented = true; // -- Annnd that's all folks! } Entries.Clear(); } } }
/// <summary> /// TranslateEventData - Takes the Event Data and translates it to something human readable /// </summary> /// <param name="HistoryEvent">The Event whose argument data is being translated</param> /// <param name="ArgumentReader">The raw data we are translating</param> /// <returns>The Human Readable text</returns> // Revision History // MM/DD/YY who Version Issue# Description // -------- --- ------- ------ --------------------------------------- // 05/01/08 KRC 1.50.20 Created // 07/02/09 AF 2.20.11 Corrected the naming of SITESCAN_OR_PENDING_TABLE_CLEAR. // This is a standard event and does not refer to SiteScan // 03/15/12 jrf 2.53.50 TREQ5571 Switched to pass as argument a HistoryEntry instead of just // the history code. // 10/12/12 MSC 2.70.28 TQ6684 Translating the Power Up and Power Down events. // 12/17/12 MSC 2.70.51 241238 Code Review Changes. // 02/23/15 jrf 4.10.04 566291 The power outage and restored event data was modified to // only show the power outage count if the first event argument is 1. // Anything higher than 1 is reseved. // 12/17/15 AF 4.23.00 559019 Adding the event argument data to the CLOCK_RESET event // 01/28/16 AF 4.50.224 RTT586620 Extending the event argument for the power restored event to support power up threshold // 04/18/16 CFB 4.50.248 WR625383 Changed fields "Power outage count" and "Power restored count" to "Outage ID" and "Power Restored ID" respectively // 04/20/16 CFB 4.50.248 WR625383 Changed fields "Outage ID" and "Power Restored ID" to "Outage "Id" // 07/12/16 MP 4.70.7 WR688986 Changed POWER_OUTAGE and POWER_RESTORED to PRIMARY_POWER_DOWN and PRIMARY_POWER_UP public virtual string TranslatedEventData(HistoryEntry HistoryEvent, PSEMBinaryReader ArgumentReader) { String strData = ""; switch (HistoryEvent.HistoryCode) { case (ushort)(CANSIDevice.HistoryEvents.CLOCK_RESET): { // The time format must be set before this method is called DateTime dtCurrentTime = ArgumentReader.ReadLTIME((PSEMBinaryReader.TM_FORMAT)TimeFormat); strData = "Current Time: " + dtCurrentTime.ToShortDateString() + " " + dtCurrentTime.ToLongTimeString(); break; } case (ushort)(CANSIDevice.HistoryEvents.PENDING_TABLE_ACTIVATION): case (ushort)(CANSIDevice.HistoryEvents.PENDING_TABLE_CLEAR): { strData = "Table: "; strData += ArgumentReader.ReadInt16().ToString(CultureInfo.InvariantCulture); break; } case (ushort)(CANSIDevice.HistoryEvents.LOSS_OF_PHASE): case (ushort)(CANSIDevice.HistoryEvents.REVERSE_POWER_FLOW): { byte byArg = ArgumentReader.ReadByte(); strData = "Phase(s): "; if (0 != (byArg & PHASE_A_MASK)) { strData += " (A)"; } if (0 != (byArg & PHASE_B_MASK)) { strData += " (B)"; } if (0 != (byArg & PHASE_C_MASK)) { strData += " (C)"; } break; } case (ushort)(CANSIDevice.HistoryEvents.RATE_CHANGE): { byte byArg = ArgumentReader.ReadByte(); if (byArg == RATE_A_MASK) { strData += " (Rate A)"; } else if (byArg == RATE_B_MASK) { strData += " (Rate B)"; } else if (byArg == RATE_C_MASK) { strData += " (Rate C)"; } else if (byArg == RATE_D_MASK) { strData += " (Rate D)"; } else if (byArg == RATE_E_MASK) { strData += " (Rate E)"; } else if (byArg == RATE_F_MASK) { strData += " (Rate F)"; } else if (byArg == RATE_G_MASK) { strData += " (Rate G)"; } break; } case (ushort)(CANSIDevice.HistoryEvents.PRIMARY_POWER_DOWN): { byte Enabled = ArgumentReader.ReadByte(); if (Enabled == 1) { byte Counter = ArgumentReader.ReadByte(); strData += "Outage Id: " + Counter; } break; } case (ushort)(CANSIDevice.HistoryEvents.PRIMARY_POWER_UP): { byte Enabled = ArgumentReader.ReadByte(); if (Enabled == 1) { byte Counter = ArgumentReader.ReadByte(); strData += "Outage Id: " + Counter; } else if (Enabled == 2) { byte reserved = ArgumentReader.ReadByte(); ushort NumberOfPowerCycles = ArgumentReader.ReadUInt16(); strData += "Number of Power Cycles: " + NumberOfPowerCycles.ToString(CultureInfo.CurrentCulture); } break; } // KRC:TODO - Add other Events here that have data to interpret. default: { strData = ""; break; } } return(strData); }
private void buttonExtExcel_Click(object sender, EventArgs e) { Forms.ExportForm frm = new Forms.ExportForm(); frm.Init(new string[] { "Export Current View" }, allowRawJournalExport: true); if (frm.ShowDialog(this.FindForm()) == DialogResult.OK) { if (frm.ExportAsJournals) { try { using (StreamWriter writer = new StreamWriter(frm.Path)) { foreach (DataGridViewRow dgvr in dataGridViewJournal.Rows) { HistoryEntry he = dgvr.Cells[JournalHistoryColumns.HistoryTag].Tag as HistoryEntry; if (dgvr.Visible && he.EventTimeLocal.CompareTo(frm.StartTime) >= 0 && he.EventTimeLocal.CompareTo(frm.EndTime) <= 0) { string forExport = he.journalEntry.GetJson()?.ToString().Replace("\r\n", ""); forExport = System.Text.RegularExpressions.Regex.Replace(forExport, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1"); writer.Write(forExport); writer.WriteLine(); } } } if (frm.AutoOpen) { System.Diagnostics.Process.Start(frm.Path); } } catch { ExtendedControls.MessageBoxTheme.Show(this.FindForm(), "Failed to write to " + frm.Path, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { if (frm.SelectedIndex == 0) { BaseUtils.CSVWriteGrid grd = new BaseUtils.CSVWriteGrid(); grd.SetCSVDelimiter(frm.Comma); grd.GetLineStatus += delegate(int r) { if (r < dataGridViewJournal.Rows.Count) { HistoryEntry he = dataGridViewJournal.Rows[r].Cells[JournalHistoryColumns.HistoryTag].Tag as HistoryEntry; return((dataGridViewJournal.Rows[r].Visible && he.EventTimeLocal.CompareTo(frm.StartTime) >= 0 && he.EventTimeLocal.CompareTo(frm.EndTime) <= 0) ? BaseUtils.CSVWriteGrid.LineStatus.OK : BaseUtils.CSVWriteGrid.LineStatus.Skip); } else { return(BaseUtils.CSVWriteGrid.LineStatus.EOF); } }; grd.GetLine += delegate(int r) { DataGridViewRow rw = dataGridViewJournal.Rows[r]; return(new Object[] { rw.Cells[0].Value, rw.Cells[2].Value, rw.Cells[3].Value }); }; grd.GetHeader += delegate(int c) { return((c < 3 && frm.IncludeHeader) ? dataGridViewJournal.Columns[c + ((c > 0) ? 1 : 0)].HeaderText : null); }; if (grd.WriteCSV(frm.Path)) { if (frm.AutoOpen) { System.Diagnostics.Process.Start(frm.Path); } } else { ExtendedControls.MessageBoxTheme.Show(this.FindForm(), "Failed to write to " + frm.Path, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } }
// second part of add history row, adds item to view. private void AddNewJournalRow(bool insert, HistoryEntry item) { string detail = ""; if (item.EventDescription.Length > 0) detail = item.EventDescription; if (item.EventDetailedInfo.Length > 0) detail += ((detail.Length > 0) ? Environment.NewLine : "") + item.EventDetailedInfo; object[] rowobj = { EDDiscoveryForm.EDDConfig.DisplayUTC ? item.EventTimeUTC : item.EventTimeLocal, "", item.EventSummary, detail }; int rownr; if (insert) { dataGridViewJournal.Rows.Insert(0, rowobj); rownr = 0; } else { dataGridViewJournal.Rows.Add(rowobj); rownr = dataGridViewJournal.Rows.Count - 1; } dataGridViewJournal.Rows[rownr].Cells[JournalHistoryColumns.HistoryTag].Tag = item; }
private async void OnNewEntry(HistoryEntry he, HistoryList hl) { last_he = he; if (last_he != null) { if (bodyRadius == null || lastradiusbody != he.WhereAmI) // try and get radius, this is cleared on target selection { StarScan.SystemNode last_sn = await discoveryform.history.StarScan.FindSystemAsync(he.System, false); // find scan if we have one JournalScan sd = last_sn?.Find(he.WhereAmI)?.ScanData; // find body scan data if present, null if not bodyRadius = sd?.nRadius; if (bodyRadius.HasValue) { lastradiusbody = he.WhereAmI; System.Diagnostics.Debug.WriteLine("Compass Radius Set " + lastradiusbody + " " + bodyRadius.Value); } } switch (he.journalEntry.EventTypeID) { case JournalTypeEnum.Screenshot: JournalScreenshot js = he.journalEntry as JournalScreenshot; latitude = js.nLatitude; longitude = js.nLongitude; altitude = js.nAltitude; break; case JournalTypeEnum.Touchdown: JournalTouchdown jt = he.journalEntry as JournalTouchdown; if (jt.PlayerControlled.HasValue && jt.PlayerControlled.Value) { latitude = jt.Latitude; longitude = jt.Longitude; altitude = 0; } break; case JournalTypeEnum.Location: JournalLocation jl = he.journalEntry as JournalLocation; latitude = jl.Latitude; longitude = jl.Longitude; altitude = null; break; case JournalTypeEnum.Liftoff: JournalLiftoff jlo = he.journalEntry as JournalLiftoff; if (jlo.PlayerControlled.HasValue && jlo.PlayerControlled.Value) { latitude = jlo.Latitude; longitude = jlo.Longitude; altitude = 0; } break; case JournalTypeEnum.LeaveBody: latitude = null; longitude = null; altitude = null; break; case JournalTypeEnum.FSDJump: // to allow us to do PopulateBookmark.. case JournalTypeEnum.CarrierJump: break; default: return; } PopulateBookmarkCombo(); DisplayCompass(); } }
private void Display(HistoryEntry he, HistoryList hl, bool selectedEntry) { ResetDefaults(); DrawSystem(he, false); }
void Process(List <JournalFSDJump> edsmlogs, DateTime logstarttime, DateTime logendtime) { // Get all of the local entries now that we have the entries from EDSM // Moved here to avoid the race that could have been causing duplicate entries // EDSM only returns FSD entries, so only look for them. Tested 27/4/2018 after the HE optimisations List <HistoryEntry> hlfsdlist = JournalEntry.GetAll(Commander.Id, logstarttime.AddDays(-1), logendtime.AddDays(1)). OfType <JournalLocOrJump>().OrderBy(je => je.EventTimeUTC). Select(je => HistoryEntry.FromJournalEntry(je, null)).ToList(); List <JournalFSDJump> toadd = new List <JournalFSDJump>(); int previdx = -1; foreach (JournalFSDJump jfsd in edsmlogs) // find out list of ones not present { int index = hlfsdlist.FindIndex(x => x.System.Name.Equals(jfsd.StarSystem, StringComparison.InvariantCultureIgnoreCase) && x.EventTimeUTC.Ticks == jfsd.EventTimeUTC.Ticks); if (index < 0) // not found, see if its around that date.. { // Look for any entries where DST may have thrown off the time foreach (var vi in hlfsdlist.Select((v, i) => new { v = v, i = i }).Where(vi => vi.v.System.Name.Equals(jfsd.StarSystem, StringComparison.InvariantCultureIgnoreCase))) { if (vi.i > previdx) { double hdiff = vi.v.EventTimeUTC.Subtract(jfsd.EventTimeUTC).TotalHours; if (hdiff >= -2 && hdiff <= 2 && hdiff == Math.Floor(hdiff)) { index = vi.i; // same system, nearly same time.. TBD check break; } } } } if (index < 0) // its not a duplicate, add to db { toadd.Add(jfsd); } else { // it is a duplicate, check if the first discovery flag is set right JournalFSDJump existingfsd = hlfsdlist[index].journalEntry as JournalFSDJump; if (existingfsd != null && existingfsd.EDSMFirstDiscover != jfsd.EDSMFirstDiscover) // if we have a FSD one, and first discover is different { existingfsd.UpdateFirstDiscover(jfsd.EDSMFirstDiscover); } previdx = index; } } if (toadd.Count > 0) // if we have any, we can add { System.Diagnostics.Debug.WriteLine($"Adding EDSM logs count {toadd.Count}"); TravelLogUnit tlu = new TravelLogUnit("EDSM\\EDSM-" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)); // need a tlu for it tlu.Type = TravelLogUnit.EDSMType; // EDSM tlu.CommanderId = EDCommander.CurrentCmdrID; tlu.Add(); // Add to Database UserDatabase.Instance.ExecuteWithDatabase(cn => { foreach (JournalFSDJump jfsd in toadd) { System.Diagnostics.Trace.WriteLine(string.Format("Add {0} {1}", jfsd.EventTimeUTC, jfsd.StarSystem)); jfsd.SetTLUCommander(tlu.ID, tlu.CommanderId.Value); // update its TLU id to the TLU made above jfsd.Add(jfsd.CreateFSDJournalEntryJson(), cn.Connection); // add it to the db with the JSON created } }); LogLine($"Retrieved {toadd.Count} log entries from EDSM, from {logstarttime.ToLocalTime().ToString()} to {logendtime.ToLocalTime().ToString()}"); OnDownloadedSystems?.Invoke(); } }
protected void AddEntry(HistoryEntry entry) { try { if (!_validEntries.Contains(entry.ItemId)) { _validEntries.Add(entry.ItemId); } else { Log.Info("HistoryCollector. ProcessEntry. Entry '{0}' was already added. Skipping.".FormatWith(entry.ItemId), this); } } catch (Exception exception) { Log.Error("HistoryCollector. Could not process entry. Action: '{0}', Item: '{1}'.".FormatWith(entry.Action, entry.ItemPath), exception); } }
private async void DrawSystem(HistoryEntry he, bool force) { StarScan.SystemNode scannode = null; var samesys = last_he?.System != null && he?.System != null && he.System.Name == last_he.System.Name; //System.Diagnostics.Debug.WriteLine("Scan grid " + samesys + " F:" + force); if (he == null) // no he, no display { last_he = he; dataGridViewScangrid.Rows.Clear(); SetControlText("No Scan".T(EDTx.NoScan)); return; } else { scannode = await discoveryform.history.StarScan.FindSystemAsync(he.System, true); // get data with EDSM if (scannode == null) // no data, clear display, clear any last_he so samesys is false next time { last_he = null; dataGridViewScangrid.Rows.Clear(); SetControlText("No Scan".T(EDTx.NoScan)); return; } if (samesys && !force) // same system, no force, no redisplay { return; } } last_he = he; // only record first row if same system var firstdisplayedrow = (dataGridViewScangrid.RowCount > 0 && samesys) ? dataGridViewScangrid.SafeFirstDisplayedScrollingRowIndex() : -1; dataGridViewScangrid.RowTemplate.MinimumHeight = Font.ScalePixels(64); // based on icon size bodysize = dataGridViewScangrid.RowTemplate.MinimumHeight; iconsize = bodysize / 4; dataGridViewScangrid.Rows.Clear(); var all_nodes = scannode.Bodies.ToList(); // flatten tree of scan nodes to prepare for listing var stars = 0; var planets = 0; var terrestrial = 0; var gasgiants = 0; var moons = 0; foreach (StarScan.ScanNode sn in all_nodes) { // define strings to be populated var bdClass = new StringBuilder(); var bdDist = new StringBuilder(); var bdDetails = new StringBuilder(); if (sn.NodeType == StarScan.ScanNodeType.ring) { // do nothing, by now } else if (sn.NodeType == StarScan.ScanNodeType.beltcluster) { if (showStructures && sn.ScanData?.BodyName != null) { if (showBelts) { bdClass.Clear(); bdClass.Append("Belt Cluster"); if (sn.ScanData.ScanType == "Detailed") { bdDetails.Append("Scanned"); } else { bdDetails.Append("No scan data available"); } if (Math.Abs(sn.ScanData.DistanceFromArrivalLS) > 0) { bdDist.AppendFormat("{0:0.00}AU ({1:0.0}ls)", sn.ScanData.DistanceFromArrivalLS / JournalScan.oneAU_LS, sn.ScanData.DistanceFromArrivalLS); } var img = global::EDDiscovery.Icons.Controls.ScanGrid_Belt; dataGridViewScangrid.Rows.Add(new object[] { null, sn.ScanData.BodyDesignationOrName, bdClass, bdDist, bdDetails }); var cur = dataGridViewScangrid.Rows[dataGridViewScangrid.Rows.Count - 1]; cur.Tag = img; cur.Cells[0].Tag = null; cur.Cells[4].Tag = cur.Cells[0].ToolTipText = cur.Cells[1].ToolTipText = cur.Cells[2].ToolTipText = cur.Cells[3].ToolTipText = cur.Cells[4].ToolTipText = sn.ScanData.DisplayString(historicmatlist: last_he.MaterialCommodity, currentmatlist: discoveryform.history.GetLast?.MaterialCommodity); } } } else { var overlays = new Overlays(); // check for null data if (sn.ScanData?.BodyName != null) { // check for body class if (sn.ScanData.IsStar) { // is a star, so populate its information field with relevant data stars++; // star class if (sn.ScanData.StarTypeText != null) { bdClass.Append(sn.ScanData.StarTypeText); } // is the main star? if (sn.ScanData.BodyName.EndsWith(" A", StringComparison.Ordinal)) { bdDist.AppendFormat("Main Star".T(EDTx.UserControlScanGrid_MainStar)); } // if not, then tell us its hierarchy leveland distance from main star else if (sn.ScanData.nSemiMajorAxis.HasValue) { if (sn.ScanData.IsStar || sn.ScanData.nSemiMajorAxis.Value > JournalScan.oneAU_m / 10) { bdDist.AppendFormat("{0:0.00}AU ({1:0.00}ls)", (sn.ScanData.nSemiMajorAxis.Value / JournalScan.oneAU_m), sn.ScanData.nSemiMajorAxis.Value / JournalScan.oneLS_m); } else { bdDist.AppendFormat("{0}km", (sn.ScanData.nSemiMajorAxis.Value / 1000).ToString("N1")); } } // display stellar bodies mass, in sols if (sn.ScanData.nStellarMass.HasValue) { bdDetails.Append("Mass".T(EDTx.UserControlScanGrid_Mass)).Append(": ").Append(sn.ScanData.nStellarMass.Value.ToString("N2")).Append(", "); } // display stellar bodies radius in sols if (sn.ScanData.nRadius.HasValue) { bdDetails.Append("Radius".T(EDTx.UserControlScanGrid_Radius)).Append(": ").Append((sn.ScanData.nRadius.Value / JournalScan.oneSolRadius_m).ToString("N2")).Append(", "); } // show the temperature if (sn.ScanData.nSurfaceTemperature.HasValue) { bdDetails.Append("Temperature".T(EDTx.UserControlScanGrid_Temperature)).Append(": ").Append((sn.ScanData.nSurfaceTemperature.Value)).Append("K."); } // habitable zone for stars - do not display for black holes. if (showStellarZones && sn.ScanData.IsStar && sn.ScanData.StarTypeID != EDStar.H) { if (showHabitable) { string hz = sn.ScanData.CircumstellarZonesString(false, JournalScan.CZPrint.CZHab); bdDetails.AppendFormat(Environment.NewLine + hz); } if (showMetalRich) { string hz = sn.ScanData.CircumstellarZonesString(false, JournalScan.CZPrint.CZMR); bdDetails.AppendFormat(Environment.NewLine + hz); } if (showWaterWorlds) { string hz = sn.ScanData.CircumstellarZonesString(false, JournalScan.CZPrint.CZWW); bdDetails.AppendFormat(Environment.NewLine + hz); } if (showEarthLike) { string hz = sn.ScanData.CircumstellarZonesString(false, JournalScan.CZPrint.CZEL); bdDetails.AppendFormat(Environment.NewLine + hz); } if (showAmmonia) { string hz = sn.ScanData.CircumstellarZonesString(false, JournalScan.CZPrint.CZAW); bdDetails.AppendFormat(Environment.NewLine + hz); } if (showIcyBodies) { string hz = sn.ScanData.CircumstellarZonesString(false, JournalScan.CZPrint.CZIP); bdDetails.AppendFormat(Environment.NewLine + hz); } } } else { // is a non-stellar body // is terraformable? If so, prepend it to the body class if (sn.ScanData.Terraformable) { bdClass.Append("Terraformable".T(EDTx.UserControlScanGrid_Terraformable)).Append(", "); } // is a planet?... if (sn.ScanData.PlanetTypeText.HasChars()) { bdClass.Append(sn.ScanData.PlanetTypeText); } planets++; // tell us the distance from the arrivals in both AU and LS if (sn.Level <= 1 && sn.NodeType == StarScan.ScanNodeType.body) { bdDist.AppendFormat("{0:0.00}AU ({1:0.0}ls)", sn.ScanData.DistanceFromArrivalLS / JournalScan.oneAU_LS, sn.ScanData.DistanceFromArrivalLS); } // ...or a moon? if (sn.Level >= 2 && sn.NodeType == StarScan.ScanNodeType.body) { if (sn.ScanData.IsPlanet) { moons++; } bdClass.Append(" ").Append("Moon".T(EDTx.UserControlScanGrid_Moon)); // moon distances from center body are measured from in SemiMajorAxis if (sn.ScanData.nSemiMajorAxis.HasValue) { bdDist.AppendFormat("{0:0.0}ls ({1:0}km)", sn.ScanData.nSemiMajorAxis.Value / JournalScan.oneLS_m, sn.ScanData.nSemiMajorAxis.Value / 1000); } } if (sn.ScanData.GasWorld) { gasgiants++; } else { terrestrial++; } // Details // display non-stellar bodies radius in earth radiuses if (sn.ScanData.nRadius.HasValue) { bdDetails.Append("Radius".T(EDTx.UserControlScanGrid_Radius)).Append(": ").Append((sn.ScanData.nRadius.Value / JournalScan.oneEarthRadius_m).ToString("N2")).Append(", "); } // show the temperature, both in K and C degrees if (sn.ScanData.nSurfaceTemperature.HasValue) { bdDetails.Append("Temperature".T(EDTx.UserControlScanGrid_Temperature)).Append(": ").Append((sn.ScanData.nSurfaceTemperature.Value).ToString("N2")).Append("K, (").Append((sn.ScanData.nSurfaceTemperature.Value - 273).ToString("N2")).Append("C)."); } // print the main atmospheric composition and pressure, if presents if (!String.IsNullOrEmpty(sn.ScanData.Atmosphere) && sn.ScanData.Atmosphere != "None") { bdDetails.Append(Environment.NewLine).Append(sn.ScanData.Atmosphere); if (sn.ScanData.nSurfacePressure.HasValue) { bdDetails.Append(", ").Append((sn.ScanData.nSurfacePressure.Value / JournalScan.oneAtmosphere_Pa).ToString("N3")).Append("Pa."); } } // tell us that a bodie is landable, and shows its gravity if (sn.ScanData.IsLandable) { var Gg = ""; if (sn.ScanData.nSurfaceGravity.HasValue) { var g = sn.ScanData.nSurfaceGravity / JournalScan.oneGee_m_s2; Gg = " (G: " + g.Value.ToString("N1") + ")"; } bdDetails.Append(Environment.NewLine).Append("Landable".T(EDTx.UserControlScanGrid_Landable)).Append(Gg).Append(". "); overlays.landable = true; } // tell us that there is some volcanic activity if (sn.ScanData.Volcanism != null) { bdDetails.Append(Environment.NewLine).Append("Geological activity".T(EDTx.UserControlScanGrid_Geologicalactivity)).Append(": ").Append(sn.ScanData.Volcanism).Append(". "); overlays.volcanism = true; } if (sn.ScanData.Mapped) { bdDetails.Append(Environment.NewLine).Append("Surface mapped".T(EDTx.UserControlScanGrid_Surfacemapped)).Append(". "); overlays.mapped = true; } // materials if (sn.ScanData.HasMaterials) { toolStripProgressBar.Visible = true; var ret = ""; foreach (KeyValuePair <string, double> mat in sn.ScanData.Materials) { var mc = MaterialCommodityData.GetByFDName(mat.Key); if (mc?.IsJumponium == true) { ret = ret.AppendPrePad(mc.Name, ", "); overlays.materials = true; } } if (ret.Length > 0 && showMaterials) { bdDetails.Append(Environment.NewLine).Append("This body contains: ".T(EDTx.UserControlScanGrid_BC)).Append(ret); } ReportJumponium(ret); } } // have some belt, ring or other special structure? if (showStructures) { if (sn.ScanData.HasRings) { for (int r = 0; r < sn.ScanData.Rings.Length; r++) { if (sn.ScanData.Rings[r].Name.EndsWith("Belt", StringComparison.Ordinal)) { if (showBelts) { // is a belt bdDetails.Append(Environment.NewLine).Append("Belt: ".T(EDTx.UserControlScanGrid_Belt)); var RingName = sn.ScanData.Rings[r].Name; bdDetails.Append(JournalScan.StarPlanetRing.DisplayStringFromRingClass(sn.ScanData.Rings[r].RingClass)).Append(" "); bdDetails.Append((sn.ScanData.Rings[r].InnerRad / JournalScan.oneLS_m).ToString("N2")).Append("ls to ").Append((sn.ScanData.Rings[r].OuterRad / JournalScan.oneLS_m).ToString("N2")).Append("ls. "); } } else { if (showRings) { // is a ring bdDetails.Append(Environment.NewLine).Append("Ring: ".T(EDTx.UserControlScanGrid_Ring)); var RingName = sn.ScanData.Rings[r].Name; bdDetails.Append(JournalScan.StarPlanetRing.DisplayStringFromRingClass(sn.ScanData.Rings[r].RingClass)).Append(" "); bdDetails.Append((sn.ScanData.Rings[r].InnerRad / JournalScan.oneLS_m).ToString("N2")).Append("ls to ").Append((sn.ScanData.Rings[r].OuterRad / JournalScan.oneLS_m).ToString("N2")).Append("ls. "); } } } } } //! for all relevant bodies: // give estimated value if (showValues) { var value = sn.ScanData.EstimatedValue; bdDetails.Append(Environment.NewLine).Append("Value".T(EDTx.UserControlScanGrid_Value)).Append(" ").Append(value.ToString("N0")); } // pick an image var img = sn.ScanData.IsStar ? sn.ScanData.GetStarTypeImage() : sn.ScanData.GetPlanetClassImage(); dataGridViewScangrid.Rows.Add(new object[] { null, sn.ScanData.BodyDesignationOrName, bdClass, bdDist, bdDetails }); var cur = dataGridViewScangrid.Rows[dataGridViewScangrid.Rows.Count - 1]; cur.Tag = img; cur.Cells[0].Tag = overlays; cur.Cells[4].Tag = cur.Cells[0].ToolTipText = cur.Cells[1].ToolTipText = cur.Cells[2].ToolTipText = cur.Cells[3].ToolTipText = cur.Cells[4].ToolTipText = sn.ScanData.DisplayString(historicmatlist: last_he.MaterialCommodity, currentmatlist: discoveryform.history.GetLast?.MaterialCommodity); } } // check if it's a green system isGreenSystem |= (hasArsenic && hasCadmium && hasCarbon && hasGermanium && hasNiobium && hasPopolonium && hasVanadium && hasYttrium); if (isGreenSystem) { toolStripProgressBar.ToolTipText = "This is a green system, as it has all existing jumponium materials available!".T(EDTx.UserControlScanGrid_GS); toolStripStatusGreen.Visible = true; } else if (!isGreenSystem) { toolStripProgressBar.ToolTipText = toolStripProgressBar.Value + " jumponium materials found in system.".T(EDTx.UserControlScanGrid_JS); } // set a meaningful title for the controller SetControlText(string.Format("Scan Summary for {0}: {1} stars; {2} planets ({3} terrestrial, {4} gas giants), {5} moons".T(EDTx.UserControlScanGrid_ScanSummaryfor), scannode.System.Name, stars, planets, terrestrial, gasgiants, moons)); if (firstdisplayedrow >= 0 && firstdisplayedrow < dataGridViewScangrid.RowCount) { dataGridViewScangrid.SafeFirstDisplayedScrollingRowIndex(firstdisplayedrow); } toolStripStatusTotalValue.Text = "~" + scannode.ScanValue(true).ToString() + " cr"; } }
internal HistoryEventArgs(HistoryEntry entry) { _historyEntry = entry; }
public int ActionRunOnEntry(HistoryEntry he, ActionEvent ev, string flagstart = null, bool now = false) //set flagstart to be the first flag of the actiondata.. { return(ActionRun(ev, he, null, flagstart, now)); }
/// <summary> /// Creates an entry into the History System. Will not be saved until SaveEntries() is called. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <param name="player"></param> /// <param name="lastPlayer"></param> /// <param name="newBlock"></param> /// <param name="lastBlock"></param> public void AddEntry(short x, short y, short z, ushort player, ushort lastPlayer, byte newBlock, byte lastBlock) { var he = new HistoryEntry { LastBlock = lastBlock, NewBlock = newBlock, Player = player, LastPlayer = lastPlayer, X = x, Y = y, Z = z, Timestamp = (int) ServerCore.GetCurrentUnixTime() }; lock (_eLock) { Entries.Add(he); } if (Entries.Count > 55000) SaveEntries(); }
private void OnTravelChange(HistoryEntry he, HistoryList hl, bool selectedEntry) { Display(he); }