phyreballs /tools/PhyreFly/src/controls/AssetManager.cs

Language C# Lines 480
MD5 Hash 8079e795fb4456030ce72fa1972f3696 Estimated Cost $10,133 (why?)
Repository https://bitbucket.org/drummertom999/phyreballs View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
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;
	}
}
Back to Top