/tools/PhyreFly/src/controls/AssetManager.cs
C# | 480 lines | 393 code | 66 blank | 21 comment | 48 complexity | 8079e795fb4456030ce72fa1972f3696 MD5 | raw file
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Drawing;
- using System.Data;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Xml.Linq;
- using System.Diagnostics;
- using System.Threading;
-
- namespace PhyreFly
- {
- public partial class AssetManager : UserControl
- {
- #region Node Names
- private static string ROOT_NODE = "assets";
- private static string OUTPUT_NODE = "output";
- private static string ASSET_NODE = "asset";
- #endregion
-
- #region Column Names
- private const int COL_ICON = 0;
- private const int COL_SOURCE = 1;
- private const int COL_SYMBOL = 2;
- private const int COL_BTN_BUILD = 3;
- private const int COL_BTN_REBUILD = 4;
- #endregion
-
- public AssetManager(string assetListFilename, string platform, AssetProcessAction action)
- {
- InitializeComponent();
-
- // Setup globals
- PFGlobals.XmlFile = assetListFilename;
- PFGlobals.XmlFileDir = Path.GetDirectoryName(assetListFilename);
- PFUtils.RemoveReadOnlyFlag(assetListFilename);
-
- // Register for console log events
- PFConsole.OnWrite += new PFConsole.OutputFunction(PFConsole_OnWrite);
-
- // Load XML and initialize form
- if (!ValidateLoadXmlFile() || !InitForm())
- {
- PFGlobals.MainWindow.Close();
- return;
- }
-
- // Validate and set platform
- if (platform != null && m_supportedPlatforms.Contains(platform))
- {
- int count = 1;
- foreach(string supportedPlatform in m_supportedPlatforms)
- {
- if(platform == supportedPlatform)
- {
- ui_cb_platforms.SelectedIndex = count;
- break;
- }
- ++count;
- }
- }
-
- // Begin action?
- if (action != AssetProcessAction.None)
- {
- PFAssetProcessor.AutoClose = true;
- StartGlobalAction(action);
- }
- }
-
- #region XML Validate / Load / Save
- private bool ValidateLoadXmlFile()
- {
- try
- {
- m_assetListFile = XDocument.Load(PFGlobals.XmlFile, LoadOptions.SetLineInfo);
- }
- catch (Exception e)
- {
- MessageBox.Show("Could not open file: {0}", e.Message);
- return false;
- }
-
- if (m_assetListFile.Root.Name != ROOT_NODE)
- {
- MessageBox.Show(String.Format("Document is missing root node '{0}'", ROOT_NODE));
- return false;
- }
-
- XElement outputNode = m_assetListFile.Root.Element(OUTPUT_NODE);
- if (outputNode == null)
- {
- MessageBox.Show(String.Format("Document is missing '{0}' node", OUTPUT_NODE));
- return false;
- }
-
- m_outputAttributes = new PFOutputAttributes(outputNode);
- if (!m_outputAttributes.ReadFromFile())
- return false;
-
- // Collect Assets
- m_assets = (from c in m_assetListFile.Descendants(ASSET_NODE)
- select new Asset()
- {
- Source = c.Attribute("source").Value,
- Symbol = c.Attribute("symbol").Value,
- }).ToList<Asset>();
-
- return true;
- }
-
- private void SaveXmlFile()
- {
- // Remove nodes from XDocument
- foreach (XElement node in m_assetListFile.Descendants(ASSET_NODE).ToList())
- node.Remove();
-
- foreach (DataGridViewRow row in ui_dataGrid.Rows)
- {
- XElement assetNode = new XElement(ASSET_NODE);
- assetNode.SetAttributeValue("source", row.Cells[COL_SOURCE].Value);
- assetNode.SetAttributeValue("symbol", row.Cells[COL_SYMBOL].Value);
- m_assetListFile.Root.Add(assetNode);
- }
- m_assetListFile.Save(PFGlobals.XmlFile);
- }
- #endregion
-
- private bool InitForm()
- {
- try
- {
- // Dock user control
- this.Dock = DockStyle.Fill;
-
- // Register for asset processing events
- PFAssetProcessor.OnStart += (PFAssetProcessor.APEvent)delegate()
- {
- ui_pb_work.Invoke((MethodInvoker)delegate()
- {
- tableLayoutPanel1.RowStyles[1].Height = 25;
- ui_rtb_console.Margin = new Padding(3, 3, 3, 0);
- });
- };
-
- PFAssetProcessor.OnFinish += (PFAssetProcessor.APEvent)delegate()
- {
- ui_pb_work.Invoke((MethodInvoker)delegate()
- {
- ui_rtb_console.Margin = new Padding(3);
- tableLayoutPanel1.RowStyles[1].Height = 0;
- });
- };
-
- // Populate platforms drop-down
- ui_cb_platforms.Items.AddRange(m_supportedPlatforms);
- ui_cb_platforms.SelectedIndex = 1;
-
- // Initially collapse progress bar
- tableLayoutPanel1.RowStyles[1].Height = 0;
-
- // Assign right click menu to console window
- ui_rtb_console.ContextMenu = m_cm;
-
- // Bind form elements
- ui_tb_output_mode.DataBindings.Add("Text", m_outputAttributes.Mode, "Value");
- ui_tb_output_filename.DataBindings.Add("Text", m_outputAttributes.Filename, "Value");
- ui_tb_output_rcname.DataBindings.Add("Text", m_outputAttributes.RCName, "Value");
- ui_tb_output_filelist.DataBindings.Add("Text", m_outputAttributes.FileList, "Value");
- ui_tb_output_pathprefix.DataBindings.Add("Text", m_outputAttributes.PathPrefix, "Value");
-
- // Bind assets to grid view
- int count = 0;
- foreach (Asset asset in m_assets)
- {
- ui_dataGrid.Rows.Add(null, asset.Source, asset.Symbol);
- ui_dataGrid.Rows[count].Tag = asset;
- ++count;
- }
-
- m_bLoaded = true;
- return true;
- }
- catch (Exception e)
- {
- MessageBox.Show("Failed binding data to form: {0}", e.Message);
- return false;
- }
- }
-
- private void StartSingleAction(Asset asset, AssetProcessAction action)
- {
- if (PFAssetProcessor.IsWorking)
- {
- PFConsole.WriteLine(PFConsole.Severity.ERROR, "Busy, please wait...");
- return;
- }
-
- string[] selectedPlatform = new string[] { ui_cb_platforms.SelectedItem.ToString() };
- Thread th = new Thread(delegate()
- {
- foreach (string platformName in ((selectedPlatform[0] == "All Platforms") ? m_supportedPlatforms : selectedPlatform))
- PFAssetProcessor.ProcessSingleAsset(asset.Source, platformName, action);
- });
- th.Name = string.Format("Process Single Asset [{0}|{1}|{2}]", Path.GetFileName(asset.Source), selectedPlatform[0], action.ToString());
- th.Start();
- }
-
- private void StartGlobalAction(AssetProcessAction action)
- {
- if (PFAssetProcessor.IsWorking)
- {
- PFConsole.WriteLine(PFConsole.Severity.ERROR, "Busy, please wait...");
- return;
- }
-
- // Perform some sanity checks on all asset files
- SortedSet<string> symbolNameList = new SortedSet<string>();
- foreach (Asset asset in m_assets)
- {
- // Make sure asset exists on disk
- if (!PFUtils.EnsureAssetExists(asset.Source))
- return;
-
- // Check for duplicate symbol names
- if (!symbolNameList.Add(asset.Symbol))
- {
- MessageBox.Show(String.Format("Error: The symbol name {0} was used more than once", asset.Symbol));
- return;
- }
- }
-
- // Save XML file
- SaveXmlFile();
-
- // Begin global build (per chosen platform) on new thread
- string[] selectedPlatform = new string[] { ui_cb_platforms.SelectedItem.ToString() };
- Thread th = new Thread(delegate()
- {
- foreach (string platformName in ((selectedPlatform[0] == "All Platforms") ? m_supportedPlatforms : selectedPlatform))
- {
- PFAssetProcessor.ProcessAllAssets(PFGlobals.XmlFile, platformName, action);
- while (PFAssetProcessor.IsWorking)
- Thread.Sleep(300);
- }
- });
- th.Name = string.Format("Process All Assets [{0}|{1}]", selectedPlatform[0], action.ToString());
- th.Start();
- }
-
- #region Path Helpers
- public static bool HasRelativePaths()
- {
- foreach (Asset asset in m_assets)
- {
- if (!PFUtils.PathIsAbsolute(asset.Source))
- return true;
- }
-
- return false;
- }
-
- public static string FindAnAbsolutePath()
- {
- foreach (Asset asset in m_assets)
- {
- if (PFUtils.PathIsAbsolute(asset.Source))
- return asset.Source;
- }
-
- return string.Empty;
- }
-
- public static string FindARelativePath()
- {
- foreach (Asset asset in m_assets)
- {
- if (!PFUtils.PathIsAbsolute(asset.Source))
- return asset.Source;
- }
-
- return string.Empty;
- }
-
- public static string GetProjectRoot()
- {
- string startPath = FindAnAbsolutePath();
- if (startPath == string.Empty)
- {
- startPath = FindARelativePath();
- string workingDir = string.Empty;
- PFAssetProcessor.GetWorkingDir(ref workingDir);
- startPath = Path.Combine(workingDir, startPath);
- }
-
- // Should now have an absolute path to an asset. If not, user error!
- startPath = PFUtils.TidyPath(startPath);
- if (!File.Exists(startPath))
- {
- string msg = "There was an error finding the project root. ";
- msg += String.Format("Ensure that the working dir and '{0}' are set up correctly", PFGlobals.AssetSpecFile);
- MessageBox.Show(msg);
- PFAssetProcessor.WorkingDir = string.Empty;
- return string.Empty;
- }
-
- // Search back up directory tree to find Globals.AssetSpecFile
- while (startPath.Contains("\\"))
- {
- startPath = startPath.Substring(0, startPath.LastIndexOf("\\"));
- string testPath = Path.Combine(startPath, PFGlobals.AssetSpecFile);
- if (File.Exists(testPath))
- return startPath; // Found asset spec file
- }
-
- return string.Empty;
- }
- #endregion
-
- #region Form Events
- private void AssetManager_Load(object sender, EventArgs e)
- {
- GetProjectRoot();
- }
-
- private void ui_btn_save_Click(object sender, EventArgs e)
- {
- SaveXmlFile();
- }
-
- private void ui_btn_open_header_Click(object sender, EventArgs e)
- {
- string headerFilename = Path.Combine(PFGlobals.XmlFileDir, m_outputAttributes.Filename.Value);
- if (File.Exists(headerFilename))
- Process.Start(PFGlobals.TextEditor, headerFilename);
- }
-
- private void ui_btn_open_xml_Click(object sender, EventArgs e)
- {
- if (File.Exists(PFGlobals.XmlFile))
- Process.Start(PFGlobals.TextEditor, PFGlobals.XmlFile);
- }
-
- private void ui_cb_platforms_KeyDown(object sender, KeyEventArgs e)
- {
- e.SuppressKeyPress = true;
- }
-
- private void ui_btn_build_all_Click(object sender, EventArgs e)
- {
- StartGlobalAction(AssetProcessAction.Build);
- }
-
- private void ui_btn_rebuild_all_Click(object sender, EventArgs e)
- {
- StartGlobalAction(AssetProcessAction.Rebuild);
- }
-
- private void ui_btn_clean_all_Click(object sender, EventArgs e)
- {
- StartGlobalAction(AssetProcessAction.Clean);
- }
-
- private void ui_dataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
- {
- if (!m_bLoaded)
- return;
-
- Asset asset = ui_dataGrid.Rows[e.RowIndex].Tag as Asset;
- asset.Source = ui_dataGrid.Rows[e.RowIndex].Cells[COL_SOURCE].Value.ToString();
- asset.Symbol = ui_dataGrid.Rows[e.RowIndex].Cells[COL_SYMBOL].Value.ToString();
- }
-
- private void ui_dataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
- {
- if ((e.ColumnIndex != COL_BTN_BUILD && e.ColumnIndex != COL_BTN_REBUILD) || e.RowIndex == -1)
- return;
-
- Asset asset = ui_dataGrid.Rows[e.RowIndex].Tag as Asset;
- if(asset != null)
- StartSingleAction(asset, (e.ColumnIndex == COL_BTN_BUILD) ? AssetProcessAction.Build : AssetProcessAction.Rebuild);
- }
-
- private void ui_btn_add_asset_Click(object sender, EventArgs e)
- {
- if (PFAssetProcessor.IsWorking)
- {
- PFConsole.WriteLine(PFConsole.Severity.ERROR, "Busy, please wait...");
- return;
- }
-
- Asset newAsset = new Asset();
- newAsset.Source = "MyAsset.dae";
- newAsset.Symbol = "g_myAssetIndex";
- m_assets.Add(newAsset);
- ui_dataGrid.Rows.Add(null, newAsset.Source, newAsset.Symbol);
- ui_dataGrid.Rows[ui_dataGrid.Rows.Count-1].Tag = newAsset;
- }
-
- private void ui_dataGrid_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
- {
- Asset removedAsset = e.Row.Tag as Asset;
- m_assets.Remove(removedAsset);
- }
-
- private void ui_btn_show_info_Click(object sender, EventArgs e)
- {
- new InfoForm().ShowDialog();
- }
-
- void PFConsole_OnWrite(Color severity, string msg, params object[] args)
- {
- ui_rtb_console.Invoke((MethodInvoker) delegate()
- {
- ui_rtb_console.SelectionStart = ui_rtb_console.Text.Length;
- ui_rtb_console.SelectionColor = severity;
- ui_rtb_console.AppendText(String.Format(msg, args));
- ui_rtb_console.SelectionStart = ui_rtb_console.Text.Length;
- ui_rtb_console.ScrollToCaret();
- });
- }
-
- private void ui_rtb_console_MouseDown(object sender, MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Right)
- {
- m_cm.MenuItems.Clear();
-
- if (ui_rtb_console.SelectionLength == 0)
- {
- if (ui_rtb_console.Text.Length != 0)
- {
- MenuItem mi = new MenuItem("Clear");
- mi.Click += new EventHandler(ConsoleRightClick_Clear);
- m_cm.MenuItems.Add(mi);
- }
- }
- else
- {
- MenuItem mi = new MenuItem("Copy");
- mi.Click += new EventHandler(ConsoleRightClick_Copy);
- m_cm.MenuItems.Add(mi);
- }
-
- m_cm.Show(ui_rtb_console, ui_rtb_console.PointToClient(MousePosition));
- }
- }
-
- void ConsoleRightClick_Copy(object sender, EventArgs e)
- {
- Clipboard.SetData(DataFormats.Text, ui_rtb_console.SelectedText);
- }
-
- void ConsoleRightClick_Clear(object sender, EventArgs e)
- {
- ui_rtb_console.Text = string.Empty;
- }
- #endregion
-
- private static List<Asset> m_assets;
- private static ContextMenu m_cm = new ContextMenu();
- private static XDocument m_assetListFile;
- private static PFOutputAttributes m_outputAttributes;
- public static PFOutputAttributes OutputAttributes
- {
- get { return m_outputAttributes; }
- }
- private static string[] m_supportedPlatforms = { "GL", "GXM", "GCM", "GLx64"};
- private bool m_bLoaded = false;
- }
-
- public class Asset
- {
- public string Source;
- public string Symbol;
- }
- }