From dfff3e3a716d2d5f36f0b1d979b7f48823bebb18 Mon Sep 17 00:00:00 2001 From: Lars Brubaker Date: Thu, 25 Jun 2015 12:19:19 -0700 Subject: [PATCH] Making code go through the new LibraryProviderSqlite rather than the old sqliteData Put in an add item. Put in a FilySystemWatch for the LibraryProviderFileSystem Lots of work on LibraryProviderSqlite CodeMaid Models.cs --- AboutPage/AboutWidget.cs | 10 +- DataStorage/Models.cs | 462 +++++++++--------- PartPreviewWindow/SaveAsWindow.cs | 2 +- PrintLibrary/Provider/LibraryProvider.cs | 2 + .../Provider/LibraryProviderFileSystem.cs | 69 ++- .../Provider/LibraryProviderSelector.cs | 8 +- .../Provider/LibraryProviderSqlite.cs | 324 +++++++++++- PrintLibrary/Provider/LibrarySQLiteData.cs | 16 +- PrintQueue/QueueDataWidget.cs | 2 +- TextCreator/View3DTextCreator.cs | 1 - 10 files changed, 626 insertions(+), 270 deletions(-) diff --git a/AboutPage/AboutWidget.cs b/AboutPage/AboutWidget.cs index 971992d3a..8b4be1af7 100644 --- a/AboutPage/AboutWidget.cs +++ b/AboutPage/AboutWidget.cs @@ -35,8 +35,10 @@ using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.ContactForm; using MatterHackers.MatterControl.CustomWidgets; +using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.HtmlParsing; using MatterHackers.MatterControl.PrintLibrary; +using MatterHackers.MatterControl.PrintLibrary.Provider; using MatterHackers.MatterControl.PrintQueue; using System; using System.Collections.Generic; @@ -117,7 +119,7 @@ namespace MatterHackers.MatterControl HashSet referencedPrintItemsFilePaths = new HashSet(); HashSet referencedThumbnailFiles = new HashSet(); - // Get a list of all the stl and amf files referenced in the queue or library. + // Get a list of all the stl and amf files referenced in the queue. foreach (PrintItemWrapper printItem in QueueData.Instance.PrintItems) { string fileLocation = printItem.FileLocation; @@ -128,13 +130,15 @@ namespace MatterHackers.MatterControl } } - foreach (PrintItemWrapper printItem in LibrarySQLiteData.Instance.PrintItems) + // Add in all the stl and amf files referenced in the library. + foreach (PrintItem printItem in LibraryProviderSQLite.GetAllPrintItemsRecursive()) { + PrintItemWrapper printItemWrapper = new PrintItemWrapper(printItem); string fileLocation = printItem.FileLocation; if (!referencedPrintItemsFilePaths.Contains(fileLocation)) { referencedPrintItemsFilePaths.Add(fileLocation); - referencedThumbnailFiles.Add(PartThumbnailWidget.GetImageFilenameForItem(printItem)); + referencedThumbnailFiles.Add(PartThumbnailWidget.GetImageFilenameForItem(printItemWrapper)); } } diff --git a/DataStorage/Models.cs b/DataStorage/Models.cs index 807df5b2a..69f6558f5 100644 --- a/DataStorage/Models.cs +++ b/DataStorage/Models.cs @@ -39,25 +39,124 @@ using System.Threading; namespace MatterHackers.MatterControl.DataStorage { + public class ApplicationSession : Entity + { + public ApplicationSession() + : base() + { + SessionStart = DateTime.Now; + PrintCount = 0; + } + + public int PrintCount { get; set; } + + public DateTime SessionEnd { get; set; } + + public DateTime SessionStart { get; set; } + } + + public class CustomCommands : Entity + { + public DateTime DateLastModified { get; set; } + + public string Name { get; set; } + + [Indexed] + public int PrinterId { get; set; } + + public string Value { get; set; } + + public override void Commit() + { + DateLastModified = DateTime.Now; + base.Commit(); + } + } + public class Entity { - [PrimaryKey, AutoIncrement] - public int Id { get; set; } - - protected bool isSaved; protected int hashCode = 0; - public event PropertyChangedEventHandler PropertyChanged; + protected bool isSaved; + + private static readonly int maxRetries = 20; private IEnumerable properties; + private int retryCount = 0; + public Entity() { isSaved = false; } - private static readonly int maxRetries = 20; - private int retryCount = 0; + public event PropertyChangedEventHandler PropertyChanged; + + [PrimaryKey, AutoIncrement] + public int Id { get; set; } + + public virtual void Commit() + { + //Assumes that autoincremented ids start with 1 + if (this.Id == 0) + { + TryHandleInsert(); + } + else + { + TryHandleUpdate(); + } + } + + public void Delete() + { + Datastore.Instance.dbSQLite.Delete(this); + } + + public override int GetHashCode() + { + StringBuilder bigStringForHashCode = new StringBuilder(); + + if (this.hashCode == 0) + { + properties = this.GetType() + .GetProperties(BindingFlags.Instance | + BindingFlags.Public) + // Ignore non-string properties + .Where(prop => prop.PropertyType == typeof(string) || prop.PropertyType == typeof(int)) + // Ignore indexers + .Where(prop => prop.GetIndexParameters().Length == 0) + // Must be both readable and writable + .Where(prop => prop.CanWrite && prop.CanRead); + + foreach (PropertyInfo prop in properties) + { + object objectHoldingValue = prop.GetValue(this, null); + if (objectHoldingValue != null) + { + string value = objectHoldingValue.ToString(); + if (value != null) + { + bigStringForHashCode.Append(prop.Name); + bigStringForHashCode.Append(value); + } + } + } + this.hashCode = bigStringForHashCode.ToString().GetHashCode(); + } + + return this.hashCode; + } + + protected void OnPropertyChanged(string name) + { + PropertyChangedEventHandler handler = PropertyChanged; + this.hashCode = 0; + if (handler != null) + { + handler(this, new PropertyChangedEventArgs(name)); + } + } private void TryHandleInsert() { @@ -96,122 +195,80 @@ namespace MatterHackers.MatterControl.DataStorage retryCount = 0; } - - public virtual void Commit() - { - //Assumes that autoincremented ids start with 1 - if (this.Id == 0) - { - TryHandleInsert(); - } - else - { - TryHandleUpdate(); - } - } - - public void Delete() - { - Datastore.Instance.dbSQLite.Delete(this); - } - - protected void OnPropertyChanged(string name) - { - PropertyChangedEventHandler handler = PropertyChanged; - this.hashCode = 0; - if (handler != null) - { - handler(this, new PropertyChangedEventArgs(name)); - } - } - - public override int GetHashCode() - { - StringBuilder bigStringForHashCode = new StringBuilder(); - - if (this.hashCode == 0) - { - properties = this.GetType() - .GetProperties(BindingFlags.Instance | - BindingFlags.Public) - // Ignore non-string properties - .Where(prop => prop.PropertyType == typeof(string) || prop.PropertyType == typeof(int)) - // Ignore indexers - .Where(prop => prop.GetIndexParameters().Length == 0) - // Must be both readable and writable - .Where(prop => prop.CanWrite && prop.CanRead); - - foreach (PropertyInfo prop in properties) - { - object objectHoldingValue = prop.GetValue(this, null); - if (objectHoldingValue != null) - { - string value = objectHoldingValue.ToString(); - if (value != null) - { - bigStringForHashCode.Append(prop.Name); - bigStringForHashCode.Append(value); - } - } - } - this.hashCode = bigStringForHashCode.ToString().GetHashCode(); - } - - return this.hashCode; - } } - public class ApplicationSession : Entity + public class Printer : Entity { - public DateTime SessionStart { get; set; } - - public DateTime SessionEnd { get; set; } - - public int PrintCount { get; set; } - - public ApplicationSession() + public Printer() : base() { - SessionStart = DateTime.Now; - PrintCount = 0; - } - } - - public class PrintItemCollection : Entity - { - [Indexed] - public int ParentCollectionID { get; set; } - - public PrintItemCollection() - { + this.Make = "Unknown"; + this.Model = "Unknown"; } - public PrintItemCollection(string name, string collectionKey) - { - this.Name = name; - Key = collectionKey; - } + // features + public string _features { get; set; } + + public bool AutoConnectFlag { get; set; } + + public string BaudRate { get; set; } + + public string ComPort { get; set; } + + public string CurrentSlicingEngine { get; set; } + + public int DefaultSettingsCollectionId { get; set; } + + public string DeviceToken { get; set; } + + //Auto connect to printer (if available) + public string DeviceType { get; set; } + + // all the data about print leveling + public bool DoPrintLeveling { get; set; } + + public string DriverType { get; set; } + + public string Make { get; set; } + + public string ManualMovementSpeeds { get; set; } + + // stored x,value,y,value,z,value,e1,value,e2,value,e3,value,... + public string MaterialCollectionIds { get; set; } + + public string Model { get; set; } public string Name { get; set; } - public string Key { get; set; } + public string PrintLevelingJsonData { get; set; } + + public string PrintLevelingProbePositions { get; set; } // this is depricated go through PrintLevelingData + + // store id1,id2... (for N extruders) + + public int QualityCollectionId { get; set; } + } + + public class PrinterSetting : Entity + { + public DateTime DateLastModified { get; set; } + + public string Name { get; set; } + + [Indexed] + public int PrinterId { get; set; } + + public string Value { get; set; } + + public override void Commit() + { + DateLastModified = DateTime.Now; + base.Commit(); + } } public class PrintItem : Entity { - [Indexed] - public int PrintItemCollectionID { get; set; } - - public string Name { get; set; } - - public string LibraryProviderLocatorJson { get; set; } - - public string FileLocation { get; set; } - - public DateTime DateAdded { get; set; } - - public int PrintCount { get; set; } - public PrintItem() : this("", "") { @@ -227,6 +284,19 @@ namespace MatterHackers.MatterControl.DataStorage PrintCount = 0; } + public DateTime DateAdded { get; set; } + + public string FileLocation { get; set; } + + public string LibraryProviderLocatorJson { get; set; } + + public string Name { get; set; } + + public int PrintCount { get; set; } + + [Indexed] + public int PrintItemCollectionID { get; set; } + public List GetLibraryProviderLocator() { List providerPath = null; @@ -238,32 +308,38 @@ namespace MatterHackers.MatterControl.DataStorage } } - public class SliceSettingsCollection : Entity + public class PrintItemCollection : Entity { - public string Name { get; set; } - - public string Tag { get; set; } //ex. 'material' or 'quality' - - public int PrinterId { get; set; } - } - - public class SliceSetting : Entity - { - [Indexed] - public int SettingsCollectionId { get; set; } - - public string Name { get; set; } - - public string Value { get; set; } - - public SliceSetting() - : base() + public PrintItemCollection() { } + + public PrintItemCollection(string name, string collectionKey) + { + this.Name = name; + Key = collectionKey; + } + + public string Key { get; set; } + + public string Name { get; set; } + + [Indexed] + public int ParentCollectionID { get; set; } } public class PrintTask : Entity { + public PrintTask() + : base() + { + PrintStart = DateTime.Now; + } + + public bool PrintComplete { get; set; } + + public DateTime PrintEnd { get; set; } + [Indexed] public int PrinterId { get; set; } @@ -274,18 +350,6 @@ namespace MatterHackers.MatterControl.DataStorage public DateTime PrintStart { get; set; } - public DateTime PrintEnd { get; set; } - - public int PrintTimeSeconds { get; set; } - - public bool PrintComplete { get; set; } - - public PrintTask() - : base() - { - PrintStart = DateTime.Now; - } - public int PrintTimeMinutes { get @@ -296,6 +360,8 @@ namespace MatterHackers.MatterControl.DataStorage } } + public int PrintTimeSeconds { get; set; } + public override void Commit() { if (this.PrintEnd != DateTime.MinValue) @@ -307,15 +373,39 @@ namespace MatterHackers.MatterControl.DataStorage } } + public class SliceSetting : Entity + { + public SliceSetting() + : base() + { + } + + public string Name { get; set; } + + [Indexed] + public int SettingsCollectionId { get; set; } + + public string Value { get; set; } + } + + public class SliceSettingsCollection : Entity + { + public string Name { get; set; } + + public int PrinterId { get; set; } + + public string Tag { get; set; } //ex. 'material' or 'quality' + } + public class SystemSetting : Entity { + public DateTime DateLastModified { get; set; } + [Indexed] public string Name { get; set; } public string Value { get; set; } - public DateTime DateLastModified { get; set; } - public override void Commit() { DateLastModified = DateTime.Now; @@ -325,97 +415,13 @@ namespace MatterHackers.MatterControl.DataStorage public class UserSetting : Entity { + public DateTime DateLastModified { get; set; } + [Indexed] public string Name { get; set; } public string Value { get; set; } - public DateTime DateLastModified { get; set; } - - public override void Commit() - { - DateLastModified = DateTime.Now; - base.Commit(); - } - } - - public class CustomCommands : Entity - { - [Indexed] - public int PrinterId { get; set; } - - public string Name { get; set; } - - public string Value { get; set; } - - public DateTime DateLastModified { get; set; } - - public override void Commit() - { - DateLastModified = DateTime.Now; - base.Commit(); - } - } - - public class Printer : Entity - { - public int DefaultSettingsCollectionId { get; set; } - - public string Name { get; set; } - - public string Make { get; set; } - - public string Model { get; set; } - - public string ComPort { get; set; } - - public string DriverType { get; set; } - - public string BaudRate { get; set; } - - public bool AutoConnectFlag { get; set; } //Auto connect to printer (if available) - - public string DeviceToken { get; set; } - - public string DeviceType { get; set; } - - // all the data about print leveling - public bool DoPrintLeveling { get; set; } - - public string PrintLevelingJsonData { get; set; } - - public string PrintLevelingProbePositions { get; set; } // this is depricated go through PrintLevelingData - - // features - public string _features { get; set; } - - public string ManualMovementSpeeds { get; set; } // stored x,value,y,value,z,value,e1,value,e2,value,e3,value,... - - public string CurrentSlicingEngine { get; set; } - - public string MaterialCollectionIds { get; set; } // store id1,id2... (for N extruders) - - public int QualityCollectionId { get; set; } - - public Printer() - : base() - { - this.Make = "Unknown"; - this.Model = "Unknown"; - } - } - - public class PrinterSetting : Entity - { - [Indexed] - public int PrinterId { get; set; } - - public string Name { get; set; } - - public string Value { get; set; } - - public DateTime DateLastModified { get; set; } - public override void Commit() { DateLastModified = DateTime.Now; diff --git a/PartPreviewWindow/SaveAsWindow.cs b/PartPreviewWindow/SaveAsWindow.cs index 7e529f7a3..1ca564b57 100644 --- a/PartPreviewWindow/SaveAsWindow.cs +++ b/PartPreviewWindow/SaveAsWindow.cs @@ -159,7 +159,7 @@ namespace MatterHackers.MatterControl PrintItem printItem = new PrintItem(); printItem.Name = newName; printItem.FileLocation = Path.GetFullPath(fileNameAndPath); - printItem.PrintItemCollectionID = LibrarySQLiteData.Instance.LibraryCollection.Id; + printItem.PrintItemCollectionID = LibrarySQLiteData.Instance.RootLibraryCollection.Id; printItem.Commit(); printItemWrapper = new PrintItemWrapper(printItem); diff --git a/PrintLibrary/Provider/LibraryProvider.cs b/PrintLibrary/Provider/LibraryProvider.cs index e4d095dd0..30483186f 100644 --- a/PrintLibrary/Provider/LibraryProvider.cs +++ b/PrintLibrary/Provider/LibraryProvider.cs @@ -77,6 +77,8 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider public abstract void AddFilesToLibrary(IList files, List providerSavePath, ReportProgressRatio reportProgress = null, RunWorkerCompletedEventHandler callback = null); + public abstract void AddItem(PrintItemWrapper itemToAdd); + public abstract PrintItemCollection GetCollectionItem(int collectionIndex); public abstract PrintItemCollection GetParentCollectionItem(); diff --git a/PrintLibrary/Provider/LibraryProviderFileSystem.cs b/PrintLibrary/Provider/LibraryProviderFileSystem.cs index 0270f46a1..01123c473 100644 --- a/PrintLibrary/Provider/LibraryProviderFileSystem.cs +++ b/PrintLibrary/Provider/LibraryProviderFileSystem.cs @@ -28,6 +28,7 @@ either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; +using MatterHackers.Agg.UI; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PrintQueue; using MatterHackers.PolygonMesh; @@ -47,19 +48,30 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider private List currentDirectoryDirectories = new List(); private List currentDirectoryFiles = new List(); private string description; + private FileSystemWatcher directoryWatcher = new FileSystemWatcher(); private string keywordFilter = string.Empty; - private string parentKey = null; + private string parentProviderKey = null; private string rootPath; - public LibraryProviderFileSystem(string rootPath, string description, string parentKeyKey) + public LibraryProviderFileSystem(string rootPath, string description, string parentProviderKey) { - this.parentKey = parentKeyKey; + this.parentProviderKey = parentProviderKey; this.description = description; this.rootPath = rootPath; key = keyCount.ToString(); keyCount++; - GetFilesInCurrentDirectory(); + SetCollectionBase(null); + + directoryWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite + | NotifyFilters.FileName | NotifyFilters.DirectoryName; + directoryWatcher.Changed += new FileSystemEventHandler(DiretoryContentsChanged); + directoryWatcher.Created += new FileSystemEventHandler(DiretoryContentsChanged); + directoryWatcher.Deleted += new FileSystemEventHandler(DiretoryContentsChanged); + directoryWatcher.Renamed += new RenamedEventHandler(DiretoryContentsChanged); + + // Begin watching. + directoryWatcher.EnableRaisingEvents = true; } public override int CollectionCount @@ -74,7 +86,7 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider { get { - if (parentKey != null) + if (parentProviderKey != null) { return true; } @@ -103,7 +115,7 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider if (keywordFilter != value) { keywordFilter = value; - GetFilesInCurrentDirectory(); + GetFilesAndCollectionsInCurrentDirectory(); LibraryProvider.OnDataReloaded(null); } } @@ -125,7 +137,7 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); - GetFilesInCurrentDirectory(); + GetFilesAndCollectionsInCurrentDirectory(); LibraryProvider.OnDataReloaded(null); } } @@ -145,10 +157,15 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider CopyAllFiles(files, destPath); } - GetFilesInCurrentDirectory(); + GetFilesAndCollectionsInCurrentDirectory(); LibraryProvider.OnDataReloaded(null); } + public override void AddItem(PrintItemWrapper itemToAdd) + { + throw new NotImplementedException(); + } + public override PrintItemCollection GetCollectionItem(int collectionIndex) { string directoryName = currentDirectoryDirectories[collectionIndex]; @@ -159,9 +176,9 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider { if (currentDirectory == ".") { - if (parentKey != null) + if (parentProviderKey != null) { - return new PrintItemCollection("..", parentKey); + return new PrintItemCollection("..", parentProviderKey); } else { @@ -196,7 +213,7 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider public override void RemoveItem(PrintItemWrapper printItemWrapper) { File.Delete(printItemWrapper.PrintItem.FileLocation); - GetFilesInCurrentDirectory(); + GetFilesAndCollectionsInCurrentDirectory(); LibraryProvider.OnDataReloaded(null); } @@ -207,14 +224,23 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider public override void SetCollectionBase(PrintItemCollection collectionBase) { - string collectionPath = collectionBase.Key; - int startOfCurrentDir = collectionPath.IndexOf('.'); - if (startOfCurrentDir != -1) + if (collectionBase == null) { - this.currentDirectory = collectionPath.Substring(startOfCurrentDir); + currentDirectory = "."; + } + else + { + string collectionPath = collectionBase.Key; + int startOfCurrentDir = collectionPath.IndexOf('.'); + if (startOfCurrentDir != -1) + { + this.currentDirectory = collectionPath.Substring(startOfCurrentDir); + } } - GetFilesInCurrentDirectory(); + GetFilesAndCollectionsInCurrentDirectory(); + + directoryWatcher.Path = Path.Combine(rootPath, currentDirectory); } private static void CopyAllFiles(IList files, string destPath) @@ -243,7 +269,16 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider } } - private void GetFilesInCurrentDirectory() + private void DiretoryContentsChanged(object sender, EventArgs e) + { + UiThread.RunOnIdle(() => + { + GetFilesAndCollectionsInCurrentDirectory(); + LibraryProvider.OnDataReloaded(null); + }); + } + + private void GetFilesAndCollectionsInCurrentDirectory() { currentDirectoryDirectories.Clear(); string[] directories = Directory.GetDirectories(Path.Combine(rootPath, currentDirectory)); diff --git a/PrintLibrary/Provider/LibraryProviderSelector.cs b/PrintLibrary/Provider/LibraryProviderSelector.cs index d21833112..a4a0764ac 100644 --- a/PrintLibrary/Provider/LibraryProviderSelector.cs +++ b/PrintLibrary/Provider/LibraryProviderSelector.cs @@ -31,7 +31,6 @@ using MatterHackers.Agg; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PrintQueue; using MatterHackers.PolygonMesh; -using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; @@ -51,7 +50,7 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider LibraryProviderSQLite.Instance.SetParentKey(this.ProviderKey); // and any directory providers (sd card provider, etc...) - //libraryProviders.Add(new LibraryProviderFileSystem(Path.Combine("C:\\", "Users", "LarsBrubaker", "Downloads"), "Downloads", this.ProviderKey)); + libraryProviders.Add(new LibraryProviderFileSystem(Path.Combine("C:\\", "Users", "LarsBrubaker", "Downloads"), "Downloads", this.ProviderKey)); //#if __ANDROID__ //libraryProviders.Add(new LibraryProviderFileSystem(ApplicationDataStorage.Instance.PublicDataStoragePath, "Downloads", this.ProviderKey)); @@ -179,6 +178,11 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider libraryProviders[libraryProviderToUseIndex].AddFilesToLibrary(files, subProviderSavePath, reportProgress, callback); } + public override void AddItem(PrintItemWrapper itemToAdd) + { + throw new NotImplementedException(); + } + public override PrintItemCollection GetCollectionItem(int collectionIndex) { if (selectedLibraryProvider == -1) diff --git a/PrintLibrary/Provider/LibraryProviderSqlite.cs b/PrintLibrary/Provider/LibraryProviderSqlite.cs index 4bb64fd7d..f743ce8ec 100644 --- a/PrintLibrary/Provider/LibraryProviderSqlite.cs +++ b/PrintLibrary/Provider/LibraryProviderSqlite.cs @@ -28,21 +28,37 @@ either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; +using MatterHackers.Agg.PlatformAbstract; using MatterHackers.Agg.UI; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.PrintQueue; +using MatterHackers.MatterControl.SettingsManagement; using MatterHackers.PolygonMesh; +using MatterHackers.PolygonMesh.Processors; using System; using System.Collections.Generic; using System.ComponentModel; +using System.IO; +using System.Linq; namespace MatterHackers.MatterControl.PrintLibrary.Provider { public class LibraryProviderSQLite : LibraryProvider { private static LibraryProviderSQLite instance = null; + private static PrintItemCollection rotLibraryCollection; + private List childCollections = new List(); + private PrintItemCollection collectionBase = GetRootLibraryCollection(); + private string keywordFilter = string.Empty; private string parentProviderKey = null; + private List printItems = new List(); + + public LibraryProviderSQLite() + { + LoadLibraryItems(); + } + public new static LibraryProviderSQLite Instance { get @@ -68,7 +84,7 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider { get { - return 0; + return childCollections.Count; } } @@ -89,7 +105,7 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider { get { - return LibrarySQLiteData.Instance.ItemCount; + return printItems.Count; } } @@ -97,12 +113,12 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider { get { - return LibrarySQLiteData.Instance.KeywordFilter; + return keywordFilter; } set { - LibrarySQLiteData.Instance.KeywordFilter = value; + keywordFilter = value; } } @@ -122,19 +138,146 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider } } + public static IEnumerable GetAllPrintItemsRecursive() + { + // NOTE: We are making the assumption that everything is reference if it does not have a 0 in eth PrintItemCollectionID. + string query = "SELECT * FROM PrintItem WHERE PrintItemCollectionID != 0;"; + IEnumerable result = (IEnumerable)Datastore.Instance.dbSQLite.Query(query); + return result; + } + + public static PrintItemCollection GetRootLibraryCollection() + { + // Attempt to initialize the library from the Datastore if null + if (rotLibraryCollection == null) + { + rotLibraryCollection = Datastore.Instance.dbSQLite.Table().Where(v => v.Name == "_library").Take(1).FirstOrDefault(); + } + + // If the _library collection is still missing, create and populate it with default content + if (rotLibraryCollection == null) + { + rotLibraryCollection = new PrintItemCollection(); + rotLibraryCollection.Name = "_library"; + rotLibraryCollection.Commit(); + + // Preload library with Oem supplied list of default parts + string[] itemsToAdd = SyncCalibrationFilesToDisk(OemSettings.Instance.PreloadedLibraryFiles); + if (itemsToAdd.Length > 0) + { + // Import any files sync'd to disk into the library, then add them to the queue + Instance.AddFilesToLibrary(itemsToAdd); + } + } + return rotLibraryCollection; + } + + static public void SaveToLibraryFolder(PrintItemWrapper printItemWrapper, List meshGroups, bool AbsolutePositioned) + { + string[] metaData = { "Created By", "MatterControl" }; + if (AbsolutePositioned) + { + metaData = new string[] { "Created By", "MatterControl", "BedPosition", "Absolute" }; + } + if (printItemWrapper.FileLocation.Contains(ApplicationDataStorage.Instance.ApplicationLibraryDataPath)) + { + MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData); + MeshFileIo.Save(meshGroups, printItemWrapper.FileLocation, outputInfo); + } + else // save a copy to the library and update this to point at it + { + string fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".amf"); + printItemWrapper.FileLocation = Path.Combine(ApplicationDataStorage.Instance.ApplicationLibraryDataPath, fileName); + + MeshOutputSettings outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData); + MeshFileIo.Save(meshGroups, printItemWrapper.FileLocation, outputInfo); + + printItemWrapper.PrintItem.Commit(); + + // let the queue know that the item has changed so it load the correct part + QueueData.Instance.SaveDefaultQueue(); + } + + printItemWrapper.OnFileHasChanged(); + } + + public static string[] SyncCalibrationFilesToDisk(List calibrationPrintFileNames) + { + // Ensure the CalibrationParts directory exists to store/import the files from disk + string tempPath = Path.Combine(ApplicationDataStorage.Instance.ApplicationUserDataPath, "data", "temp", "calibration-parts"); + Directory.CreateDirectory(tempPath); + + // Build a list of temporary files that should be imported into the library + return calibrationPrintFileNames.Where(fileName => + { + // Filter out items that already exist in the library + return Instance.GetLibraryItems(Path.GetFileNameWithoutExtension(fileName)).Count() <= 0; + }).Select(fileName => + { + // Copy calibration prints from StaticData to the filesystem before importing into the library + string tempFile = Path.Combine(tempPath, Path.GetFileName(fileName)); + using (FileStream outstream = File.OpenWrite(tempFile)) + using (Stream instream = StaticData.Instance.OpenSteam(Path.Combine("OEMSettings", "SampleParts", fileName))) + { + instream.CopyTo(outstream); + } + + // Project the new filename to the output + return tempFile; + }).ToArray(); + } + public override void AddCollectionToLibrary(string collectionName) + { + PrintItemCollection newCollection = new PrintItemCollection(collectionName, ""); + newCollection.ParentCollectionID = collectionBase.Id; + newCollection.Commit(); + } + + public override void AddFilesToLibrary(IList files, List providerSavePath = null, ReportProgressRatio reportProgress = null, RunWorkerCompletedEventHandler callback = null) + { + if (files != null && files.Count > 0) + { + BackgroundWorker loadFilesIntoLibraryBackgroundWorker = new BackgroundWorker(); + loadFilesIntoLibraryBackgroundWorker.WorkerReportsProgress = true; + + loadFilesIntoLibraryBackgroundWorker.DoWork += new DoWorkEventHandler(loadFilesIntoLibraryBackgoundWorker_DoWork); + loadFilesIntoLibraryBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(loadFilesIntoLibraryBackgroundWorker_RunWorkerCompleted); + + if (callback != null) + { + loadFilesIntoLibraryBackgroundWorker.RunWorkerCompleted += callback; + } + + loadFilesIntoLibraryBackgroundWorker.RunWorkerAsync(files); + } + } + + public override void AddItem(PrintItemWrapper itemToAdd) { throw new NotImplementedException(); } - public override void AddFilesToLibrary(IList files, List providerSavePath, ReportProgressRatio reportProgress = null, RunWorkerCompletedEventHandler callback = null) + public void AddItem(PrintItemWrapper item, int indexToInsert = -1) { - LibrarySQLiteData.Instance.LoadFilesIntoLibrary(files, reportProgress, callback); + if (indexToInsert == -1) + { + indexToInsert = printItems.Count; + } + printItems.Insert(indexToInsert, item); + // Check if the collection we are adding to is the the currently visible collection. + List currentDisplayedCollection = LibraryProvider.Instance.GetProviderLocator(); + if (currentDisplayedCollection.Count > 0 && currentDisplayedCollection[1].Key == LibraryProviderSQLite.StaticProviderKey) + { + OnItemAdded(new IndexArgs(indexToInsert)); + } + item.PrintItem.PrintItemCollectionID = GetRootLibraryCollection().Id; + item.PrintItem.Commit(); } public override PrintItemCollection GetCollectionItem(int collectionIndex) { - throw new NotImplementedException(); + return childCollections[collectionIndex]; } public override PrintItemCollection GetParentCollectionItem() @@ -149,9 +292,14 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider } } - public override PrintItemWrapper GetPrintItemWrapper(int itemIndex) + public override PrintItemWrapper GetPrintItemWrapper(int index) { - return LibrarySQLiteData.Instance.GetPrintItemWrapper(itemIndex); + if (index >= 0 && index < printItems.Count) + { + return printItems[index]; + } + + return null; } public override List GetProviderLocator() @@ -159,6 +307,22 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider throw new NotImplementedException(); } + public void LoadLibraryItems() + { + printItems.Clear(); + IEnumerable partFiles = GetLibraryItems(KeywordFilter); + if (partFiles != null) + { + foreach (PrintItem part in partFiles) + { + printItems.Add(new PrintItemWrapper(part)); + } + } + + childCollections.Clear(); + childCollections.AddRange(GetChildCollections()); + } + public override void RemoveCollection(string collectionName) { throw new NotImplementedException(); @@ -166,7 +330,19 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider public override void RemoveItem(PrintItemWrapper printItemWrapper) { - LibrarySQLiteData.Instance.RemoveItem(printItemWrapper); + int index = printItems.IndexOf(printItemWrapper); + if (index < 0) + { + // It may be possible to have the same item in the remove list twice. + // so if it is not in the PrintItems then ignore it. + return; + } + printItems.RemoveAt(index); + + // and remove it from the data base + printItemWrapper.Delete(); + + OnItemRemoved(new IndexArgs(index)); } public override void SaveToLibrary(PrintItemWrapper printItemWrapper, List meshGroupsToSave, List providerSavePath) @@ -176,6 +352,9 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider public override void SetCollectionBase(PrintItemCollection collectionBase) { + this.collectionBase = collectionBase; + + LoadLibraryItems(); } public void SetParentKey(string parentKey) @@ -183,5 +362,130 @@ namespace MatterHackers.MatterControl.PrintLibrary.Provider this.parentProviderKey = parentKey; UiThread.RunOnIdle(() => LibraryProvider.OnDataReloaded(null)); } + + private static void AddStlOrGcode(string loadedFileName, string extension) + { + PrintItem printItem = new PrintItem(); + printItem.Name = Path.GetFileNameWithoutExtension(loadedFileName); + printItem.FileLocation = Path.GetFullPath(loadedFileName); + printItem.PrintItemCollectionID = GetRootLibraryCollection().Id; + printItem.Commit(); + + if (MeshFileIo.ValidFileExtensions().Contains(extension)) + { + List meshToConvertAndSave = MeshFileIo.Load(loadedFileName); + + try + { + PrintItemWrapper printItemWrapper = new PrintItemWrapper(printItem); + SaveToLibraryFolder(printItemWrapper, meshToConvertAndSave, false); + Instance.AddItem(printItemWrapper); + } + catch (System.UnauthorizedAccessException) + { + UiThread.RunOnIdle(() => + { + //Do something special when unauthorized? + StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes, unauthorized access", "Unable to save"); + }); + } + catch + { + UiThread.RunOnIdle(() => + { + StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes.", "Unable to save"); + }); + } + } + else // it is not a mesh so just add it + { + PrintItemWrapper printItemWrapper = new PrintItemWrapper(printItem); + if (false) + { + Instance.AddItem(printItemWrapper); + } + else // save a copy to the library and update this to point at it + { + string sourceFileName = printItem.FileLocation; + string newFileName = Path.ChangeExtension(Path.GetRandomFileName(), Path.GetExtension(printItem.FileLocation)); + string destFileName = Path.Combine(ApplicationDataStorage.Instance.ApplicationLibraryDataPath, newFileName); + + File.Copy(sourceFileName, destFileName, true); + + printItemWrapper.FileLocation = destFileName; + printItemWrapper.PrintItem.Commit(); + + // let the queue know that the item has changed so it load the correct part + Instance.AddItem(printItemWrapper); + } + } + } + + private IEnumerable GetChildCollections() + { + if (collectionBase != null) + { + string query; + query = string.Format("SELECT * FROM PrintItemCollection WHERE ParentCollectionID = {0} ORDER BY Name ASC;", collectionBase.Id); + IEnumerable result = (IEnumerable)Datastore.Instance.dbSQLite.Query(query); + return result; + } + + return null; + } + + private IEnumerable GetLibraryItems(string keyphrase = null) + { + if (collectionBase != null) + { + string query; + if (keyphrase == null) + { + query = string.Format("SELECT * FROM PrintItem WHERE PrintItemCollectionID = {0} ORDER BY Name ASC;", collectionBase.Id); + } + else + { + query = string.Format("SELECT * FROM PrintItem WHERE PrintItemCollectionID = {0} AND Name LIKE '%{1}%' ORDER BY Name ASC;", collectionBase.Id, keyphrase); + } + IEnumerable result = (IEnumerable)Datastore.Instance.dbSQLite.Query(query); + return result; + } + + return null; + } + + private void loadFilesIntoLibraryBackgoundWorker_DoWork(object sender, DoWorkEventArgs e) + { + IList fileList = e.Argument as IList; + foreach (string loadedFileName in fileList) + { + string extension = Path.GetExtension(loadedFileName).ToUpper(); + if (MeshFileIo.ValidFileExtensions().Contains(extension) + || extension == ".GCODE" + || extension == ".ZIP") + { + if (extension == ".ZIP") + { + ProjectFileHandler project = new ProjectFileHandler(null); + List partFiles = project.ImportFromProjectArchive(loadedFileName); + if (partFiles != null) + { + foreach (PrintItem part in partFiles) + { + AddStlOrGcode(part.FileLocation, Path.GetExtension(part.FileLocation).ToUpper()); + } + } + } + else + { + AddStlOrGcode(loadedFileName, extension); + } + } + } + } + + private void loadFilesIntoLibraryBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) + { + } } } \ No newline at end of file diff --git a/PrintLibrary/Provider/LibrarySQLiteData.cs b/PrintLibrary/Provider/LibrarySQLiteData.cs index 9a70f3bbf..8c7a151d8 100644 --- a/PrintLibrary/Provider/LibrarySQLiteData.cs +++ b/PrintLibrary/Provider/LibrarySQLiteData.cs @@ -127,10 +127,15 @@ namespace MatterHackers.MatterControl.PrintLibrary { OnItemAdded(new IndexArgs(indexToInsert)); } - item.PrintItem.PrintItemCollectionID = LibraryCollection.Id; + item.PrintItem.PrintItemCollectionID = RootLibraryCollection.Id; item.PrintItem.Commit(); } + public void AddCollection(PrintItemCollection collection) + { + collection.Commit(); + } + public void RemoveItem(PrintItemWrapper printItemWrapper) { int index = PrintItems.IndexOf(printItemWrapper); @@ -158,7 +163,7 @@ namespace MatterHackers.MatterControl.PrintLibrary return null; } - public DataStorage.PrintItemCollection LibraryCollection + public DataStorage.PrintItemCollection RootLibraryCollection { get { @@ -215,7 +220,7 @@ namespace MatterHackers.MatterControl.PrintLibrary internal IEnumerable GetLibraryItems(string keyphrase = null) { - if (LibraryCollection == null) + if (RootLibraryCollection == null) { return null; } @@ -277,11 +282,8 @@ namespace MatterHackers.MatterControl.PrintLibrary } } - private ReportProgressRatio fileLoadReportProgress = null; - public void LoadFilesIntoLibrary(IList files, ReportProgressRatio reportProgress = null, RunWorkerCompletedEventHandler callback = null) { - this.fileLoadReportProgress = reportProgress; if (files != null && files.Count > 0) { BackgroundWorker loadFilesIntoLibraryBackgroundWorker = new BackgroundWorker(); @@ -334,7 +336,7 @@ namespace MatterHackers.MatterControl.PrintLibrary PrintItem printItem = new PrintItem(); printItem.Name = Path.GetFileNameWithoutExtension(loadedFileName); printItem.FileLocation = Path.GetFullPath(loadedFileName); - printItem.PrintItemCollectionID = LibrarySQLiteData.Instance.LibraryCollection.Id; + printItem.PrintItemCollectionID = LibrarySQLiteData.Instance.RootLibraryCollection.Id; printItem.Commit(); if (MeshFileIo.ValidFileExtensions().Contains(extension)) diff --git a/PrintQueue/QueueDataWidget.cs b/PrintQueue/QueueDataWidget.cs index 16f700df8..a01a2a9c5 100644 --- a/PrintQueue/QueueDataWidget.cs +++ b/PrintQueue/QueueDataWidget.cs @@ -460,7 +460,7 @@ namespace MatterHackers.MatterControl.PrintQueue { foreach (QueueRowItem queueItem in queueDataView.SelectedItems) { - LibrarySQLiteData.Instance.AddItem(queueItem.PrintItemWrapper); + LibraryProvider.Instance.AddItem(queueItem.PrintItemWrapper); } } diff --git a/TextCreator/View3DTextCreator.cs b/TextCreator/View3DTextCreator.cs index 2b776409a..78f23fab0 100644 --- a/TextCreator/View3DTextCreator.cs +++ b/TextCreator/View3DTextCreator.cs @@ -929,7 +929,6 @@ namespace MatterHackers.MatterControl.Plugins.TextCreator printItem.Name = string.Format("{0}", word); printItem.FileLocation = Path.GetFullPath(filePath); - printItem.PrintItemCollectionID = LibrarySQLiteData.Instance.LibraryCollection.Id; PrintItemWrapper printItemWrapper = new PrintItemWrapper(printItem);