示例#1
0
        public void ExportGcodeCommandLineUtility(String nameOfFile)
        {
            try
            {
                if (!string.IsNullOrEmpty(nameOfFile))
                {
                    gcodePathAndFilenameToSave = nameOfFile;
                    string extension = Path.GetExtension(gcodePathAndFilenameToSave);
                    if (extension == "")
                    {
                        File.Delete(gcodePathAndFilenameToSave);
                        gcodePathAndFilenameToSave += ".gcode";
                    }

                    string sourceExtension = Path.GetExtension(printItemWrapper.FileLocation).ToUpper();
                    if (MeshFileIo.ValidFileExtensions().Contains(sourceExtension))
                    {
                        SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
                        printItemWrapper.SlicingDone += sliceItem_Done;
                    }
                    else if (partIsGCode)
                    {
                        SaveGCodeToNewLocation(printItemWrapper.FileLocation, gcodePathAndFilenameToSave);
                    }
                }
            }
            catch
            {
            }
        }
        public override void OnLoad(EventArgs args)
        {
            foreach (string arg in commandLineArgs)
            {
                string argExtension = Path.GetExtension(arg).ToUpper();
                if (argExtension.Length > 1 &&
                    MeshFileIo.ValidFileExtensions().Contains(argExtension))
                {
                    QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
                }
            }

            TerminalWindow.ShowIfLeftOpen();

            ApplicationController.Instance.OnLoadActions();

#if false
            {
                SystemWindow releaseNotes        = new SystemWindow(640, 480);
                string       releaseNotesFile    = Path.Combine("C:/Users/LarsBrubaker/Downloads", "test1.html");
                string       releaseNotesContent = StaticData.Instance.ReadAllText(releaseNotesFile);
                HtmlWidget   content             = new HtmlWidget(releaseNotesContent, RGBA_Bytes.Black);
                content.AddChild(new GuiWidget(HAnchor.AbsolutePosition, VAnchor.ParentBottomTop));
                content.VAnchor        |= VAnchor.ParentTop;
                content.BackgroundColor = RGBA_Bytes.White;
                releaseNotes.AddChild(content);
                releaseNotes.BackgroundColor = RGBA_Bytes.Cyan;
                UiThread.RunOnIdle((state) =>
                {
                    releaseNotes.ShowAsSystemWindow();
                }, 1);
            }
#endif
        }
示例#3
0
        public override void OnDragDrop(FileDropEventArgs fileDropEventArgs)
        {
            foreach (string droppedFileName in fileDropEventArgs.DroppedFiles)
            {
                string extension = Path.GetExtension(droppedFileName).ToUpper();
                if (MeshFileIo.ValidFileExtensions().Contains(extension) ||
                    extension == ".GCODE")
                {
                    QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileNameWithoutExtension(droppedFileName), Path.GetFullPath(droppedFileName))));
                }
                else if (extension == ".ZIP")
                {
                    ProjectFileHandler project   = new ProjectFileHandler(null);
                    List <PrintItem>   partFiles = project.ImportFromProjectArchive(droppedFileName);
                    if (partFiles != null)
                    {
                        foreach (PrintItem part in partFiles)
                        {
                            QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(part.Name, part.FileLocation)));
                        }
                    }
                }
            }

            base.OnDragDrop(fileDropEventArgs);
        }
        void onExportGcodeFileSelected(SaveFileDialogParams saveParams)
        {
            if (saveParams.FileName != null)
            {
                gcodePathAndFilenameToSave = saveParams.FileName;
                string extension = Path.GetExtension(gcodePathAndFilenameToSave);
                if (extension == "")
                {
                    File.Delete(gcodePathAndFilenameToSave);
                    gcodePathAndFilenameToSave += ".gcode";
                }

                string sourceExtension = Path.GetExtension(printItemWrapper.FileLocation).ToUpper();
                if (MeshFileIo.ValidFileExtensions().Contains(sourceExtension))
                {
                    Close();
                    SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
                    printItemWrapper.SlicingDone.RegisterEvent(sliceItem_Done, ref unregisterEvents);
                }
                else if (partIsGCode)
                {
                    Close();
                    SaveGCodeToNewLocation(printItemWrapper.FileLocation, gcodePathAndFilenameToSave);
                }
            }
        }
示例#5
0
        public static void DoAddFiles(List <string> files)
        {
            int preAddCount = QueueData.Instance.ItemCount;

            foreach (string fileToAdd in files)
            {
                string extension = Path.GetExtension(fileToAdd).ToUpper();
                if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension)) ||
                    extension == ".GCODE")
                {
                    QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileNameWithoutExtension(fileToAdd), Path.GetFullPath(fileToAdd))));
                }
                else if (extension == ".ZIP")
                {
                    ProjectFileHandler project   = new ProjectFileHandler(null);
                    List <PrintItem>   partFiles = project.ImportFromProjectArchive(fileToAdd);
                    if (partFiles != null)
                    {
                        foreach (PrintItem part in partFiles)
                        {
                            QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(part.Name, part.FileLocation)));
                        }
                    }
                }
            }

            if (QueueData.Instance.ItemCount != preAddCount)
            {
                QueueData.Instance.SelectedIndex = QueueData.Instance.ItemCount - 1;
            }
        }
示例#6
0
 private void loadFilesIntoLibraryBackgoundWorker_DoWork(IList <string> fileList)
 {
     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 <PrintItem>   partFiles = project.ImportFromProjectArchive(loadedFileName);
                 if (partFiles != null)
                 {
                     foreach (PrintItem part in partFiles)
                     {
                         AddStlOrGcode(this, part.FileLocation, Path.GetExtension(part.FileLocation).ToUpper());
                     }
                 }
             }
             else
             {
                 AddStlOrGcode(this, loadedFileName, extension);
             }
         }
     }
 }
