private void ShowConflicts(AsmPatch patch) { List <PatchRangeConflict> conflictList = conflictPatchData.ConflictMap[patch]; foreach (PatchRangeConflict conflict in conflictList) { //PsxIso.Sectors sector = (PsxIso.Sectors)(conflict.ConflictRange.Sector); //string strSector = Enum.GetName(typeof(PsxIso.Sectors), sector); //string strSector = PatcherLib.Iso.PsxIso.GetSectorName(sector); /* * Type sectorType = (mode == FreeSpaceMode.PSP) ? typeof(PspIso.Sectors) : typeof(PsxIso.Sectors); * Enum sector = (Enum)Enum.ToObject(sectorType, conflict.ConflictRange.Sector); * string strSector = (mode == FreeSpaceMode.PSP) ? PspIso.GetSectorName((PspIso.Sectors)sector) : PsxIso.GetSectorName((PsxIso.Sectors)sector); */ string strSector = ISOHelper.GetSectorName(conflict.ConflictRange.Sector, FreeSpace.GetContext(mode)); // Patch #, Sector, Location, Conflict Location ListViewItem item = new ListViewItem(); item.Text = conflict.ConflictPatchNumber.ToString(); item.SubItems.Add(strSector); item.SubItems.Add(conflict.Range.StartOffset.ToString("X")); item.SubItems.Add(conflict.ConflictRange.StartOffset.ToString("X")); item.BackColor = conflict.IsInFreeSpace ? backColor_Conflict_FreeSpace : backColor_Conflict_NonFreeSpace; lv_Conflicts.Items.Add(item); } }
private void cmb_Events_Sector_SelectedIndexChanged(object sender, EventArgs e) { if (cmb_Events_Sector.SelectedIndex >= 0) { spinner_Events_Sector.Value = ISOHelper.GetSectorValue(((SectorPair)cmb_Events_Sector.SelectedItem).Sector); } }
public override void GET_Method_CallBack(IAsyncResult res) { try { HttpWebRequest wr = (HttpWebRequest)res.AsyncState; HttpWebResponse response = (HttpWebResponse)wr.EndGetResponse(res); StreamReader sr = new StreamReader(response.GetResponseStream()); apijson = JObject.Parse(sr.ReadToEnd()); if (apijson != null) { string response_id = (string)apijson["feed"]["author"][0]["yt$userId"]["$t"]; if (ISOHelper.WriteToFile("cache/" + response_id + ".json", apijson.ToString())) { IsolatedStorageSettings.ApplicationSettings["cache"] = true; IsolatedStorageSettings.ApplicationSettings["cache_filename"] = "cache/" + response_id + ".json"; IsolatedStorageSettings.ApplicationSettings.Save(); } } } catch (Exception ex) { Resources.ErrorLogging.Log(this.GetType().ToString(), ex.Message, "PlaylistViewmodel", string.Empty); } PopulateCollection(apijson); }
private void RefreshButton_Click(object sender, EventArgs e) { ISOHelper.DeleteDirectory("cache"); if (!loader_worker.IsBusy) { loader_worker.RunWorkerAsync(); } }
private void LogoutButton_Click(object sender, EventArgs e) { System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Remove("cache_filename"); System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Remove("refresh_token"); System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Save(); ISOHelper.DeleteDirectory("cache"); NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); }
void delvideo_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { ToggleProgressBar("Done"); ISOHelper.DeleteFile("cache\\" + plentry.Id + ".json"); if (!back_worker.IsBusy) { back_worker.RunWorkerAsync(index); } }
public static string GetModifiedSectorName(PspIso.Sectors sector) { if (sector == Sectors.PSP_GAME_SYSDIR_BOOT_BIN) { return("BOOT.BIN"); } return(ISOHelper.GetModifiedPathName(GetSectorName(sector))); }
private void PopulateCollection(JObject response) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { try { string id = ""; foreach (JObject entry in response["feed"]["entry"]) { Entry newent = new Entry(); newent.PlaylistID = plentry.Id; newent.EntryID = (string)entry["id"]["$t"]; string[] splittat = { "playlist:" }; newent.EntryID = newent.EntryID.Split(splittat, StringSplitOptions.None)[1].Split(':')[1]; newent.Id = (string)entry["media$group"]["yt$videoid"]["$t"]; newent.Title = (string)entry["title"]["$t"]; newent.ImageSource = (string)entry["media$group"]["media$thumbnail"][0]["url"]; string dura = (string)entry["media$group"]["yt$duration"]["seconds"]; newent.Duration = TimeSpan.FromSeconds(double.Parse(dura)); foreach (JObject jo in entry["link"]) { string src; if ((string)jo["type"] == "text/html" && (string)jo["rel"] == "alternate") { src = (string)jo["href"]; string[] src_split = src.Split('&'); newent.Source = src_split[0]; break; } } if (newent.Source == null) { throw new WebException("Cant get Video Address from API"); } id = newent.Id; string filename = plentry.Id + "\\" + id + ".mp3"; string offline = "Not Synced"; SolidColorBrush col = new SolidColorBrush(Colors.Red); if (ISOHelper.FileExists(filename)) { offline = "Available offline"; col.Color = Colors.Green; } newent.AvailablityColor = col; newent.Offline = offline; tracklistentry.Add(newent); } } catch (Exception ex) { ErrorLogging.Log(this.GetType().ToString(), ex.Message, "ViewModelTracklist", "probablyJSONResponse"); } }); completed = true; }
public string CreateXML(FreeSpaceMode mode) { Context context = (mode == FreeSpaceMode.PSP) ? Context.US_PSP : Context.US_PSX; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat(" <Patch name=\"{0}\">{1}", Name, Environment.NewLine); if (!string.IsNullOrEmpty(Description)) { sb.AppendFormat(" <Description> {0} </Description>{1}", Description, Environment.NewLine); } sb.Append(PatcherLib.Utilities.Utilities.CreatePatchXML(innerList, context)); foreach (VariableType variable in Variables) { int value = variable.ByteArray.ToIntLE(); System.Text.StringBuilder sbSpecific = new System.Text.StringBuilder(); int patchCount = variable.Content.Count; for (int index = 0; index < patchCount; index++) { PatchedByteArray patchedByteArray = variable.Content[index]; //string file = Enum.GetName(typeof(PatcherLib.Iso.PsxIso.Sectors), patchedByteArray.Sector); //string file = PatcherLib.Iso.PsxIso.GetSectorName(patchedByteArray.Sector); /* * Type sectorType = (mode == FreeSpaceMode.PSP) ? typeof(PatcherLib.Iso.PspIso.Sectors) : typeof(PatcherLib.Iso.PsxIso.Sectors); * Enum sector = (Enum)Enum.ToObject(sectorType, patchedByteArray.Sector); * string file = (mode == FreeSpaceMode.PSP) * ? PatcherLib.Iso.PspIso.GetSectorName((PatcherLib.Iso.PspIso.Sectors)sector) * : PatcherLib.Iso.PsxIso.GetSectorName((PatcherLib.Iso.PsxIso.Sectors)sector); */ string file = ISOHelper.GetSectorName(patchedByteArray.SectorEnum); sbSpecific.AppendFormat("{0}:{1}{2}", file, patchedByteArray.Offset.ToString("X"), ((index < (patchCount - 1)) ? "," : "")); } string strVariableReference = ""; if (variable.IsReference) { strVariableReference = String.Format(" reference=\"{0}\" operator=\"{1}\" operand=\"{2}\"", variable.Reference.Name, variable.Reference.Operand, variable.Reference.OperatorSymbol); } string strDefault = variable.IsReference ? "" : String.Format(" default=\"{0}\"", value.ToString("X")); string strSpecific = sbSpecific.ToString(); string strContent = string.IsNullOrEmpty(strSpecific) ? "symbol=\"true\"" : String.Format("specific=\"{0}\"", strSpecific); sb.AppendFormat(" <Variable name=\"{0}\" {1} bytes=\"{2}\"{3}{4} />{5}", variable.Name, strContent, variable.NumBytes, strDefault, strVariableReference, Environment.NewLine); } sb.AppendLine(" </Patch>"); return(sb.ToString()); }
void delvideo_worker_DoWork(object sender, DoWorkEventArgs e) { ToggleProgressBar("Deleting Video..."); string[] args = (String[])e.Argument; ISOHelper.DeleteFile(plentry.Id + "\\" + args[0] + ".mp3"); Delete.Video(plentry.Id, args[1]); while (!Delete.Completed) { System.Threading.Thread.Sleep(3000); } }
public static void ReadFreeSpaceXML(string xmlFilename = _xmlFilename) { if (File.Exists(xmlFilename)) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlFilename); XmlNode rootNode = xmlDoc.SelectSingleNode("//FreeSpace"); foreach (FreeSpaceMode mode in freeSpaceModes) { List <string> newRangeNames = new List <string>(); List <PatchRange> newRanges = new List <PatchRange>(); string modeName = Enum.GetName(typeof(FreeSpaceMode), mode); XmlNode parentNode = rootNode[modeName]; if (parentNode != null) { foreach (XmlNode node in parentNode.ChildNodes) { XmlAttribute attrName = node.Attributes["name"]; XmlAttribute attrSector = node.Attributes["sector"]; XmlAttribute attrStartOffset = node.Attributes["startOffset"]; XmlAttribute attrEndOffset = node.Attributes["endOffset"]; string name = attrName.InnerText; int sector = 0; string sectorText = attrSector.InnerText; Type sectorType = (mode == FreeSpaceMode.PSP) ? typeof(PspIso.Sectors) : typeof(PsxIso.Sectors); Enum sectorValue = (Enum)Enum.Parse(sectorType, sectorText); if (!int.TryParse(sectorText, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out sector)) { sector = ISOHelper.GetSectorValue(sectorValue); } uint startOffset = uint.Parse(attrStartOffset.InnerText, System.Globalization.NumberStyles.HexNumber); uint endOffset = uint.Parse(attrEndOffset.InnerText, System.Globalization.NumberStyles.HexNumber); newRangeNames.Add(name); newRanges.Add(new PatchRange(sector, startOffset, endOffset)); } } RangeNames[(int)mode] = newRangeNames.ToArray(); Ranges[(int)mode] = newRanges.ToArray(); } } }
private void clearsync_click(object sender, EventArgs e) { if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing || BackgroundAudioPlayer.Instance.PlayerState == PlayState.Paused) { BackgroundAudioPlayer.Instance.Stop(); } if (!ISOHelper.DeleteDirectory(plentry.Id)) { MessageBox.Show("Some files were locked by audio player, or do not exist"); } if (!back_worker.IsBusy) { back_worker.RunWorkerAsync(index); } }
void addvideo_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { ToggleProgressBar("Done"); ISOHelper.DeleteFile("cache\\" + plentry.Id + ".json"); if (!back_worker.IsBusy) { back_worker.RunWorkerAsync(index); } if (Add.ErrorOccured) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show("Error occured while adding video to playlist"); }); } }
void delplay_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { ToggleProgressBar("Done"); ISOHelper.DeleteFile("cache\\" + plentry.Id + ".json"); if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing || BackgroundAudioPlayer.Instance.PlayerState == PlayState.Paused) { BackgroundAudioPlayer.Instance.Stop(); } if (!ISOHelper.DeleteDirectory(plentry.Id)) { MessageBox.Show("Some files were locked by audio player, or do not exist"); } ISOHelper.DeleteDirectory("cache"); System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { NavigationService.GoBack(); }); }
public void GetApiResponse() { string filename = "cache/" + plentry.Id + ".json"; if (ISOHelper.FileExists(filename)) { apijson = JObject.Parse(ISOHelper.ReadFromFile(filename)); PopulateCollection(apijson); } else { string url = plentry.Source + "&alt=json" + "&fields=entry(id,title,link,media:group(yt:videoid,media:thumbnail,yt:duration))" + "&access_token=" + IsolatedStorageSettings.ApplicationSettings["access_token"]; GET(url); } }
private void GetApiResponse() { string filename; IsolatedStorageSettings.ApplicationSettings.TryGetValue("cache_filename", out filename); if (ISOHelper.FileExists(filename)) { apijson = JObject.Parse(ISOHelper.ReadFromFile(filename)); PopulateCollection(apijson); } else { string url = "https://gdata.youtube.com/feeds/mobile/users/default/playlists?" + "v=2&alt=json" + "&fields=author,entry(yt:playlistId,content,title,yt:countHint,updated,media:group(media:thumbnail))" + "&access_token=" + IsolatedStorageSettings.ApplicationSettings["access_token"]; GET(url); } }
public string GetFilepath(string filepath) { string dirPath = Path.Combine(Settings.EntryDirectory, ISOHelper.GetTypeString(Context)); if (!string.IsNullOrEmpty(Mod)) { string modDirPath = Path.Combine(dirPath, Mod); string modPath = Path.Combine(modDirPath, filepath); if (File.Exists(modPath)) { return(modPath); } } string path = Path.Combine(dirPath, filepath); return(path); }
void MainPage_Loaded(object sender, RoutedEventArgs e) { ToggleProgressBar("Loading..."); string filename; IsolatedStorageSettings.ApplicationSettings.TryGetValue("cache_filename", out filename); webBrowser1.IsScriptEnabled = true; if (Network.IsConnected()) { TimeSpan token_validity; DateTime request_time; int token_expires_in = 0; string refresh_token; IsolatedStorageSettings.ApplicationSettings.TryGetValue("request_time", out request_time); IsolatedStorageSettings.ApplicationSettings.TryGetValue("expires_in", out token_expires_in); IsolatedStorageSettings.ApplicationSettings.TryGetValue("refresh_token", out refresh_token); token_validity = DateTime.Now - request_time; navigate_clear = true; if (refresh_token != null && token_validity.TotalSeconds < token_expires_in) { auth.RefreshToken(); } else if (refresh_token != null) { auth.RefreshToken(); } else { webBrowser1.Navigate(new Uri(auth.getAuthURI(), UriKind.Absolute)); } } else if (ISOHelper.FileExists(filename)) { NavigationService.Navigate(new Uri("/Pages/Playlist.xaml", UriKind.Relative)); } else { MessageBox.Show("No connectivity to internet and no cache available"); ToggleProgressBar("No connectivity"); } }
public override void GET_Method_CallBack(IAsyncResult res) { try { HttpWebRequest wr = (HttpWebRequest)res.AsyncState; HttpWebResponse response = (HttpWebResponse)wr.EndGetResponse(res); StreamReader sr = new StreamReader(response.GetResponseStream()); apijson = JObject.Parse(sr.ReadToEnd()); if (apijson != null) { string filename = "cache/" + plentry.Id + ".json"; ISOHelper.WriteToFile(filename, apijson.ToString()); } } catch (Exception ex) { ErrorLogging.Log(this.GetType().ToString(), ex.Message, "ViewModelTracklist", string.Empty); } PopulateCollection(apijson); }
public static List <PatchedByteArray> GetISOPatches(EntryData entryData, Context context, DataHelper dataHelper = null) { dataHelper = dataHelper ?? new DataHelper(context); List <PatchedByteArray> patches = new List <PatchedByteArray>(); SettingsData settings = Settings.GetSettings(context); Enum battleSector = settings.BattleConditionalsSector; int battleOffset = settings.BattleConditionalsOffset; byte[] battleBytes = dataHelper.ConditionalSetsToByteArray(CommandType.BattleConditional, entryData.BattleConditionals); patches.Add(new PatchedByteArray(battleSector, battleOffset, battleBytes)); if ((settings.BattleConditionalsApplyLimitPatch) && (DataHelper.GetMaxBlocks(entryData.BattleConditionals) > 10)) { patches.Add(new PatchedByteArray(settings.BattleConditionalsLimitPatchSector, settings.BattleConditionalsLimitPatchOffset, settings.BattleConditionalsLimitPatchBytes)); } Enum worldSector = settings.WorldConditionalsSector; int worldOffset = settings.WorldConditionalsOffset; byte[] worldBytes = dataHelper.ConditionalSetsToByteArray(CommandType.WorldConditional, entryData.WorldConditionals); patches.Add(new PatchedByteArray(worldSector, worldOffset, worldBytes)); if (settings.WorldConditionalsRepoint) { byte[] patchBytes = (((uint)(ISOHelper.GetRamOffsetUnsigned(worldSector, context, true) + worldOffset))).ToBytes(); patches.Add(new PatchedByteArray(settings.WorldConditionalsPointerSector, settings.WorldConditionalsPointerOffset, patchBytes)); } Enum eventSector = settings.EventsSector; int eventOffset = settings.EventsOffset; byte[] eventBytes = dataHelper.EventsToByteArray(entryData.Events); patches.Add(new PatchedByteArray(eventSector, eventOffset, eventBytes)); return(patches); }
private void InitHelper() { MapData mapData = MapData.GetInstance(); ICoordinateHelper helper; if (mapData.ViewType == ViewType.iso) { helper = new ISOHelper(mapData.CellWidth, mapData.CellHeight); if (mapData.CellWidth % 4 != 0) { DialogManager.ShowMessageAsync(this, "地图宽度有误", "斜视角地图中,格子宽度应为4的倍数"); return; } mapData.CellHeight = mapData.CellWidth / 2; helper.Height = helper.Width / 2; } else { helper = new RectangularHelper(); helper.Width = mapData.CellWidth; helper.Height = mapData.CellHeight; } MainWindow.GetInstance().CoordinateHelper = helper; }
private void InitHelper() { GameData gameData = GameData.GetInstance(); ICoordinateHelper helper; if (gameData.ViewType == MapViewType.iso) { helper = new ISOHelper(gameData.CellWidth, gameData.CellHeight); if (gameData.CellWidth % 2 != 0) { DialogManager.ShowMessageAsync(this, "地图宽度有误", "斜视角地图中,格子宽度应为2的倍数"); return; } gameData.CellHeight = gameData.CellWidth / 2; helper.Height = helper.Width / 2; } else { helper = new RectangularHelper(); helper.Width = gameData.CellWidth; helper.Height = gameData.CellHeight; } MapEditor.GetInstance().CoordinateHelper = helper; }
void addplay_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //progressbar.IsEnabled = false; //progressbar.IsIndeterminate = false; progindicator.IsIndeterminate = false; progindicator.IsVisible = false; progindicator.Text = "Done"; if (Add.ErrorOccured) { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { System.Windows.MessageBox.Show("Could not add playlist"); }); } else { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { //System.Windows.MessageBox.Show("playlist added, please refresh playlist page to see new playlist."); ISOHelper.DeleteDirectory("cache"); NavigationService.GoBack(); }); } }
public static string CreatePatchXML(IEnumerable <PatcherLib.Datatypes.PatchedByteArray> patchedByteArrays, Datatypes.Context context, bool includePatchTag = false, bool includeRootTag = false, string name = null, string description = null) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (includeRootTag) { sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); sb.AppendLine("<Patches>"); } if ((includePatchTag) && (!string.IsNullOrEmpty(name))) { sb.AppendFormat(" <Patch name=\"{0}\">{1}", name, Environment.NewLine); if (!string.IsNullOrEmpty(description)) { sb.AppendFormat(" <Description>{0}</Description>{1}", description, Environment.NewLine); } } foreach (PatcherLib.Datatypes.PatchedByteArray patchedByteArray in patchedByteArrays) { byte[] bytes = patchedByteArray.GetBytes(); int byteCount = bytes.Length; if (byteCount > 0) { List <uint> fourByteSets = new List <uint>(GetUintArrayFromBytes(bytes, false)); //string file = PatcherLib.Iso.PsxIso.GetSectorName(patchedByteArray.Sector); /* * Type sectorType = (context == Datatypes.Context.US_PSP) ? typeof(PatcherLib.Iso.PspIso.Sectors) : typeof(PatcherLib.Iso.PsxIso.Sectors); * Enum sector = (Enum)Enum.ToObject(sectorType, patchedByteArray.Sector); * string file = (context == Datatypes.Context.US_PSP) * ? PatcherLib.Iso.PspIso.GetSectorName((PatcherLib.Iso.PspIso.Sectors)sector) * : PatcherLib.Iso.PsxIso.GetSectorName((PatcherLib.Iso.PsxIso.Sectors)sector); */ string file = ISOHelper.GetSectorName(patchedByteArray.SectorEnum); sb.AppendFormat(" <Location file=\"{0}\"{1}{2}>{3}", file, (patchedByteArray.IsSequentialOffset ? "" : String.Format(" offset=\"{0}\"", patchedByteArray.Offset.ToString("X"))), (patchedByteArray.MarkedAsData ? " mode=\"DATA\"" : ""), Environment.NewLine); foreach (uint fourByteSet in fourByteSets) { sb.AppendFormat(" {0}{1}", fourByteSet.ToString("X8"), Environment.NewLine); } int remainingBytes = byteCount % 4; if (remainingBytes > 0) { int remainingBytesIndex = byteCount - remainingBytes; System.Text.StringBuilder sbRemainingBytes = new System.Text.StringBuilder(remainingBytes * 2); for (int index = remainingBytesIndex; index < byteCount; index++) { sbRemainingBytes.Append(bytes[index].ToString("X2")); } sb.AppendFormat(" {0}{1}", sbRemainingBytes.ToString(), Environment.NewLine); } sb.AppendLine(" </Location>"); } } if (includePatchTag) { sb.AppendLine(" </Patch>"); } if (includeRootTag) { sb.AppendLine("</Patches>"); } return(sb.ToString()); }
public static string GetModifiedFileName(FFTPack.Files file) { return(ISOHelper.GetModifiedPathName(GetFileName(file))); }
public static SettingsData LoadSettings(XmlNode settingsNode, Context context) { SettingsData data = new SettingsData(); data.Context = context; PropertyInfo[] properties = typeof(SettingsData).GetProperties(); foreach (PropertyInfo property in properties) { Type type = property.PropertyType; string xpath = "add[@key='" + property.Name + "']"; XmlNode node = settingsNode.SelectSingleNode(xpath); if (node != null) { string strValue = node.Attributes["value"].InnerText; object value = 0; bool isSet = true; if (type == typeof(string)) { if (property.Name.ToLower().Trim().StartsWith("filepath")) { value = data.GetFilepath(strValue); } else { value = strValue; } } else if (type == typeof(int)) { value = Utilities.ParseInt(strValue); } else if (type == typeof(bool)) { value = Utilities.ParseBool(strValue); } else if (type == typeof(byte[])) { value = Utilities.GetBytesFromHexString(strValue.Replace("0x", "")); } else if (type == typeof(Enum)) { value = ISOHelper.GetSector(strValue, context); } else { isSet = false; } if (isSet) { property.SetValue(data, value, null); } } } data.TotalEventSize = data.EventSize * data.NumEvents; data.WorldConditionalsPointerRAMLocation = ISOHelper.GetRamOffset(data.WorldConditionalsPointerSector, context) + data.WorldConditionalsPointerOffset; data.BattleConditionalsLimitPatchRAMLocation = ISOHelper.GetRamOffset(data.BattleConditionalsLimitPatchSector, context) + data.BattleConditionalsLimitPatchOffset; data.ScenariosRAMLocation = ISOHelper.GetRamOffset(data.ScenariosSector, context) + data.ScenariosOffset; data.WorldConditionalsCalcRAMLocation = ISOHelper.GetRamOffset(data.WorldConditionalsSector, context) + data.WorldConditionalsOffset; return(data); }
private void SetSectorDefault(Enum sector, NumericUpDown spinner, ComboBox comboBox) { spinner.Value = ISOHelper.GetSectorValue(sector); SetSectorComboBoxValue(sector, comboBox); }
private void DoOfflineSync() { if (App.GlobalOfflineSync.SOURCES.Count > 0) { proindicator.IsVisible = true; proindicator.Text = "Download Failed. Already in progress"; return; } //OfflineSyncExt.DestinationInfo dinfo = new FileDownloader.DestinationInfo(); using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication()) { if (!iso.DirectoryExists(plentry.Id)) { iso.CreateDirectory(plentry.Id); } } int select = 0; if (listBox1.SelectedIndex > -1) { select = listBox1.SelectedIndex; } for (int i = 0; i < viewmodel.tracklistentry.Count; i++) { if (select == viewmodel.tracklistentry.Count) { select = 0; } var listEntry = viewmodel.tracklistentry[select]; string filename = plentry.Id + "\\" + listEntry.Id + ".mp3"; if (ISOHelper.FileExists(filename)) { select++; continue; } //dinfo.Title = listEntry.Title; //dinfo.Source = listEntry.Source; //dinfo.Destination = filename; App.GlobalOfflineSync.SOURCES.Add(listEntry); select++; } try { if (App.GlobalOfflineSync.SOURCES.Count > 0) { App.GlobalOfflineSync.Cancelled = false; App.GlobalOfflineSync.Next(); } else { System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { proindicator.IsVisible = true; proindicator.Text = "Sync Completed."; }); } } catch (Exception e) { //ErrorLogging.Log(e.Message); ErrorLogging.Log(this.GetType().ToString(), e.Message, "TracklistSyncError", string.Empty); } }
/// <summary> /// 绘制网格 /// </summary> public static void DrawNet(int startRow, int startCol, int rows, int cols, double cellWidth, double cellHeight, int canvasWidth, int canvasHeight, Canvas canvas, bool isISO, out ICoordinateHelper coordinateHelper) { List<LinePoint> points = new List<LinePoint>(); //Point topPoint; if (isISO) { double totalWidth = (rows + cols) * cellWidth / 2; double totalHeight = totalWidth / 2; coordinateHelper = new ISOHelper(cellWidth, cellHeight); coordinateHelper.TopPoint = new Point(canvasWidth / 2 - (totalWidth - cellWidth * rows) / 2, (int)Math.Floor((canvasHeight - totalHeight) * 0.5)); double endX = cols * cellWidth / 2; double endY = endX / 2; Point p; for (int row = 0; row <= rows; row++) { p = new Point(coordinateHelper.TopPoint.X - cellWidth / 2 * row, coordinateHelper.TopPoint.Y + cellHeight / 2 * row); points.Add(new LinePoint() { StartPoint = p, EndPoint = p + new Vector(endX, endY) }); } endX = rows * cellWidth / 2; endY = endX / 2; for (int col = 0; col <= cols; col++) { p = new Point(coordinateHelper.TopPoint.X + cellWidth / 2 * col, coordinateHelper.TopPoint.Y + cellHeight / 2 * col); points.Add(new LinePoint() { StartPoint = p, EndPoint = new Point(p.X - endX, p.Y + endY) }); } } else { double totalWidth = cellWidth * cols; double totalHeight = cellHeight * rows; double startX = 0; double startY = 0; startX = (canvasWidth - totalWidth) / 2; startY = (canvasHeight - totalHeight) / 2; coordinateHelper = new RectangularHelper() { Width = cellWidth, Height = cellHeight }; coordinateHelper.TopPoint = new Point(startX, startY); Point index = coordinateHelper.GetItemIndex(new Point(startX, startY)); index = coordinateHelper.GetItemPos((int)index.X, (int)index.Y); startX = (int)index.X; startY = (int)index.Y; for (int row = 0; row <= rows; row++) { points.Add(new LinePoint() { StartPoint = new Point(startX, startY + row * cellHeight), EndPoint = new Point(startX + cols * cellWidth, startY + row * cellHeight) }); } for (int col = 0; col <= cols; col++) { points.Add(new LinePoint() { StartPoint = new Point(startX + col * cellWidth, startY), EndPoint = new Point(startX + col * cellWidth, startY + rows * cellHeight) }); } } Draw(canvas, points, Brushes.Black); }
private static GetPatchResult GetPatch(XmlNode node, string xmlFileName, ASMEncodingUtility asmUtility, List <VariableType> variables) { KeyValuePair <string, string> nameDesc = GetPatchNameAndDescription(node); bool hideInDefault = false; XmlAttribute attrHideInDefault = node.Attributes["hideInDefault"]; if (attrHideInDefault != null) { if (attrHideInDefault.InnerText.ToLower().Trim() == "true") { hideInDefault = true; } } bool isHidden = false; XmlAttribute attrIsHidden = node.Attributes["hidden"]; if (attrIsHidden != null) { if (attrIsHidden.InnerText.ToLower().Trim() == "true") { isHidden = true; } } bool hasDefaultSector = false; //PsxIso.Sectors defaultSector = (PsxIso.Sectors)0; Context context = (asmUtility.EncodingMode == ASMEncodingMode.PSP) ? Context.US_PSP : Context.US_PSX; Type sectorType = ISOHelper.GetSectorType(context); Enum defaultSector = ISOHelper.GetSector(0, context); // (Enum)Enum.ToObject(sectorType, 0); XmlAttribute attrDefaultFile = node.Attributes["file"]; XmlAttribute attrDefaultSector = node.Attributes["sector"]; if (attrDefaultFile != null) { //defaultSector = (PsxIso.Sectors)Enum.Parse(typeof(PsxIso.Sectors), attrDefaultFile.InnerText); //defaultSector = (Enum)Enum.Parse(sectorType, attrDefaultFile.InnerText); defaultSector = ISOHelper.GetSector(attrDefaultFile.InnerText, context); hasDefaultSector = true; } else if (attrDefaultSector != null) { //defaultSector = (PsxIso.Sectors)Int32.Parse(attrDefaultSector.InnerText, System.Globalization.NumberStyles.HexNumber); defaultSector = ISOHelper.GetSectorHex(attrDefaultSector.InnerText, context); hasDefaultSector = true; } XmlNodeList currentLocs = node.SelectNodes("Location"); List <PatchedByteArray> patches = new List <PatchedByteArray>(currentLocs.Count); StringBuilder sbOuterErrorText = new StringBuilder(); Dictionary <PatchedByteArray, string> replaceLabelsContentMap = new Dictionary <PatchedByteArray, string>(); foreach (XmlNode location in currentLocs) { //UInt32 offset = UInt32.Parse( location.Attributes["offset"].InnerText, System.Globalization.NumberStyles.HexNumber ); XmlAttribute offsetAttribute = location.Attributes["offset"]; XmlAttribute fileAttribute = location.Attributes["file"]; XmlAttribute sectorAttribute = location.Attributes["sector"]; XmlAttribute modeAttribute = location.Attributes["mode"]; XmlAttribute offsetModeAttribute = location.Attributes["offsetMode"]; XmlAttribute inputFileAttribute = location.Attributes["inputFile"]; XmlAttribute replaceLabelsAttribute = location.Attributes["replaceLabels"]; XmlAttribute attrLabel = location.Attributes["label"]; XmlAttribute attrSpecific = location.Attributes["specific"]; XmlAttribute attrMovable = location.Attributes["movable"]; XmlAttribute attrAlign = location.Attributes["align"]; XmlAttribute attrStatic = location.Attributes["static"]; string strOffsetAttr = (offsetAttribute != null) ? offsetAttribute.InnerText : ""; string[] strOffsets = strOffsetAttr.Replace(" ", "").Split(','); bool ignoreOffsetMode = false; bool isSpecific = false; bool isSequentialOffset = false; List <SpecificLocation> specifics = FillSpecificAttributeData(attrSpecific, defaultSector); bool isAsmMode = false; bool markedAsData = false; if (modeAttribute != null) { string modeAttributeText = modeAttribute.InnerText.ToLower().Trim(); if (modeAttributeText == "asm") { isAsmMode = true; } else if (modeAttributeText == "data") { markedAsData = true; } } int align = 0; if (attrAlign != null) { Int32.TryParse(sectorAttribute.InnerText, out align); if (align < 0) { align = 0; } } else if (isAsmMode) { align = 4; } if (specifics.Count > 0) { isSpecific = true; List <string> newStrOffsets = new List <string>(specifics.Count); foreach (SpecificLocation specific in specifics) { newStrOffsets.Add(specific.OffsetString); } strOffsets = newStrOffsets.ToArray(); } else if ((string.IsNullOrEmpty(strOffsetAttr)) && (patches.Count > 0)) { // No offset defined -- offset is (last patch offset) + (last patch size) PatchedByteArray lastPatchedByteArray = patches[patches.Count - 1]; long offset = lastPatchedByteArray.Offset + lastPatchedByteArray.GetBytes().Length; ignoreOffsetMode = true; isSequentialOffset = true; // Advance offset to match up with alignment, if necessary if (align > 0) { int offsetAlign = (int)(offset % align); if (offsetAlign > 0) { offset += (align - offsetAlign); isSequentialOffset = false; } } string strOffset = offset.ToString("X"); strOffsets = new string[1] { strOffset }; } //PsxIso.Sectors sector = (PsxIso.Sectors)0; Enum sector = ISOHelper.GetSector(0, context); // (Enum)Enum.ToObject(sectorType, 0); if (isSpecific) { sector = specifics[0].Sector; } else if (fileAttribute != null) { //sector = (PsxIso.Sectors)Enum.Parse( typeof( PsxIso.Sectors ), fileAttribute.InnerText ); //sector = (Enum)Enum.Parse( sectorType, fileAttribute.InnerText ); sector = ISOHelper.GetSector(fileAttribute.InnerText, context); } else if (sectorAttribute != null) { //sector = (PsxIso.Sectors)Int32.Parse( sectorAttribute.InnerText, System.Globalization.NumberStyles.HexNumber ); //sector = (Enum)Enum.ToObject(sectorType, Int32.Parse(sectorAttribute.InnerText, System.Globalization.NumberStyles.HexNumber)); sector = ISOHelper.GetSectorHex(sectorAttribute.InnerText, context); } else if (hasDefaultSector) { sector = defaultSector; } else if (patches.Count > 0) { //sector = (PsxIso.Sectors)(patches[patches.Count - 1].Sector); //sector = (Enum)Enum.ToObject(sectorType, patches[patches.Count - 1].Sector); sector = patches[patches.Count - 1].SectorEnum; } else { sbOuterErrorText.AppendLine("Error in patch XML: Invalid file/sector!"); } bool isRamOffset = false; if ((!ignoreOffsetMode) && (offsetModeAttribute != null)) { if (offsetModeAttribute.InnerText.ToLower().Trim() == "ram") { isRamOffset = true; } } string content = location.InnerText; if (inputFileAttribute != null) { try { string strMode = Enum.GetName(typeof(ASMEncodingMode), asmUtility.EncodingMode); string readPath = Path.Combine("Include", inputFileAttribute.InnerText); FileInfo fileInfo = new FileInfo(xmlFileName); readPath = Path.Combine(fileInfo.DirectoryName, readPath); using (StreamReader streamReader = new StreamReader(readPath, Encoding.UTF8)) { content = streamReader.ReadToEnd(); } } catch (Exception) { string readPath = inputFileAttribute.InnerText; using (StreamReader streamReader = new StreamReader(readPath, Encoding.UTF8)) { content = streamReader.ReadToEnd(); } } } bool replaceLabels = false; if (replaceLabelsAttribute != null) { if (replaceLabelsAttribute.InnerText.ToLower().Trim() == "true") { replaceLabels = true; } } if (replaceLabels) { StringBuilder sbLabels = new StringBuilder(); foreach (PatchedByteArray currentPatchedByteArray in patches) { if (!string.IsNullOrEmpty(currentPatchedByteArray.Label)) { sbLabels.Append(String.Format(".label @{0}, {1}{2}", currentPatchedByteArray.Label, currentPatchedByteArray.RamOffset, Environment.NewLine)); } } asmUtility.EncodeASM(sbLabels.ToString(), 0); content = asmUtility.ReplaceLabelsInHex(content, true, true); } string label = ""; if (attrLabel != null) { label = attrLabel.InnerText.Replace(" ", ""); } bool isMoveSimple = isAsmMode; if (attrMovable != null) { bool.TryParse(attrMovable.InnerText, out isMoveSimple); } bool isStatic = false; if (attrStatic != null) { bool.TryParse(attrStatic.InnerText, out isStatic); } int ftrOffset = ISOHelper.GetFileToRamOffset(sector, context); int offsetIndex = 0; foreach (string strOffset in strOffsets) { UInt32 offset = UInt32.Parse(strOffset, System.Globalization.NumberStyles.HexNumber); UInt32 ramOffset = offset; UInt32 fileOffset = offset; if (ftrOffset >= 0) { try { if (isRamOffset) { fileOffset -= (UInt32)ftrOffset; } else { ramOffset += (UInt32)ftrOffset; } } catch (Exception) { } } if (context == Context.US_PSX) { ramOffset = ramOffset | PsxIso.KSeg0Mask; } byte[] bytes; string errorText = ""; if (isAsmMode) { string encodeContent = content; StringBuilder sbPrefix = new StringBuilder(); foreach (PatchedByteArray currentPatchedByteArray in patches) { if (!string.IsNullOrEmpty(currentPatchedByteArray.Label)) { sbPrefix.Append(String.Format(".label @{0}, {1}{2}", currentPatchedByteArray.Label, currentPatchedByteArray.RamOffset, Environment.NewLine)); } } foreach (VariableType variable in variables) { sbPrefix.Append(String.Format(".eqv %{0}, {1}{2}", ASMStringHelper.RemoveSpaces(variable.Name).Replace(",", ""), PatcherLib.Utilities.Utilities.GetUnsignedByteArrayValue_LittleEndian(variable.ByteArray), Environment.NewLine)); } encodeContent = sbPrefix.ToString() + content; ASMEncoderResult result = asmUtility.EncodeASM(encodeContent, ramOffset, true); bytes = result.EncodedBytes; errorText = result.ErrorText; } else { AsmPatch.GetBytesResult result = AsmPatch.GetBytes(content, ramOffset, variables); bytes = result.Bytes; errorText = result.ErrorMessage; } /* * bool isCheckedAsm = false; * if (!markedAsData) * { * ASMCheckResult checkResult = asmUtility.CheckASMFromBytes(bytes, ramOffset, true, false, new HashSet<ASMCheckCondition>() { * ASMCheckCondition.LoadDelay, * ASMCheckCondition.UnalignedOffset, * ASMCheckCondition.MultCountdown, * ASMCheckCondition.StackPointerOffset4, * ASMCheckCondition.BranchInBranchDelaySlot * }); * * if (checkResult.IsASM) * { * isCheckedAsm = true; * if (!string.IsNullOrEmpty(checkResult.ErrorText)) * { * errorText += checkResult.ErrorText; * } * } * } */ //if (!string.IsNullOrEmpty(errorText)) // sbOuterErrorText.Append(errorText); PatchedByteArray patchedByteArray = new PatchedByteArray(sector, fileOffset, bytes); patchedByteArray.IsAsm = isAsmMode; patchedByteArray.MarkedAsData = markedAsData; patchedByteArray.IsCheckedAsm = false; // isCheckedAsm; patchedByteArray.IsSequentialOffset = isSequentialOffset; patchedByteArray.IsMoveSimple = isMoveSimple; //patchedByteArray.AsmText = isAsmMode ? content : ""; patchedByteArray.Text = content; patchedByteArray.RamOffset = ramOffset; patchedByteArray.ErrorText = errorText; patchedByteArray.Label = label; patchedByteArray.IsStatic = isStatic; if (replaceLabels) { replaceLabelsContentMap.Add(patchedByteArray, content); } patches.Add(patchedByteArray); offsetIndex++; if (offsetIndex < strOffsets.Length) { if (isSpecific) { sector = specifics[offsetIndex].Sector; ftrOffset = ISOHelper.GetFileToRamOffset(sector, context); } } } } StringBuilder sbEncodePrefix = new StringBuilder(); foreach (PatchedByteArray currentPatchedByteArray in patches) { if (!string.IsNullOrEmpty(currentPatchedByteArray.Label)) { sbEncodePrefix.Append(String.Format(".label @{0}, {1}{2}", currentPatchedByteArray.Label, currentPatchedByteArray.RamOffset, Environment.NewLine)); } } foreach (VariableType variable in variables) { sbEncodePrefix.Append(String.Format(".eqv %{0}, {1}{2}", ASMStringHelper.RemoveSpaces(variable.Name).Replace(",", ""), PatcherLib.Utilities.Utilities.GetUnsignedByteArrayValue_LittleEndian(variable.ByteArray), Environment.NewLine)); } string strEncodePrefix = sbEncodePrefix.ToString(); asmUtility.EncodeASM(strEncodePrefix, 0); foreach (PatchedByteArray patchedByteArray in patches) { string errorText = string.Empty; string replaceLabelsContent; if (replaceLabelsContentMap.TryGetValue(patchedByteArray, out replaceLabelsContent)) { if (!string.IsNullOrEmpty(replaceLabelsContent)) { AsmPatch.GetBytesResult result = AsmPatch.GetBytes(asmUtility.ReplaceLabelsInHex(replaceLabelsContent, true, false), (uint)patchedByteArray.RamOffset, variables); patchedByteArray.SetBytes(result.Bytes); errorText += result.ErrorMessage; } } if (patchedByteArray.IsAsm) { string encodeContent = strEncodePrefix + patchedByteArray.Text; ASMEncoderResult result = asmUtility.EncodeASM(encodeContent, (uint)patchedByteArray.RamOffset); patchedByteArray.SetBytes(result.EncodedBytes); errorText += result.ErrorText; } if (!patchedByteArray.MarkedAsData) { HashSet <ASMCheckCondition> checkConditions = new HashSet <ASMCheckCondition>() { ASMCheckCondition.LoadDelay, ASMCheckCondition.UnalignedOffset, ASMCheckCondition.MultCountdown, ASMCheckCondition.StackPointerOffset4, ASMCheckCondition.BranchInBranchDelaySlot }; if (asmUtility.EncodingMode == ASMEncodingMode.PSP) { checkConditions.Remove(ASMCheckCondition.LoadDelay); } ASMCheckResult checkResult = asmUtility.CheckASMFromBytes(patchedByteArray.GetBytes(), (uint)patchedByteArray.RamOffset, true, false, checkConditions); if (checkResult.IsASM) { patchedByteArray.IsCheckedAsm = true; if (!string.IsNullOrEmpty(checkResult.ErrorText)) { errorText += checkResult.ErrorText; } } } if (!string.IsNullOrEmpty(errorText)) { sbOuterErrorText.Append(errorText); } } currentLocs = node.SelectNodes("STRLocation"); foreach (XmlNode location in currentLocs) { XmlAttribute fileAttribute = location.Attributes["file"]; XmlAttribute sectorAttribute = location.Attributes["sector"]; //PsxIso.Sectors sector = (PsxIso.Sectors)0; Enum sector = ISOHelper.GetSector(0, context); // (Enum)Enum.ToObject(sectorType, 0); if (fileAttribute != null) { //sector = (PsxIso.Sectors)Enum.Parse( typeof( PsxIso.Sectors ), fileAttribute.InnerText ); //sector = (Enum)Enum.Parse(sectorType, fileAttribute.InnerText); sector = ISOHelper.GetSector(fileAttribute.InnerText, context); } else if (sectorAttribute != null) { //sector = (PsxIso.Sectors)Int32.Parse( sectorAttribute.InnerText, System.Globalization.NumberStyles.HexNumber ); //sector = (Enum)Enum.ToObject(sectorType, Int32.Parse(sectorAttribute.InnerText, System.Globalization.NumberStyles.HexNumber)); sector = ISOHelper.GetSectorHex(sectorAttribute.InnerText, context); } else { throw new Exception(); } string filename = location.Attributes["input"].InnerText; filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(xmlFileName), filename); patches.Add(new STRPatchedByteArray(sector, filename)); } return(new GetPatchResult(nameDesc.Key, nameDesc.Value, patches.AsReadOnly(), hideInDefault, isHidden, sbOuterErrorText.ToString())); }
public static IList <AsmPatch> GetPatches(XmlNode rootNode, string xmlFilename, ASMEncodingUtility asmUtility) { bool rootHideInDefault = false; XmlAttribute attrHideInDefault = rootNode.Attributes["hideInDefault"]; if (attrHideInDefault != null) { rootHideInDefault = (attrHideInDefault.InnerText.ToLower().Trim() == "true"); } bool rootIsHidden = false; XmlAttribute attrIsHidden = rootNode.Attributes["hidden"]; if (attrIsHidden != null) { rootIsHidden = (attrIsHidden.InnerText.ToLower().Trim() == "true"); } string shortXmlFilename = xmlFilename.Substring(xmlFilename.LastIndexOf("\\") + 1); XmlNodeList patchNodes = rootNode.SelectNodes("Patch"); List <AsmPatch> result = new List <AsmPatch>(patchNodes.Count); Context context = (asmUtility.EncodingMode == ASMEncodingMode.PSP) ? Context.US_PSP : Context.US_PSX; Type sectorType = ISOHelper.GetSectorType(context); Enum defaultSector = ISOHelper.GetSector(0, context); foreach (XmlNode node in patchNodes) { XmlAttribute ignoreNode = node.Attributes["ignore"]; if (ignoreNode != null && Boolean.Parse(ignoreNode.InnerText)) { continue; } bool hasDefaultSector = false; //PsxIso.Sectors defaultSector = (PsxIso.Sectors)0; //Enum defaultSector = (Enum)Enum.ToObject(sectorType, 0); XmlAttribute attrDefaultFile = node.Attributes["file"]; XmlAttribute attrDefaultSector = node.Attributes["sector"]; if (attrDefaultFile != null) { //defaultSector = (PsxIso.Sectors)Enum.Parse(typeof(PsxIso.Sectors), attrDefaultFile.InnerText); //defaultSector = (Enum)Enum.Parse(sectorType, attrDefaultFile.InnerText); defaultSector = ISOHelper.GetSector(attrDefaultFile.InnerText, context); hasDefaultSector = true; } else if (attrDefaultSector != null) { //defaultSector = (PsxIso.Sectors)Int32.Parse(attrDefaultSector.InnerText, System.Globalization.NumberStyles.HexNumber); //defaultSector = (Enum)Enum.ToObject(sectorType, Int32.Parse(attrDefaultSector.InnerText, System.Globalization.NumberStyles.HexNumber)); defaultSector = ISOHelper.GetSectorHex(attrDefaultSector.InnerText, context); hasDefaultSector = true; } StringBuilder sbPatchErrorText = new StringBuilder(); List <VariableType> variables = new List <VariableType>(); List <PatchedByteArray> includePatches = new List <PatchedByteArray>(); XmlNodeList includeNodes = node.SelectNodes("Include"); foreach (XmlNode includeNode in includeNodes) { XmlAttribute attrPatch = includeNode.Attributes["patch"]; if (attrPatch != null) { string patchName = attrPatch.InnerText.ToLower().Trim(); int foundPatchCount = 0; foreach (AsmPatch currentAsmPatch in result) { if (currentAsmPatch.Name.ToLower().Trim().Equals(patchName)) { foreach (VariableType variable in currentAsmPatch.Variables) { variables.Add(variable.Copy()); } for (int index = 0; index < currentAsmPatch.NonVariableCount; index++) { includePatches.Add(currentAsmPatch[index].Copy()); } foundPatchCount++; } } if (foundPatchCount == 0) { sbPatchErrorText.AppendLine("Error in patch XML: Missing dependent patch \"" + attrPatch.InnerText + "\"!"); } } } foreach (XmlNode varNode in node.SelectNodes("Variable")) { XmlAttribute numBytesAttr = varNode.Attributes["bytes"]; string strNumBytes = (numBytesAttr == null) ? "1" : numBytesAttr.InnerText; byte numBytes = (byte)(UInt32.Parse(strNumBytes) & 0xff); string varName = varNode.Attributes["name"].InnerText; XmlAttribute fileAttribute = varNode.Attributes["file"]; XmlAttribute sectorAttribute = varNode.Attributes["sector"]; XmlAttribute attrSpecific = varNode.Attributes["specific"]; XmlAttribute attrAlign = varNode.Attributes["align"]; //PsxIso.Sectors varSec = (PsxIso.Sectors)Enum.Parse( typeof( PsxIso.Sectors ), varNode.Attributes["file"].InnerText ); //UInt32 varOffset = UInt32.Parse( varNode.Attributes["offset"].InnerText, System.Globalization.NumberStyles.HexNumber ); //string strOffsetAttr = varNode.Attributes["offset"].InnerText; XmlAttribute offsetAttribute = varNode.Attributes["offset"]; string strOffsetAttr = (offsetAttribute != null) ? offsetAttribute.InnerText : ""; string[] strOffsets = strOffsetAttr.Replace(" ", "").Split(','); bool ignoreOffsetMode = false; bool isSpecific = false; List <SpecificLocation> specifics = FillSpecificAttributeData(attrSpecific, defaultSector); int align = 0; if (attrAlign != null) { Int32.TryParse(sectorAttribute.InnerText, out align); if (align < 0) { align = 0; } } XmlAttribute symbolAttribute = varNode.Attributes["symbol"]; bool isSymbol = (symbolAttribute != null) && PatcherLib.Utilities.Utilities.ParseBool(symbolAttribute.InnerText); if (isSymbol) { strOffsets = new string[0]; } else if (specifics.Count > 0) { isSpecific = true; List <string> newStrOffsets = new List <string>(specifics.Count); foreach (SpecificLocation specific in specifics) { newStrOffsets.Add(specific.OffsetString); } strOffsets = newStrOffsets.ToArray(); } else if ((string.IsNullOrEmpty(strOffsetAttr)) && (variables.Count > 0) && (variables[variables.Count - 1].Content.Count > 0)) { // No offset defined -- offset is (last patch offset) + (last patch size) int lastIndex = variables[variables.Count - 1].Content.Count - 1; PatchedByteArray lastPatchedByteArray = variables[variables.Count - 1].Content[lastIndex]; long offset = lastPatchedByteArray.Offset + lastPatchedByteArray.GetBytes().Length; string strOffset = offset.ToString("X"); strOffsets = new string[1] { strOffset }; ignoreOffsetMode = true; // Advance offset to match up with alignment, if necessary if (align > 0) { int offsetAlign = (int)(offset % align); if (offsetAlign > 0) { offset += (align - offsetAlign); } } } //PsxIso.Sectors sector = (PsxIso.Sectors)0; Enum sector = ISOHelper.GetSector(0, context); // (Enum)Enum.ToObject(sectorType, 0); if (isSpecific) { sector = specifics[0].Sector; } else if (fileAttribute != null) { //sector = (PsxIso.Sectors)Enum.Parse(typeof(PsxIso.Sectors), fileAttribute.InnerText); //sector = (Enum)Enum.Parse(sectorType, fileAttribute.InnerText); sector = ISOHelper.GetSector(fileAttribute.InnerText, context); } else if (sectorAttribute != null) { //sector = (PsxIso.Sectors)Int32.Parse(sectorAttribute.InnerText, System.Globalization.NumberStyles.HexNumber); //sector = (Enum)Enum.ToObject(sectorType, Int32.Parse(sectorAttribute.InnerText, System.Globalization.NumberStyles.HexNumber)); sector = ISOHelper.GetSectorHex(sectorAttribute.InnerText, context); } else if (hasDefaultSector) { sector = defaultSector; } else if ((variables.Count > 0) && (variables[variables.Count - 1].Content.Count > 0)) { int lastIndex = variables[variables.Count - 1].Content.Count - 1; //sector = (PsxIso.Sectors)(variables[variables.Count - 1].Content[lastIndex].Sector); //sector = (Enum)Enum.ToObject(sectorType, variables[variables.Count - 1].Content[lastIndex].Sector); sector = variables[variables.Count - 1].Content[lastIndex].SectorEnum; } else if (!isSymbol) { sbPatchErrorText.AppendLine("Error in patch XML: Invalid file/sector!"); } XmlAttribute offsetModeAttribute = varNode.Attributes["offsetMode"]; bool isRamOffset = false; if ((!ignoreOffsetMode) && (offsetModeAttribute != null)) { if (offsetModeAttribute.InnerText.ToLower().Trim() == "ram") { isRamOffset = true; } } int ftrOffset = ISOHelper.GetFileToRamOffset(sector, context); XmlAttribute defaultAttr = varNode.Attributes["default"]; Byte[] byteArray = new Byte[numBytes]; UInt32 def = 0; if (defaultAttr != null) { def = UInt32.Parse(defaultAttr.InnerText, System.Globalization.NumberStyles.HexNumber); for (int i = 0; i < numBytes; i++) { byteArray[i] = (Byte)((def >> (i * 8)) & 0xff); } } List <PatchedByteArray> patchedByteArrayList = new List <PatchedByteArray>(); int offsetIndex = 0; foreach (string strOffset in strOffsets) { UInt32 offset = UInt32.Parse(strOffset, System.Globalization.NumberStyles.HexNumber); //UInt32 ramOffset = offset; UInt32 fileOffset = offset; if (ftrOffset >= 0) { try { if (isRamOffset) { fileOffset -= (UInt32)ftrOffset; } //else // ramOffset += (UInt32)ftrOffset; } catch (Exception) { } } //ramOffset = ramOffset | PsxIso.KSeg0Mask; // KSEG0 patchedByteArrayList.Add(new PatchedByteArray(sector, fileOffset, byteArray)); offsetIndex++; if (offsetIndex < strOffsets.Length) { if (isSpecific) { sector = specifics[offsetIndex].Sector; ftrOffset = ISOHelper.GetFileToRamOffset(sector, context); } } } bool isReference = false; string referenceName = ""; string referenceOperatorSymbol = ""; uint referenceOperand = 0; XmlAttribute attrReference = varNode.Attributes["reference"]; XmlAttribute attrOperator = varNode.Attributes["operator"]; XmlAttribute attrOperand = varNode.Attributes["operand"]; if (attrReference != null) { isReference = true; referenceName = attrReference.InnerText; referenceOperatorSymbol = (attrOperator != null) ? attrOperator.InnerText : ""; if (attrOperand != null) { //UInt32.Parse(defaultAttr.InnerText, System.Globalization.NumberStyles.HexNumber); uint.TryParse(attrOperand.InnerText, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.CurrentCulture, out referenceOperand); } } List <VariableType.VariablePreset> presetValueList = new List <VariableType.VariablePreset>(); XmlNodeList presetNodeList = varNode.SelectNodes("Preset"); string presetKey = null; XmlAttribute attrPreset = varNode.Attributes["preset"]; if (attrPreset != null) { presetKey = attrPreset.InnerText; if (!string.IsNullOrEmpty(presetKey)) { presetValueList = VariableType.VariablePreset.TypeMap[presetKey]; } } else if (presetNodeList != null) { foreach (XmlNode presetNode in presetNodeList) { XmlAttribute attrName = presetNode.Attributes["name"]; XmlAttribute attrValue = presetNode.Attributes["value"]; XmlAttribute attrModify = presetNode.Attributes["modify"]; UInt32 value = 0; byte[] valueBytes = new Byte[numBytes]; if (attrValue != null) { UInt32.TryParse(attrValue.InnerText, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.CurrentCulture, out value); for (int i = 0; i < numBytes; i++) { valueBytes[i] = (byte)((value >> (i * 8)) & 0xff); } } bool isModifiable = false; if (attrModify != null) { bool.TryParse(attrModify.InnerText, out isModifiable); } presetValueList.Add(new VariableType.VariablePreset(attrName.InnerText, value, valueBytes, isModifiable)); } } VariableType vType = new VariableType(); vType.NumBytes = numBytes; vType.ByteArray = byteArray; vType.Name = varName; vType.Content = patchedByteArrayList; vType.IsReference = isReference; vType.Reference = new VariableReference(); vType.Reference.Name = referenceName; vType.Reference.OperatorSymbol = referenceOperatorSymbol; vType.Reference.Operand = referenceOperand; vType.PresetValues = presetValueList; variables.Add(vType); } GetPatchResult getPatchResult = GetPatch(node, xmlFilename, asmUtility, variables); List <PatchedByteArray> patches = new List <PatchedByteArray>(includePatches.Count + getPatchResult.StaticPatches.Count); patches.AddRange(includePatches); patches.AddRange(getPatchResult.StaticPatches); AsmPatch asmPatch = new AsmPatch(getPatchResult.Name, shortXmlFilename, getPatchResult.Description, patches, (getPatchResult.HideInDefault | rootHideInDefault), (getPatchResult.IsHidden | rootIsHidden), variables); asmPatch.ErrorText = sbPatchErrorText.ToString() + getPatchResult.ErrorText; //asmPatch.Update(asmUtility); result.Add(asmPatch); } patchNodes = rootNode.SelectNodes("ImportFilePatch"); foreach (XmlNode node in patchNodes) { KeyValuePair <string, string> nameDesc = GetPatchNameAndDescription(node); string name = nameDesc.Key; string description = nameDesc.Value; XmlNodeList fileNodes = node.SelectNodes("ImportFile"); if (fileNodes.Count != 1) { continue; } XmlNode theRealNode = fileNodes[0]; //PsxIso.Sectors sector = (PsxIso.Sectors)Enum.Parse( typeof( PsxIso.Sectors ), theRealNode.Attributes["file"].InnerText ); Enum sector = (Enum)Enum.Parse(sectorType, theRealNode.Attributes["file"].InnerText); UInt32 offset = UInt32.Parse(theRealNode.Attributes["offset"].InnerText, System.Globalization.NumberStyles.HexNumber); UInt32 expectedLength = UInt32.Parse(theRealNode.Attributes["expectedLength"].InnerText, System.Globalization.NumberStyles.HexNumber); result.Add(new FileAsmPatch(name, shortXmlFilename, description, new InputFilePatch(sector, offset, expectedLength))); } return(result.AsReadOnly()); }
public static ConflictResolveResult ResolveConflicts(IList <AsmPatch> patchList, ASMEncoding.ASMEncodingUtility asmUtility, int maxConflictResolveAttempts = MaxConflictResolveAttempts) { List <AsmPatch> resultPatchList = new List <AsmPatch>(); Dictionary <AsmPatch, int> patchIndexMap = new Dictionary <AsmPatch, int>(); StringBuilder sbMessage = new StringBuilder(); bool hasConflicts = false; for (int index = 0; index < patchList.Count; index++) { resultPatchList.Add(patchList[index]); patchIndexMap.Add(patchList[index], index); } Context context = (asmUtility.EncodingMode == ASMEncoding.ASMEncodingMode.PSP) ? Context.US_PSP : Context.US_PSX; FreeSpaceMode mode = FreeSpace.GetMode(context); FreeSpaceMaps freeSpaceMaps = FreeSpace.GetFreeSpaceMaps(resultPatchList, mode); foreach (PatchRange freeSpaceRange in freeSpaceMaps.PatchRangeMap.Keys) { List <PatchedByteArray> innerPatches = freeSpaceMaps.PatchRangeMap[freeSpaceRange]; FreeSpaceAnalyzeResult analyzeResult = FreeSpace.Analyze(innerPatches, freeSpaceRange, true); int conflictResolveAttempts = 0; /* * Type sectorType = ISOHelper.GetSectorType(context); * Enum sector = (Enum)Enum.ToObject(sectorType, freeSpaceRange.Sector); * string strSector = (mode == FreeSpaceMode.PSP) ? PspIso.GetSectorName((PspIso.Sectors)sector) : PsxIso.GetSectorName((PsxIso.Sectors)sector); */ string strSector = ISOHelper.GetSectorName(freeSpaceRange.Sector, context); while ((analyzeResult.HasConflicts) && (conflictResolveAttempts < maxConflictResolveAttempts)) { bool isStatic = false; bool stayStatic = false; int endIndex = innerPatches.Count - 1; for (int index = 0; index < endIndex; index++) { PatchedByteArray innerPatch = innerPatches[index]; isStatic = innerPatch.IsStatic || stayStatic; stayStatic = (innerPatch.IsStatic) && (innerPatch.IsPatchEqual(innerPatches[index + 1])); if ((analyzeResult.ConflictIndexes.Contains(index)) && (!isStatic)) { long moveOffset = analyzeResult.LargestGapOffset - innerPatch.Offset; MovePatchRange movePatchRange = new MovePatchRange(new PatchRange(innerPatch), moveOffset); AsmPatch asmPatch = freeSpaceMaps.InnerPatchMap[innerPatch]; int resultPatchIndex = patchIndexMap[asmPatch]; patchIndexMap.Remove(asmPatch); asmPatch = asmPatch.Copy(); resultPatchList[resultPatchIndex] = asmPatch; patchIndexMap.Add(asmPatch, resultPatchIndex); asmPatch.MoveBlock(asmUtility, movePatchRange); asmPatch.Update(asmUtility); sbMessage.AppendLine("Conflict resolved by moving segment of patch \"" + asmPatch.Name + "\" in sector " + strSector + " from offset " + innerPatch.Offset.ToString("X") + " to " + analyzeResult.LargestGapOffset.ToString("X") + "."); freeSpaceMaps = FreeSpace.GetFreeSpaceMaps(resultPatchList, mode); innerPatches = freeSpaceMaps.PatchRangeMap[freeSpaceRange]; analyzeResult = FreeSpace.Analyze(innerPatches, freeSpaceRange, false); conflictResolveAttempts++; break; } } } if (analyzeResult.HasConflicts) { hasConflicts = true; int endIndex = innerPatches.Count - 1; for (int index = 0; index < endIndex; index++) { if (analyzeResult.ConflictIndexes.Contains(index)) { sbMessage.Length = 0; sbMessage.AppendLine("Conflict in sector " + strSector + " at offset " + innerPatches[index].Offset.ToString("X") + "!"); break; } } } } return(new ConflictResolveResult(resultPatchList, hasConflicts, sbMessage.ToString())); }