示例#7
0
        private void onExportX3gFileSelected(SaveFileDialogParams saveParams)
        {
            if (saveParams.FileName != null)
            {
                x3gPathAndFilenameToSave = saveParams.FileName;
                string extension = Path.GetExtension(x3gPathAndFilenameToSave);
                if (extension == "")
                {
                    File.Delete(gcodePathAndFilenameToSave);
                    x3gPathAndFilenameToSave += ".x3g";
                }

                string saveExtension = Path.GetExtension(printItemWrapper.FileLocation).ToUpper();
                if (MeshFileIo.ValidFileExtensions().Contains(saveExtension))
                {
                    Close();
                    SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
                    printItemWrapper.SlicingDone += x3gItemSlice_Complete;
                }
                else if (partIsGCode)
                {
                    Close();
                    generateX3GfromGcode(printItemWrapper.FileLocation, x3gPathAndFilenameToSave);
                }
            }
        }
示例#8
0
        public void Start()
        {
            if (allFilesToExport.Count > 0)
            {
                if (StartingNextPart != null)
                {
                    StartingNextPart(this, new StringEventArgs(ItemNameBeingWorkedOn));
                }

                savedGCodeFileNames = new List <string>();
                foreach (PrintItem part in allFilesToExport)
                {
                    PrintItemWrapper printItemWrapper = new PrintItemWrapper(part);
                    string           extension        = Path.GetExtension(printItemWrapper.FileLocation).ToUpper();
                    if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension)))
                    {
                        SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
                        printItemWrapper.SlicingDone          += sliceItem_Done;
                        printItemWrapper.SlicingOutputMessage += printItemWrapper_SlicingOutputMessage;
                    }
                    else if (Path.GetExtension(printItemWrapper.FileLocation).ToUpper() == ".GCODE")
                    {
                        sliceItem_Done(printItemWrapper, null);
                    }
                }
            }
        }
 public void AddFilesToLibrary(IList <string> files, ReportProgressRatio reportProgress = null)
 {
     foreach (string loadedFileName in files)
     {
         string extension = Path.GetExtension(loadedFileName).ToUpper();
         if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension)) ||
             extension == ".GCODE" ||
             extension == ".ZIP")
         {
             if (extension == ".ZIP")
             {
                 ProjectFileHandler project   = new ProjectFileHandler(null);
                 List <PrintItem>   partFiles = project.ImportFromProjectArchive(loadedFileName);
                 if (partFiles != null)
                 {
                     foreach (PrintItem part in partFiles)
                     {
                         AddItem(new PrintItemWrapper(part, this.GetProviderLocator()));
                     }
                 }
             }
             else
             {
                 AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileNameWithoutExtension(loadedFileName), loadedFileName), this.GetProviderLocator()));
             }
         }
     }
 }
示例#10
0
        private static void AddStlOrGcode(LibraryProviderSQLite libraryToAddTo, string loadedFileName, string extension)
        {
            PrintItem printItem = new PrintItem();

            printItem.Name                  = Path.GetFileNameWithoutExtension(loadedFileName);
            printItem.FileLocation          = Path.GetFullPath(loadedFileName);
            printItem.PrintItemCollectionID = libraryToAddTo.baseLibraryCollection.Id;
            printItem.Commit();

            if (MeshFileIo.ValidFileExtensions().Contains(extension))
            {
                List <MeshGroup> meshToConvertAndSave = MeshFileIo.Load(loadedFileName);

                try
                {
                    PrintItemWrapper printItemWrapper = new PrintItemWrapper(printItem);
                    SaveToLibraryFolder(printItemWrapper, meshToConvertAndSave, false);
                    libraryToAddTo.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)
                {
                    libraryToAddTo.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
                    libraryToAddTo.AddItem(printItemWrapper);
                }
            }
        }
        public override void OnDraw(Graphics2D graphics2D)
        {
            totalDrawTime.Restart();
            GuiWidget.DrawCount = 0;
            using (new PerformanceTimer("Draw Timer", "MC Draw"))
            {
                base.OnDraw(graphics2D);
            }
            totalDrawTime.Stop();

            millisecondTimer.Update((int)totalDrawTime.ElapsedMilliseconds);

            if (ShowMemoryUsed)
            {
                long memory = GC.GetTotalMemory(false);
                this.Title = "Allocated = {0:n0} : {1:000}ms, d{2} Size = {3}x{4}, onIdle = {5:00}:{6:00}, widgetsDrawn = {7}".FormatWith(memory, millisecondTimer.GetAverage(), drawCount++, this.Width, this.Height, UiThread.CountExpired, UiThread.Count, GuiWidget.DrawCount);
                if (DoCGCollectEveryDraw)
                {
                    GC.Collect();
                }
            }

            if (firstDraw)
            {
                //Task.Run((Action)AutomationTest);
                UiThread.RunOnIdle(DoAutoConnectIfRequired);

                firstDraw = false;
                foreach (string arg in commandLineArgs)
                {
                    string argExtension = Path.GetExtension(arg).ToUpper();
                    if (argExtension.Length > 1 &&
                        MeshFileIo.ValidFileExtensions().Contains(argExtension))
                    {
                        QueueData.Instance.AddItem(new PrintItemWrapper(new DataStorage.PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
                    }
                }

                TerminalWindow.ShowIfLeftOpen();

                if (AfterFirstDraw != null)
                {
                    AfterFirstDraw();
                }

                UiThread.RunOnIdle(() =>
                {
                    //StyledMessageBox.ShowMessageBox(null, "message that is long and wraps. message that is long and wraps. message that is long and wraps." , "caption", StyledMessageBox.MessageType.YES_NO);
                    // show a dialog to tell the user there is an update
                });
            }

            //msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds);
            //msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D);
        }
示例#12
0
 public override void OnDragOver(FileDropEventArgs fileDropEventArgs)
 {
     foreach (string file in fileDropEventArgs.DroppedFiles)
     {
         string extension = Path.GetExtension(file).ToUpper();
         if (MeshFileIo.ValidFileExtensions().Contains(extension))
         {
             fileDropEventArgs.AcceptDrop = true;
         }
     }
     base.OnDragOver(fileDropEventArgs);
 }
        public override void OnDraw(Graphics2D graphics2D)
        {
            totalDrawTime.Restart();
            GuiWidget.DrawCount = 0;
            base.OnDraw(graphics2D);
            totalDrawTime.Stop();

            millisecondTimer.Update((int)totalDrawTime.ElapsedMilliseconds);

            if (ShowMemoryUsed)
            {
                long memory = GC.GetTotalMemory(false);
                this.Title = "Allocated = {0:n0} : {1:000}ms, d{2} Size = {3}x{4}, onIdle = {5:00}:{6:00}, drawCount = {7}".FormatWith(memory, millisecondTimer.GetAverage(), drawCount++, this.Width, this.Height, UiThread.CountExpired, UiThread.Count, GuiWidget.DrawCount);
                if (DoCGCollectEveryDraw)
                {
                    GC.Collect();
                }
            }

            if (firstDraw)
            {
                UiThread.RunOnIdle(DoAutoConnectIfRequired);

                firstDraw = false;
                foreach (string arg in commandLineArgs)
                {
                    string argExtension = Path.GetExtension(arg).ToUpper();
                    if (argExtension.Length > 1 &&
                        MeshFileIo.ValidFileExtensions().Contains(argExtension))
                    {
                        QueueData.Instance.AddItem(new PrintItemWrapper(new DataStorage.PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
                    }
                }

                TerminalWindow.ShowIfLeftOpen();

#if false
                foreach (CreatorInformation creatorInfo in RegisteredCreators.Instance.Creators)
                {
                    if (creatorInfo.description.Contains("Image"))
                    {
                        creatorInfo.functionToLaunchCreator(null, null);
                    }
                }
#endif
            }

            //msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds);
            //msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D);
        }
示例#14
0
        public override void OnDragDrop(FileDropEventArgs fileDropEventArgs)
        {
            foreach (string droppedFileName in fileDropEventArgs.DroppedFiles)
            {
                string extension = Path.GetExtension(droppedFileName).ToUpper();
                if (MeshFileIo.ValidFileExtensions().Contains(extension))
                {
                    meshViewerWidget.LoadMesh(droppedFileName, MeshVisualizer.MeshViewerWidget.CenterPartAfterLoad.DO);
                    break;
                }
            }

            base.OnDragDrop(fileDropEventArgs);
        }
示例#15
0
        protected virtual void AddStlOrGcode(string loadedFileName, string displayName)
        {
            string extension = Path.GetExtension(loadedFileName).ToUpper();

            PrintItem printItem = new PrintItem();

            printItem.Name                  = displayName;
            printItem.FileLocation          = Path.GetFullPath(loadedFileName);
            printItem.PrintItemCollectionID = this.baseLibraryCollection.Id;
            printItem.Commit();

            if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension)))
            {
                List <MeshGroup> meshToConvertAndSave = MeshFileIo.Load(loadedFileName);

                try
                {
                    PrintItemWrapper printItemWrapper = new PrintItemWrapper(printItem, this);
                    SaveToLibraryFolder(printItemWrapper, meshToConvertAndSave, false);
                }
                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, this);
                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();
            }
        }
示例#16
0
 public override void OnDragEnter(FileDropEventArgs fileDropEventArgs)
 {
     if (libraryDataView != null &&
         libraryDataView.CurrentLibraryProvider != null &&
         !libraryDataView.CurrentLibraryProvider.IsProtected())
     {
         foreach (string file in fileDropEventArgs.DroppedFiles)
         {
             string extension = Path.GetExtension(file).ToUpper();
             if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension)) ||
                 extension == ".GCODE" ||
                 extension == ".ZIP")
             {
                 fileDropEventArgs.AcceptDrop = true;
             }
         }
     }
     base.OnDragEnter(fileDropEventArgs);
 }
示例#17
0
        public override void OnDragDrop(FileDropEventArgs fileDropEventArgs)
        {
            foreach (string droppedFileName in fileDropEventArgs.DroppedFiles)
            {
                string extension = Path.GetExtension(droppedFileName).ToUpper();
                if (MeshFileIo.ValidFileExtensions().Contains(extension) ||
                    extension == ".GCODE")
                {
                    PrintItem printItem = new PrintItem();
                    printItem.Name                  = Path.GetFileNameWithoutExtension(droppedFileName);
                    printItem.FileLocation          = Path.GetFullPath(droppedFileName);
                    printItem.PrintItemCollectionID = LibraryData.Instance.LibraryCollection.Id;
                    printItem.Commit();

                    LibraryData.Instance.AddItem(new PrintItemWrapper(printItem));
                }
            }

            base.OnDragDrop(fileDropEventArgs);
        }
示例#18
0
        public override void OnLoad(EventArgs args)
        {
            foreach (string arg in commandLineArgs)
            {
                string argExtension = Path.GetExtension(arg).ToUpper();
                if (argExtension.Length > 1 &&
                    MeshFileIo.ValidFileExtensions().Contains(argExtension))
                {
                    QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
                }
            }

            TerminalWindow.ShowIfLeftOpen();

            ApplicationController.Instance.OnLoadActions();

            //HtmlWindowTest();

            IsLoading = false;
        }
示例#19
0
        private static void AddStlOrGcode(string loadedFileName, string extension)
        {
            PrintItem printItem = new PrintItem();

            printItem.Name                  = Path.GetFileNameWithoutExtension(loadedFileName);
            printItem.FileLocation          = Path.GetFullPath(loadedFileName);
            printItem.PrintItemCollectionID = LibraryData.Instance.LibraryCollection.Id;
            printItem.Commit();

            if (MeshFileIo.ValidFileExtensions().Contains(extension))
            {
                List <MeshGroup> meshToConvertAndSave = MeshFileIo.Load(loadedFileName);

                try
                {
                    PrintItemWrapper printItemWrapper = new PrintItemWrapper(printItem);
                    LibraryData.SaveToLibraryFolder(printItemWrapper, meshToConvertAndSave, false);
                    LibraryData.Instance.AddItem(printItemWrapper);
                }
                catch (System.UnauthorizedAccessException)
                {
                    UiThread.RunOnIdle((state) =>
                    {
                        //Do something special when unauthorized?
                        StyledMessageBox.ShowMessageBox(null, "Oops! Unable to save changes, unauthorized access", "Unable to save");
                    });
                }
                catch
                {
                    UiThread.RunOnIdle((state) =>
                    {
                        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);
                LibraryData.Instance.AddItem(printItemWrapper);
            }
        }
示例#20
0
        public override void OnDraw(Graphics2D graphics2D)
        {
            totalDrawTime.Restart();
            GuiWidget.DrawCount = 0;
            base.OnDraw(graphics2D);
            totalDrawTime.Stop();

            if (ShowMemoryUsed)
            {
                long memory = GC.GetTotalMemory(false);
                this.Title = "Allocated = {0:n0} : {1}ms, d{2} Size = {3}x{4}, onIdle = {5}, drawCount = {6}".FormatWith(memory, totalDrawTime.ElapsedMilliseconds, drawCount++, this.Width, this.Height, UiThread.Count, GuiWidget.DrawCount);
                if (DoCGCollectEveryDraw)
                {
                    GC.Collect();
                }
            }

            if (firstDraw)
            {
                UiThread.RunOnIdle(DoAutoConnectIfRequired);

                firstDraw = false;
                foreach (string arg in commandLineArgs)
                {
                    string argExtension = Path.GetExtension(arg).ToUpper();
                    if (argExtension.Length > 1 &&
                        MeshFileIo.ValidFileExtensions().Contains(argExtension))
                    {
                        QueueData.Instance.AddItem(new PrintItemWrapper(new DataStorage.PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
                    }
                }
            }

            //msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds);
            //msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D);
        }
示例#21
0
        public override void OnDragOver(FileDropEventArgs fileDropEventArgs)
        {
            base.OnDragOver(fileDropEventArgs);

            if (!fileDropEventArgs.AcceptDrop)
            {
                // no child has accepted the drop
                foreach (string file in fileDropEventArgs.DroppedFiles)
                {
                    string extension = Path.GetExtension(file).ToUpper();
                    if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension)) ||
                        extension == ".GCODE" ||
                        extension == ".ZIP")
                    {
                        fileDropEventArgs.AcceptDrop = true;
                    }
                }
                dropWasOnChild = false;
            }
            else
            {
                dropWasOnChild = true;
            }
        }
示例#22
0
        private MatterControlApplication(double width, double height)
            : base(width, height)
        {
            ApplicationSettings.Instance.set("HardwareHasCamera", "false");

            Name = "MatterControl";

            // set this at startup so that we can tell next time if it got set to true in close
            UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1;

            this.commandLineArgs = Environment.GetCommandLineArgs();
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++)
            {
                string command      = commandLineArgs[currentCommandIndex];
                string commandUpper = command.ToUpper();
                switch (commandUpper)
                {
                case "FORCE_SOFTWARE_RENDERING":
                    GL.HardwareAvailable = false;
                    break;

                case "CLEAR_CACHE":
                    AboutWidget.DeleteCacheData(0);
                    break;

                case "SHOW_MEMORY":
                    ShowMemoryUsed = true;
                    break;

                case "DO_GC_COLLECT_EVERY_DRAW":
                    ShowMemoryUsed       = true;
                    DoCGCollectEveryDraw = true;
                    break;

                //case "CREATE_AND_SELECT_PRINTER":
                //	if (currentCommandIndex + 1 <= commandLineArgs.Length)
                //	{
                //		currentCommandIndex++;
                //		string argument = commandLineArgs[currentCommandIndex];
                //		string[] printerData = argument.Split(',');
                //		if (printerData.Length >= 2)
                //		{
                //			Printer ActivePrinter = new Printer();

                //			ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]);
                //			ActivePrinter.Make = printerData[0];
                //			ActivePrinter.Model = printerData[1];

                //			if (printerData.Length == 3)
                //			{
                //				ActivePrinter.ComPort = printerData[2];
                //			}

                //			PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter);
                //			test.LoadSettingsFromConfigFile(ActivePrinter.Make, ActivePrinter.Model);
                //			ActiveSliceSettings.Instance = ActivePrinter;
                //		}
                //	}

                //	break;

                case "CONNECT_TO_PRINTER":
                    if (currentCommandIndex + 1 <= commandLineArgs.Length)
                    {
                        PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter();
                    }
                    break;

                case "START_PRINT":
                    if (currentCommandIndex + 1 <= commandLineArgs.Length)
                    {
                        bool hasBeenRun = false;
                        currentCommandIndex++;
                        string fullPath = commandLineArgs[currentCommandIndex];
                        QueueData.Instance.RemoveAll();
                        if (!string.IsNullOrEmpty(fullPath))
                        {
                            string fileName = Path.GetFileNameWithoutExtension(fullPath);
                            QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath)));
                            PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) =>
                            {
                                if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected)
                                {
                                    hasBeenRun = true;
                                    PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible();
                                }
                            }, ref unregisterEvent);
                        }
                    }
                    break;

                case "SLICE_AND_EXPORT_GCODE":
                    if (currentCommandIndex + 1 <= commandLineArgs.Length)
                    {
                        currentCommandIndex++;
                        string fullPath = commandLineArgs[currentCommandIndex];
                        QueueData.Instance.RemoveAll();
                        if (!string.IsNullOrEmpty(fullPath))
                        {
                            string           fileName         = Path.GetFileNameWithoutExtension(fullPath);
                            PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath));
                            QueueData.Instance.AddItem(printItemWrapper);

                            SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
                            ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper);
                            exportForTest.ExportGcodeCommandLineUtility(fileName);
                        }
                    }
                    break;
                }

                if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper()))
                {
                    // If we are the only instance running then do nothing.
                    // Else send these to the running instance so it can load them.
                }
            }

            //WriteTestGCodeFile();
#if !DEBUG
            if (File.Exists("RunUnitTests.txt"))
#endif
            {
#if IS_WINDOWS_FORMS
                if (!Clipboard.IsInitialized)
                {
                    Clipboard.SetSystemClipboard(new WindowsFormsClipboard());
                }
#endif

                // you can turn this on to debug some bounds issues
                //GuiWidget.DebugBoundsUnderMouse = true;
            }

            GuiWidget.DefaultEnforceIntegerBounds = true;

            if (UserSettings.Instance.IsTouchScreen)
            {
                GuiWidget.DeviceScale            = 1.3;
                SystemWindow.ShareSingleOsWindow = true;
            }
            //GuiWidget.DeviceScale = 2;

            using (new PerformanceTimer("Startup", "MainView"))
            {
                this.AddChild(ApplicationController.Instance.MainView);
            }
            this.MinimumSize = minSize;
            this.Padding     = new BorderDouble(0); //To be re-enabled once native borders are turned off

#if false                                           // this is to test freeing gcodefile memory
            Button test = new Button("test");
            test.Click += (sender, e) =>
            {
                //MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile();
                //gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode");
                SystemWindow window = new SystemWindow(100, 100);
                window.ShowAsSystemWindow();
            };
            allControls.AddChild(test);
#endif
            this.AnchorAll();

            if (GL.HardwareAvailable)
            {
                UseOpenGL = true;
            }
            string version = "1.6";

            Title = "MatterHackers: MatterControl {0}".FormatWith(version);
            if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
            {
                Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra);
            }

            UiThread.RunOnIdle(CheckOnPrinter);

            string desktopPosition = ApplicationSettings.Instance.get(ApplicationSettingsKey.DesktopPosition);
            if (!string.IsNullOrEmpty(desktopPosition))
            {
                string[] sizes = desktopPosition.Split(',');

                //If the desktop position is less than -10,-10, override
                int xpos = Math.Max(int.Parse(sizes[0]), -10);
                int ypos = Math.Max(int.Parse(sizes[1]), -10);

                DesktopPosition = new Point2D(xpos, ypos);
            }
            else
            {
                DesktopPosition = new Point2D(-1, -1);
            }

            this.Maximized = ApplicationSettings.Instance.get(ApplicationSettingsKey.MainWindowMaximized) == "true";
        }
示例#23
0
        public MatterControlApplication(double width, double height)
            : base(width, height)
        {
            CrashTracker.Reset();

            this.commandLineArgs = Environment.GetCommandLineArgs();
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            foreach (string command in commandLineArgs)
            {
                string commandUpper = command.ToUpper();
                switch (commandUpper)
                {
                case "TEST":
                    Testing.TestingDispatch testDispatch = new Testing.TestingDispatch();
                    testDispatch.RunTests();
                    return;

                case "CLEAR_CACHE":
                    AboutPage.DeleteCacheData();
                    break;

                case "SHOW_MEMORY":
                    ShowMemoryUsed = true;
                    break;

                case "DO_GC_COLLECT_EVERY_DRAW":
                    ShowMemoryUsed       = true;
                    DoCGCollectEveryDraw = true;
                    break;
                }

                if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper()))
                {
                    // If we are the only instance running then do nothing.
                    // Else send these to the running instance so it can load them.
                }
            }

            //WriteTestGCodeFile();
#if !DEBUG
            if (File.Exists("RunUnitTests.txt"))
#endif
            {
#if IS_WINDOWS_FORMS
                Clipboard.SetSystemClipboardFunctions(System.Windows.Forms.Clipboard.GetText, System.Windows.Forms.Clipboard.SetText, System.Windows.Forms.Clipboard.ContainsText);
#endif

                MatterHackers.PolygonMesh.UnitTests.UnitTests.Run();
                MatterHackers.RayTracer.UnitTests.Run();
                MatterHackers.Agg.Tests.UnitTests.Run();
                MatterHackers.VectorMath.Tests.UnitTests.Run();
                MatterHackers.Agg.UI.Tests.UnitTests.Run();

                // you can turn this on to debug some bounds issues
                //GuiWidget.DebugBoundsUnderMouse = true;
            }

            GuiWidget.DefaultEnforceIntegerBounds = true;

            if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
            {
                TextWidget.GlobalPointSizeScaleRatio = 1.3;
            }

            this.AddChild(ApplicationController.Instance.MainView);
            this.MinimumSize = new Vector2(400, 400);
            this.Padding     = new BorderDouble(0); //To be re-enabled once native borders are turned off

#if false                                           // this is to test freeing gcodefile memory
            Button test = new Button("test");
            test.Click += (sender, e) =>
            {
                //MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile();
                //gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode");
                SystemWindow window = new SystemWindow(100, 100);
                window.ShowAsSystemWindow();
            };
            allControls.AddChild(test);
#endif
            this.AnchorAll();

            UseOpenGL = true;
            string version = "1.1";

            Title = "MatterControl {0}".FormatWith(version);
            if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
            {
                Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra);
            }

            UiThread.RunOnIdle(CheckOnPrinter);

            string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition");
            if (desktopPosition != null && desktopPosition != "")
            {
                string[] sizes = desktopPosition.Split(',');

                //If the desktop position is less than -10,-10, override
                int xpos = Math.Max(int.Parse(sizes[0]), -10);
                int ypos = Math.Max(int.Parse(sizes[1]), -10);
                DesktopPosition = new Point2D(xpos, ypos);
            }
            ShowAsSystemWindow();
        }
        public override void OnDraw(Graphics2D graphics2D)
        {
            totalDrawTime.Restart();
            GuiWidget.DrawCount = 0;
            using (new PerformanceTimer("Draw Timer", "MC Draw"))
            {
                base.OnDraw(graphics2D);
            }
            totalDrawTime.Stop();

            millisecondTimer.Update((int)totalDrawTime.ElapsedMilliseconds);

            if (ShowMemoryUsed)
            {
                long memory = GC.GetTotalMemory(false);
                this.Title = "Allocated = {0:n0} : {1:000}ms, d{2} Size = {3}x{4}, onIdle = {5:00}:{6:00}, widgetsDrawn = {7}".FormatWith(memory, millisecondTimer.GetAverage(), drawCount++, this.Width, this.Height, UiThread.CountExpired, UiThread.Count, GuiWidget.DrawCount);
                if (DoCGCollectEveryDraw)
                {
                    GC.Collect();
                }
            }

            if (firstDraw)
            {
                firstDraw = false;
                foreach (string arg in commandLineArgs)
                {
                    string argExtension = Path.GetExtension(arg).ToUpper();
                    if (argExtension.Length > 1 &&
                        MeshFileIo.ValidFileExtensions().Contains(argExtension))
                    {
                        QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
                    }
                }

                TerminalWindow.ShowIfLeftOpen();

#if false
                {
                    SystemWindow releaseNotes        = new SystemWindow(640, 480);
                    string       releaseNotesFile    = Path.Combine("C:/Users/LarsBrubaker/Downloads", "test1.html");
                    string       releaseNotesContent = StaticData.Instance.ReadAllText(releaseNotesFile);
                    HtmlWidget   content             = new HtmlWidget(releaseNotesContent, RGBA_Bytes.Black);
                    content.AddChild(new GuiWidget(HAnchor.AbsolutePosition, VAnchor.ParentBottomTop));
                    content.VAnchor        |= VAnchor.ParentTop;
                    content.BackgroundColor = RGBA_Bytes.White;
                    releaseNotes.AddChild(content);
                    releaseNotes.BackgroundColor = RGBA_Bytes.Cyan;
                    UiThread.RunOnIdle((state) =>
                    {
                        releaseNotes.ShowAsSystemWindow();
                    }, 1);
                }
#endif

                AfterFirstDraw?.Invoke();

                if (false && UserSettings.Instance.get("SoftwareLicenseAccepted") != "true")
                {
                    UiThread.RunOnIdle(() => WizardWindow.Show <LicenseAgreementPage>("SoftwareLicense", "Software License Agreement"));
                }

                if (!ProfileManager.Instance.ActiveProfiles.Any())
                {
                    // Start the setup wizard if no profiles exist
                    UiThread.RunOnIdle(() => WizardWindow.Show());
                }
            }

            //msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds);
            //msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D);
        }
        /// <summary>
        /// Creates a database PrintItem entity, if forceAMF is set, converts to AMF otherwise just copies
        /// the source file to a new library path and updates the PrintItem to point at the new target
        /// </summary>
        private void AddItem(Stream stream, string extension, string displayName, bool forceAMF = true)
        {
            // Create a new entity in the database
            PrintItem printItem = new PrintItem();

            printItem.Name = displayName;
            printItem.PrintItemCollectionID = this.baseLibraryCollection.Id;
            printItem.Commit();

            // Special load processing for mesh data, simple copy below for non-mesh
            if (forceAMF &&
                (extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension.ToUpper())))
            {
                try
                {
                    // Load mesh
                    List <MeshGroup> meshToConvertAndSave = MeshFileIo.Load(stream, extension);

                    // Create a new PrintItemWrapper

                    if (!printItem.FileLocation.Contains(ApplicationDataStorage.Instance.ApplicationLibraryDataPath))
                    {
                        string[] metaData = { "Created By", "MatterControl" };
                        if (false)                         //AbsolutePositioned
                        {
                            metaData = new string[] { "Created By", "MatterControl", "BedPosition", "Absolute" };
                        }

                        // save a copy to the library and update this to point at it
                        printItem.FileLocation = CreateLibraryPath(".amf");
                        var outputInfo = new MeshOutputSettings(MeshOutputSettings.OutputType.Binary, metaData);
                        MeshFileIo.Save(meshToConvertAndSave, printItem.FileLocation, outputInfo);
                        printItem.Commit();
                    }
                }
                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
            {
                // Non-mesh content - copy stream to new Library path
                printItem.FileLocation = CreateLibraryPath(extension);
                using (var outStream = File.Create(printItem.FileLocation))
                {
                    stream.CopyTo(outStream);
                }
                printItem.Commit();
            }
        }
        private MatterControlApplication(double width, double height, out bool showWindow)
            : base(width, height)
        {
            Name       = "MatterControl";
            showWindow = false;

            // set this at startup so that we can tell next time if it got set to true in close
            UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1;

            this.commandLineArgs = Environment.GetCommandLineArgs();
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            bool forceSofwareRendering = false;

            for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++)
            {
                string command      = commandLineArgs[currentCommandIndex];
                string commandUpper = command.ToUpper();
                switch (commandUpper)
                {
                case "TEST":
                    CheckKnownAssemblyConditionalCompSymbols();
                    return;

                case "FORCE_SOFTWARE_RENDERING":
                    forceSofwareRendering = true;
                    GL.ForceSoftwareRendering();
                    break;

                case "MHSERIAL_TO_ANDROID":
                {
                    Dictionary <string, string> vidPid_NameDictionary = new Dictionary <string, string>();
                    string[] MHSerialLines = File.ReadAllLines(Path.Combine("..", "..", "StaticData", "Drivers", "MHSerial", "MHSerial.inf"));
                    foreach (string line in MHSerialLines)
                    {
                        if (line.Contains("=DriverInstall,"))
                        {
                            string name   = Regex.Match(line, "%(.*).name").Groups[1].Value;
                            string vid    = Regex.Match(line, "VID_(.*)&PID").Groups[1].Value;
                            string pid    = Regex.Match(line, "PID_([0-9a-fA-F]+)").Groups[1].Value;
                            string vidPid = "{0},{1}".FormatWith(vid, pid);
                            if (!vidPid_NameDictionary.ContainsKey(vidPid))
                            {
                                vidPid_NameDictionary.Add(vidPid, name);
                            }
                        }
                    }

                    using (StreamWriter deviceFilter = new StreamWriter("deviceFilter.txt"))
                    {
                        using (StreamWriter serialPort = new StreamWriter("serialPort.txt"))
                        {
                            foreach (KeyValuePair <string, string> vidPid_Name in vidPid_NameDictionary)
                            {
                                string[] vidPid = vidPid_Name.Key.Split(',');
                                int      vid    = Int32.Parse(vidPid[0], System.Globalization.NumberStyles.HexNumber);
                                int      pid    = Int32.Parse(vidPid[1], System.Globalization.NumberStyles.HexNumber);
                                serialPort.WriteLine("customTable.AddProduct(0x{0:X4}, 0x{1:X4}, cdcDriverType);  // {2}".FormatWith(vid, pid, vidPid_Name.Value));
                                deviceFilter.WriteLine("<!-- {2} -->\n<usb-device vendor-id=\"{0}\" product-id=\"{1}\" />".FormatWith(vid, pid, vidPid_Name.Value));
                            }
                        }
                    }
                }
                    return;

                case "CLEAR_CACHE":
                    AboutWidget.DeleteCacheData();
                    break;

                case "SHOW_MEMORY":
                    ShowMemoryUsed = true;
                    break;

                case "DO_GC_COLLECT_EVERY_DRAW":
                    ShowMemoryUsed       = true;
                    DoCGCollectEveryDraw = true;
                    break;

                case "CREATE_AND_SELECT_PRINTER":
                    if (currentCommandIndex + 1 <= commandLineArgs.Length)
                    {
                        currentCommandIndex++;
                        string   argument    = commandLineArgs[currentCommandIndex];
                        string[] printerData = argument.Split(',');
                        if (printerData.Length >= 2)
                        {
                            Printer ActivePrinter = new Printer();

                            ActivePrinter.Name  = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]);
                            ActivePrinter.Make  = printerData[0];
                            ActivePrinter.Model = printerData[1];

                            if (printerData.Length == 3)
                            {
                                ActivePrinter.ComPort = printerData[2];
                            }

                            PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter);
                            test.LoadDefaultSliceSettings(ActivePrinter.Make, ActivePrinter.Model);
                            ActivePrinterProfile.Instance.ActivePrinter = ActivePrinter;
                        }
                    }

                    break;

                case "CONNECT_TO_PRINTER":
                    if (currentCommandIndex + 1 <= commandLineArgs.Length)
                    {
                        PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter();
                    }
                    break;

                case "START_PRINT":
                    if (currentCommandIndex + 1 <= commandLineArgs.Length)
                    {
                        bool hasBeenRun = false;
                        currentCommandIndex++;
                        string fullPath = commandLineArgs[currentCommandIndex];
                        QueueData.Instance.RemoveAll();
                        if (!string.IsNullOrEmpty(fullPath))
                        {
                            string fileName = Path.GetFileNameWithoutExtension(fullPath);
                            QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath)));
                            PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) =>
                            {
                                if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected)
                                {
                                    hasBeenRun = true;
                                    PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible();
                                }
                            }, ref unregisterEvent);
                        }
                    }
                    break;

                case "SLICE_AND_EXPORT_GCODE":
                    if (currentCommandIndex + 1 <= commandLineArgs.Length)
                    {
                        currentCommandIndex++;
                        string fullPath = commandLineArgs[currentCommandIndex];
                        QueueData.Instance.RemoveAll();
                        if (!string.IsNullOrEmpty(fullPath))
                        {
                            string           fileName         = Path.GetFileNameWithoutExtension(fullPath);
                            PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath));
                            QueueData.Instance.AddItem(printItemWrapper);

                            SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
                            ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper);
                            exportForTest.ExportGcodeCommandLineUtility(fileName);
                        }
                    }
                    break;
                }

                if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper()))
                {
                    // If we are the only instance running then do nothing.
                    // Else send these to the running instance so it can load them.
                }
            }

            //WriteTestGCodeFile();
#if !DEBUG
            if (File.Exists("RunUnitTests.txt"))
#endif
            {
#if IS_WINDOWS_FORMS
                if (!Clipboard.IsInitialized)
                {
                    Clipboard.SetSystemClipboard(new WindowsFormsClipboard());
                }
#endif

                // you can turn this on to debug some bounds issues
                //GuiWidget.DebugBoundsUnderMouse = true;
            }

            GuiWidget.DefaultEnforceIntegerBounds = true;

            if (ActiveTheme.Instance.DisplayMode == ActiveTheme.ApplicationDisplayType.Touchscreen)
            {
                TextWidget.GlobalPointSizeScaleRatio = 1.3;
            }

            this.AddChild(ApplicationController.Instance.MainView);
            this.MinimumSize = minSize;
            this.Padding     = new BorderDouble(0); //To be re-enabled once native borders are turned off

#if false                                           // this is to test freeing gcodefile memory
            Button test = new Button("test");
            test.Click += (sender, e) =>
            {
                //MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile();
                //gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode");
                SystemWindow window = new SystemWindow(100, 100);
                window.ShowAsSystemWindow();
            };
            allControls.AddChild(test);
#endif
            this.AnchorAll();

            if (!forceSofwareRendering)
            {
                UseOpenGL = true;
            }
            string version = "1.4";

            Title = "MatterControl {0}".FormatWith(version);
            if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
            {
                Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra);
            }

            UiThread.RunOnIdle(CheckOnPrinter);

            string desktopPosition = ApplicationSettings.Instance.get("DesktopPosition");
            if (desktopPosition != null && desktopPosition != "")
            {
                string[] sizes = desktopPosition.Split(',');

                //If the desktop position is less than -10,-10, override
                int xpos = Math.Max(int.Parse(sizes[0]), -10);
                int ypos = Math.Max(int.Parse(sizes[1]), -10);

                DesktopPosition = new Point2D(xpos, ypos);
            }

            showWindow = true;
        }
        public List <PrintItem> ImportFromProjectArchive(string loadedFileName = null)
        {
            if (loadedFileName == null)
            {
                loadedFileName = defaultProjectPathAndFileName;
            }

            if (System.IO.File.Exists(loadedFileName))
            {
                FileStream fs              = File.OpenRead(loadedFileName);
                ZipArchive zip             = new ZipArchive(fs);
                int        projectHashCode = zip.GetHashCode();

                //If the temp folder doesn't exist - create it, otherwise clear it
                string stagingFolder = Path.Combine(applicationDataPath, "data", "temp", "project-extract", projectHashCode.ToString());
                if (!Directory.Exists(stagingFolder))
                {
                    Directory.CreateDirectory(stagingFolder);
                }
                else
                {
                    System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(@stagingFolder);
                    EmptyFolder(directory);
                }

                List <PrintItem> printItemList   = new List <PrintItem>();
                Project          projectManifest = null;

                foreach (ZipArchiveEntry zipEntry in zip.Entries)
                {
                    string sourceExtension = Path.GetExtension(zipEntry.Name).ToUpper();

                    // Note: directories have empty Name properties
                    //
                    // Only process ZipEntries that are:
                    //    - not directories and
                    //     - are in the ValidFileExtension list or
                    //     - have a .GCODE extension or
                    //     - are named manifest.json
                    if (!string.IsNullOrWhiteSpace(zipEntry.Name) &&
                        (zipEntry.Name == "manifest.json" ||
                         MeshFileIo.ValidFileExtensions().Contains(sourceExtension) ||
                         sourceExtension == ".GCODE"))
                    {
                        string extractedFileName = Path.Combine(stagingFolder, zipEntry.Name);

                        string neededPathForZip = Path.GetDirectoryName(extractedFileName);
                        if (!Directory.Exists(neededPathForZip))
                        {
                            Directory.CreateDirectory(neededPathForZip);
                        }

                        using (Stream zipStream = zipEntry.Open())
                            using (FileStream streamWriter = File.Create(extractedFileName))
                            {
                                zipStream.CopyTo(streamWriter);
                            }

                        if (zipEntry.Name == "manifest.json")
                        {
                            using (StreamReader sr = new System.IO.StreamReader(extractedFileName))
                            {
                                projectManifest = (Project)Newtonsoft.Json.JsonConvert.DeserializeObject(sr.ReadToEnd(), typeof(Project));
                            }
                        }
                    }
                }

                if (projectManifest != null)
                {
                    foreach (ManifestItem item in projectManifest.ProjectFiles)
                    {
                        for (int i = 1; i <= item.ItemQuantity; i++)
                        {
                            printItemList.Add(this.GetPrintItemFromFile(Path.Combine(stagingFolder, item.FileName), item.Name));
                        }
                    }
                }
                else
                {
                    string[] files = Directory.GetFiles(stagingFolder, "*.*", SearchOption.AllDirectories);
                    foreach (string fileName in files)
                    {
                        printItemList.Add(this.GetPrintItemFromFile(fileName, Path.GetFileNameWithoutExtension(fileName)));
                    }
                }

                return(printItemList);
            }
            else
            {
                return(null);
            }
        }