Пример #1
0
        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            try             // if we get a bad result we can get a target ivocation exception. In that case just don't show anything
            {
                byte[]      raw           = e.Result;
                Stream      stream        = new MemoryStream(raw);
                ImageBuffer unScaledImage = new ImageBuffer(10, 10, 32, new BlenderBGRA());
                StaticData.Instance.LoadImageData(stream, unScaledImage);
                // If the source image (the one we downloaded) is more than twice as big as our dest image.
                while (unScaledImage.Width > Image.Width * 2)
                {
                    // The image sampler we use is a 2x2 filter so we need to scale by a max of 1/2 if we want to get good results.
                    // So we scale as many times as we need to to get the Image to be the right size.
                    // If this were going to be a non-uniform scale we could do the x and y separatly to get better results.
                    ImageBuffer halfImage = new ImageBuffer(unScaledImage.Width / 2, unScaledImage.Height / 2, 32, scalingBlender);
                    halfImage.NewGraphics2D().Render(unScaledImage, 0, 0, 0, halfImage.Width / (double)unScaledImage.Width, halfImage.Height / (double)unScaledImage.Height);
                    unScaledImage = halfImage;
                }
                Image.NewGraphics2D().Render(unScaledImage, 0, 0, 0, Image.Width / (double)unScaledImage.Width, Image.Height / (double)unScaledImage.Height);
                Image.MarkImageChanged();
                Invalidate();

                if (LoadComplete != null)
                {
                    LoadComplete(this, null);
                }
            }
            catch (Exception)
            {
                GuiWidget.BreakInDebugger();
            }
        }
Пример #2
0
 public void Exit()
 {
     if (wasExited)
     {
         return;
     }
     wasExited = true;
     if (this.activeSession != null)
     {
         this.activeSession.SessionEnd = DateTime.Now;
         this.activeSession.Commit();
     }
     // lets wait a bit to make sure the commit has resolved.
     Thread.Sleep(100);
     try
     {
         dbSQLite.Close();
     }
     catch (Exception)
     {
         GuiWidget.BreakInDebugger();
         // we faild to close so lets wait a bit and try again
         Thread.Sleep(1000);
         try
         {
             dbSQLite.Close();
         }
         catch (Exception)
         {
             GuiWidget.BreakInDebugger();
         }
     }
 }
Пример #3
0
            public static void LoadConfigurationSettingsFromFileAsUnsaved(string pathAndFileName)
            {
                try
                {
                    if (File.Exists(pathAndFileName))
                    {
                        string[] lines = System.IO.File.ReadAllLines(pathAndFileName);
                        foreach (string line in lines)
                        {
                            //Ignore commented lines
                            if (line.Trim() != "" && !line.StartsWith("#"))
                            {
                                string[] settingLine = line.Split('=');
                                if (settingLine.Length > 1)
                                {
                                    string keyName             = settingLine[0].Trim();
                                    string settingDefaultValue = settingLine[1].Trim();

                                    //Add the setting to the active layer
                                    //SaveValue(keyName, settingDefaultValue);
                                    throw new NotImplementedException("load to dictionary");
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.Print(e.Message);
                    GuiWidget.BreakInDebugger();
                    Debug.WriteLine(string.Format("Error loading configuration: {0}", e));
                }
            }
Пример #4
0
        public bool InstallUpdate()
        {
            string downloadToken = ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentBuildToken);

            string updateFileName = Path.Combine(updateFileLocation, "{0}.{1}".FormatWith(downloadToken, InstallerExtension));

#if __ANDROID__
            string friendlyFileName = Path.Combine(updateFileLocation, "MatterControlSetup.apk");
#else
            string releaseVersion   = ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentReleaseVersion);
            string friendlyFileName = Path.Combine(updateFileLocation, "MatterControlSetup-{0}.{1}".FormatWith(releaseVersion, InstallerExtension));
#endif

            if (System.IO.File.Exists(friendlyFileName))
            {
                System.IO.File.Delete(friendlyFileName);
            }

            try
            {
                //Change download file to friendly file name
                System.IO.File.Move(updateFileName, friendlyFileName);
#if __ANDROID__
                if (InstallUpdateFromMainActivity != null)
                {
                    InstallUpdateFromMainActivity(this, null);
                }
                return(true);
#else
                int tries = 0;
                do
                {
                    Thread.Sleep(10);
                } while (tries++ < 100 && !File.Exists(friendlyFileName));

                //Run installer file
                Process installUpdate = new Process();
                installUpdate.StartInfo.FileName = friendlyFileName;
                installUpdate.Start();

                //Attempt to close current application
                SystemWindow topSystemWindow = MatterControlApplication.Instance as SystemWindow;
                if (topSystemWindow != null)
                {
                    topSystemWindow.CloseOnIdle();
                    return(true);
                }
#endif
            }
            catch
            {
                GuiWidget.BreakInDebugger();
                if (System.IO.File.Exists(friendlyFileName))
                {
                    System.IO.File.Delete(friendlyFileName);
                }
            }

            return(false);
        }
        public static void LoadUITheme()
        {
            //Load the default theme by index
            if (string.IsNullOrEmpty(UserSettings.Instance.get("ActiveThemeIndex")))
            {
                for (int i = 0; i < ActiveTheme.AvailableThemes.Count; i++)
                {
                    IThemeColors current = ActiveTheme.AvailableThemes[i];
                    if (current.Name == OemSettings.Instance.ThemeColor)
                    {
                        UserSettings.Instance.set("ActiveThemeIndex", i.ToString());
                        break;
                    }
                }
            }

            int themeIndex;

            if (int.TryParse(UserSettings.Instance.get("ActiveThemeIndex"), out themeIndex) && themeIndex < ActiveTheme.AvailableThemes.Count)
            {
                try
                {
                    ActiveTheme.Instance = ActiveTheme.AvailableThemes[themeIndex];
                }
                catch
                {
                    GuiWidget.BreakInDebugger();
                }
            }
        }
Пример #6
0
        private static int CleanDirectory(string path, int daysOldToDelete, List <string> extensionsToDelete, HashSet <string> filesToKeep = null)
        {
            int contentCount = 0;

            if (!Directory.Exists(path))
            {
                return(0);
            }

            foreach (string directory in Directory.EnumerateDirectories(path).ToArray())
            {
                int directoryContentCount = CleanDirectory(directory, daysOldToDelete, extensionsToDelete, filesToKeep);
                if (directoryContentCount == 0 &&
                    !folderNamesToPreserve.Contains(Path.GetFileName(directory)))
                {
                    try
                    {
                        Directory.Delete(directory);
                    }
                    catch (Exception)
                    {
                        GuiWidget.BreakInDebugger();
                    }
                }
                else
                {
                    // it has a directory that has content
                    contentCount++;
                }
            }

            foreach (string file in Directory.EnumerateFiles(path, "*.*"))
            {
                bool fileIsNew = new FileInfo(file).LastAccessTime > DateTime.Now.AddDays(-daysOldToDelete);
                bool forceKeep = filesToKeep != null && filesToKeep.Contains(file);

                if (fileIsNew ||
                    forceKeep ||
                    !extensionsToDelete.Contains(Path.GetExtension(file).ToUpper()))
                {
                    contentCount++;
                }
                else
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception)
                    {
                        GuiWidget.BreakInDebugger();
                    }
                }
            }

            return(contentCount);
        }
        private static string CopyFile(string sourceFile, string destFileName, string destPath)
        {
            // make sure the directory exists
            try
            {
                Directory.CreateDirectory(destPath);
            }
            catch (Exception e)
            {
                GuiWidget.BreakInDebugger();
            }

            // save it to the root directory
            string outputFileName = Path.Combine(destPath, destFileName);

            outputFileName = Path.ChangeExtension(outputFileName, Path.GetExtension(sourceFile));
            // and copy the file
            try
            {
                if (!File.Exists(outputFileName))
                {
                    File.Copy(sourceFile, outputFileName);
                }
                else                 // make a new file and append a number so that we are not destructive
                {
                    string directory = Path.GetDirectoryName(outputFileName);
                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputFileName);
                    string extension = Path.GetExtension(outputFileName);
                    // get the filename without a number on the end
                    int lastSpaceIndex = fileNameWithoutExtension.LastIndexOf(' ');
                    if (lastSpaceIndex != -1)
                    {
                        int endingNumber;
                        // check if the last set of characters is a number
                        if (int.TryParse(fileNameWithoutExtension.Substring(lastSpaceIndex), out endingNumber))
                        {
                            fileNameWithoutExtension = fileNameWithoutExtension.Substring(0, lastSpaceIndex);
                        }
                    }
                    int    numberToAppend = 2;
                    string fileNameToUse  = Path.Combine(directory, fileNameWithoutExtension + " " + numberToAppend.ToString() + extension);
                    while (File.Exists(fileNameToUse))
                    {
                        numberToAppend++;
                        fileNameToUse = Path.Combine(directory, fileNameWithoutExtension + " " + numberToAppend.ToString() + extension);
                    }
                    File.Copy(sourceFile, fileNameToUse);
                }
            }
            catch (Exception e)
            {
                GuiWidget.BreakInDebugger();
            }

            return(outputFileName);
        }
Пример #8
0
        private void DownloadUpdateTask()
        {
            if (!WaitingToCompleteTransaction())
            {
                string downloadToken = ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentBuildToken);

                if (downloadToken == null)
                {
#if DEBUG
                    throw new Exception("Build token should not be null");
#endif
                    //
                }
                else
                {
                    downloadAttempts++;
                    SetUpdateStatus(UpdateStatusStates.UpdateDownloading);
                    string downloadUri = $"{MatterControlApplication.MCWSBaseUri}/downloads/development/{ApplicationSettings.Instance.get(LatestVersionRequest.VersionKey.CurrentBuildToken)}";

                    //Make HEAD request to determine the size of the download (required by GAE)
                    System.Net.WebRequest request = System.Net.WebRequest.Create(downloadUri);
                    request.Method = "HEAD";

                    try
                    {
                        WebResponse response = request.GetResponse();
                        downloadSize = (int)response.ContentLength;
                    }
                    catch
                    {
                        GuiWidget.BreakInDebugger();
                        //Unknown download size
                        downloadSize = 0;
                    }

                    if (!System.IO.Directory.Exists(updateFileLocation))
                    {
                        System.IO.Directory.CreateDirectory(updateFileLocation);
                    }

                    updateFileName = Path.Combine(updateFileLocation, string.Format("{0}.{1}", downloadToken, InstallerExtension));

                    webClient = new WebClient();
                    webClient.DownloadFileCompleted   += new AsyncCompletedEventHandler(DownloadCompleted);
                    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
                    try
                    {
                        webClient.DownloadFileAsync(new Uri(downloadUri), updateFileName);
                    }
                    catch
                    {
                    }
                }
            }
        }
Пример #9
0
        public SliceEngineSelector(string label)
            : base(label)
        {
            HAnchor = HAnchor.ParentLeftRight;

            //Add Each SliceEngineInfo Objects to DropMenu
            foreach (SliceEngineInfo engineMenuItem in SlicingQueue.AvailableSliceEngines)
            {
                bool engineAllowed = true;
                if (ActiveSliceSettings.Instance.ExtruderCount > 1 && engineMenuItem.Name != "MatterSlice")
                {
                    engineAllowed = false;
                }

                if (engineAllowed)
                {
                    MenuItem item = AddItem(engineMenuItem.Name);
                    ActivePrinterProfile.SlicingEngineTypes itemEngineType = engineMenuItem.GetSliceEngineType();
                    item.Selected += (sender, e) =>
                    {
                        if (ActivePrinterProfile.Instance.ActiveSliceEngineType != itemEngineType)
                        {
                            ActivePrinterProfile.Instance.ActiveSliceEngineType = itemEngineType;
                            ApplicationController.Instance.ReloadAdvancedControlsPanel();
                        }
                    };

                    //Set item as selected if it matches the active slice engine
                    if (engineMenuItem.GetSliceEngineType() == ActivePrinterProfile.Instance.ActiveSliceEngineType)
                    {
                        SelectedLabel = engineMenuItem.Name;
                    }
                }
            }

            //If nothing is selected (ie selected engine is not available) set to
            if (SelectedLabel == "")
            {
                try
                {
                    SelectedLabel = MatterSliceInfo.DisplayName;
                }
                catch (Exception e)
                {
                    Debug.Print(e.Message);
                    GuiWidget.BreakInDebugger();
                    throw new Exception("MatterSlice is not available, for some strange reason");
                }
            }

            MinimumSize = new Vector2(LocalBounds.Width, LocalBounds.Height);
        }
Пример #10
0
 public void DoPostLoadInitialization()
 {
     try
     {
         gCodeRenderer.GCodeFileToDraw?.GetFilamentUsedMm(ActiveSliceSettings.Instance.GetValue <double>(SettingsKey.filament_diameter));
     }
     catch (Exception e)
     {
         Debug.Print(e.Message);
         GuiWidget.BreakInDebugger();
     }
     gCodeRenderer.CreateFeaturesForLayerIfRequired(0);
 }
        public SliceEngineSelector(string label)
            : base(label)
        {
            HAnchor = HAnchor.ParentLeftRight;

            //Add Each SliceEngineInfo Objects to DropMenu
            foreach (SliceEngineInfo engineMenuItem in SlicingQueue.AvailableSliceEngines)
            {
                bool engineAllowed = true;
                if (ActiveSliceSettings.Instance.GetValue <int>(SettingsKey.extruder_count) > 1 && engineMenuItem.Name != "MatterSlice")
                {
                    engineAllowed = false;
                }

                if (engineAllowed)
                {
                    MenuItem           item           = AddItem(engineMenuItem.Name);
                    SlicingEngineTypes itemEngineType = engineMenuItem.GetSliceEngineType();
                    item.Selected += (sender, e) =>
                    {
                        if (ActiveSliceSettings.Instance.Helpers.ActiveSliceEngineType() != itemEngineType)
                        {
                            ActiveSliceSettings.Instance.Helpers.ActiveSliceEngineType(itemEngineType);
                            ApplicationController.Instance.ReloadAdvancedControlsPanel();
                        }
                    };

                    //Set item as selected if it matches the active slice engine
                    if (engineMenuItem.GetSliceEngineType() == ActiveSliceSettings.Instance.Helpers.ActiveSliceEngineType())
                    {
                        SelectedLabel = engineMenuItem.Name;
                    }
                }
            }

            //If nothing is selected (i.e. selected engine is not available) set to
            if (SelectedLabel == "")
            {
                try
                {
                    SelectedLabel = MatterSliceInfo.DisplayName;
                }
                catch (Exception ex)
                {
                    GuiWidget.BreakInDebugger(ex.Message);
                    throw new Exception("Unable to find MatterSlice executable");
                }
            }

            MinimumSize = new Vector2(LocalBounds.Width, LocalBounds.Height);
        }
Пример #12
0
        private AnchoredDropDownList CreateDropdown()
        {
            AnchoredDropDownList dropDownList = new AnchoredDropDownList("- default -", maxHeight: 300);

            dropDownList.Margin      = new BorderDouble(0, 3);
            dropDownList.MinimumSize = new Vector2(dropDownList.LocalBounds.Width, dropDownList.LocalBounds.Height);
            MenuItem defaultMenuItem = dropDownList.AddItem("- default -", "0");

            defaultMenuItem.Selected += new EventHandler(onItemSelect);

            IEnumerable <DataStorage.SliceSettingsCollection> collections = GetCollections();

            foreach (DataStorage.SliceSettingsCollection collection in collections)
            {
                MenuItem menuItem = dropDownList.AddItem(collection.Name, collection.Id.ToString());
                menuItem.Selected += new EventHandler(onItemSelect);
            }

            MenuItem addNewPreset = dropDownList.AddItem("<< Add >>", "new");

            addNewPreset.Selected += new EventHandler(onNewItemSelect);

            if (filterTag == "material")
            {
                try
                {
                    dropDownList.SelectedValue = ActivePrinterProfile.Instance.GetMaterialSetting(presetIndex).ToString();
                }
                catch (Exception e)
                {
                    Debug.Print(e.Message);
                    GuiWidget.BreakInDebugger();
                    //Unable to set selected value
                }
            }
            else if (filterTag == "quality")
            {
                try
                {
                    dropDownList.SelectedValue = ActivePrinterProfile.Instance.ActiveQualitySettingsID.ToString();
                }
                catch (Exception e)
                {
                    Debug.Print(e.Message);
                    GuiWidget.BreakInDebugger();
                    //Unable to set selected value
                }
            }

            return(dropDownList);
        }
Пример #13
0
 public PrintItemWrapper(int printItemId)
 {
     this.PrintItem = Datastore.Instance.dbSQLite.Table <PrintItem>().Where(v => v.Id == printItemId).Take(1).FirstOrDefault();
     try
     {
         this.fileType = Path.GetExtension(this.FileLocation).ToUpper();
     }
     catch (Exception e)
     {
         Debug.Print(e.Message);
         GuiWidget.BreakInDebugger();
         //file not found
     }
 }
Пример #14
0
        public void AddTestResult(bool pass, string resultDescription = "")
        {
            results.Add(new TestResult()
            {
                result      = pass,
                description = resultDescription,
            });

            if (!pass)
            {
                // let us look at this at the time durring test run under the debugger
                GuiWidget.BreakInDebugger(resultDescription);
            }
        }
Пример #15
0
 private static void RemoveDirectory(string directoryToRemove)
 {
     try
     {
         if (Directory.Exists(directoryToRemove))
         {
             Directory.Delete(directoryToRemove, true);
         }
     }
     catch (Exception)
     {
         GuiWidget.BreakInDebugger();
     }
 }
        private void CheckOnPrinter()
        {
            try
            {
                PrinterConnectionAndCommunication.Instance.OnIdle();
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
                GuiWidget.BreakInDebugger();
#if DEBUG
                throw e;
#endif
            }
            UiThread.RunOnIdle(CheckOnPrinter);
        }
Пример #17
0
        public Datastore()
        {
            if (!File.Exists(datastoreLocation))
            {
                ApplicationDataStorage.Instance.FirstRun = true;
            }

            OSType osType = OsInformation.OperatingSystem;

            switch (osType)
            {
            case OSType.Windows:
                dbSQLite = new SQLiteWin32.SQLiteConnection(datastoreLocation);
                break;

            case OSType.Mac:
                dbSQLite = new SQLiteUnix.SQLiteConnection(datastoreLocation);
                break;

            case OSType.X11:
                dbSQLite = new SQLiteUnix.SQLiteConnection(datastoreLocation);
                break;

            case OSType.Android:
                dbSQLite = new SQLiteAndroid.SQLiteConnection(datastoreLocation);
                break;

            default:
                throw new NotImplementedException();
            }

            if (TEST_FLAG)
            {
                //In test mode - attempt to drop all tables (in case db was locked when we tried to delete it)
                foreach (Type table in dataStoreTables)
                {
                    try
                    {
                        this.dbSQLite.DropTable(table);
                    }
                    catch
                    {
                        GuiWidget.BreakInDebugger();
                    }
                }
            }
        }
Пример #18
0
 public void InstallUpdate(object sender, EventArgs e)
 {
     try
     {
         if (!UpdateControlData.Instance.InstallUpdate())
         {
             installUpdateLink.Visible = false;
             updateStatusText.Text     = string.Format("Oops! Unable to install update.".Localize());
         }
     }
     catch
     {
         GuiWidget.BreakInDebugger();
         installUpdateLink.Visible = false;
         updateStatusText.Text     = string.Format("Oops! Unable to install update.".Localize());
     }
 }
Пример #19
0
        public static void DoPostLoadInitialization(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            GCodeRenderer gCodeRenderer = (GCodeRenderer)doWorkEventArgs.Argument;

            try
            {
                if (gCodeRenderer.GCodeFileToDraw != null)
                {
                    gCodeRenderer.GCodeFileToDraw.GetFilamentUsedMm(ActiveSliceSettings.Instance.FilamentDiameter);
                }
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
                GuiWidget.BreakInDebugger();
            }
            gCodeRenderer.CreateFeaturesForLayerIfRequired(0);
        }
Пример #20
0
        private void TryHandleUpdate()
        {
            retryCount++;
            try
            {
                if (retryCount < maxRetries)
                {
                    Datastore.Instance.dbSQLite.Update(this);
                }
            }
            catch (Exception)
            {
                GuiWidget.BreakInDebugger();
                Thread.Sleep(100);
                this.TryHandleUpdate();
            }

            retryCount = 0;
        }
Пример #21
0
        public override void OnDraw(Graphics2D graphics2D)
        {
            if (!startedLoad)
            {
                try
                {
                    startedLoad = true;
                    WebClient client = new WebClient();
                    client.DownloadDataCompleted += client_DownloadDataCompleted;
                    client.DownloadDataAsync(new Uri(uriToLoad));
                }
                catch (Exception)
                {
                    GuiWidget.BreakInDebugger();
                }
            }

            base.OnDraw(graphics2D);
        }
        public bool LoadImageData(Stream stream, ImageSequence destImageSequence)
        {
            var gifImg = System.Drawing.Image.FromStream(stream);

            if (gifImg != null)
            {
                FrameDimension dimension = new FrameDimension(gifImg.FrameDimensionsList[0]);
                // Number of frames
                int frameCount = gifImg.GetFrameCount(dimension);

                for (int i = 0; i < frameCount; i++)
                {
                    // Return an Image at a certain index
                    gifImg.SelectActiveFrame(dimension, i);

                    using (var bitmap = new Bitmap(gifImg))
                    {
                        var frame = new ImageBuffer();
                        ConvertBitmapToImage(frame, bitmap);
                        destImageSequence.AddImage(frame);
                    }
                }

                try
                {
                    PropertyItem item = gifImg.GetPropertyItem(0x5100);                     // FrameDelay in libgdiplus
                    // Time is in 1/100th of a second
                    destImageSequence.SecondsPerFrame = (item.Value[0] + item.Value[1] * 256) / 100.0;
                }
                catch (Exception e)
                {
                    Debug.Print(e.Message);
                    GuiWidget.BreakInDebugger();
                    destImageSequence.SecondsPerFrame = 2;
                }

                return(true);
            }

            return(false);
        }
Пример #23
0
        public static GCodeFileLoaded Load(Stream fileStream)
        {
            GCodeFileLoaded loadedGCode = null;

            try
            {
                string gCodeString = "";
                using (var reader = new StreamReader(fileStream))
                {
                    gCodeString = reader.ReadToEnd();
                }

                loadedGCode = ParseFileContents(gCodeString, CancellationToken.None, null);
            }
            catch (IOException e)
            {
                Debug.Print(e.Message);
                GuiWidget.BreakInDebugger();
            }

            return(loadedGCode);
        }
        public SettingsLayer LoadConfigurationSettingsFromFile(string pathAndFileName, DataStorage.SliceSettingsCollection collection)
        {
            Dictionary <string, DataStorage.SliceSetting> settingsDictionary = new Dictionary <string, DataStorage.SliceSetting>();
            SettingsLayer activeCollection;

            try
            {
                if (StaticData.Instance.FileExists(pathAndFileName))
                {
                    foreach (string line in StaticData.Instance.ReadAllLines(pathAndFileName))
                    {
                        //Ignore commented lines
                        if (!line.StartsWith("#"))
                        {
                            string[] settingLine         = line.Split('=');
                            string   keyName             = settingLine[0].Trim();
                            string   settingDefaultValue = settingLine[1].Trim();

                            DataStorage.SliceSetting sliceSetting = new DataStorage.SliceSetting();
                            sliceSetting.Name  = keyName;
                            sliceSetting.Value = settingDefaultValue;

                            settingsDictionary.Add(keyName, sliceSetting);
                        }
                    }
                    activeCollection = new SettingsLayer(collection, settingsDictionary);
                    return(activeCollection);
                }
                return(null);
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
                GuiWidget.BreakInDebugger();
                Debug.WriteLine(string.Format("Error loading configuration: {0}", e));
                return(null);
            }
        }
Пример #25
0
 private void onExportLogFileSelected(SaveFileDialogParams saveParams)
 {
     if (!string.IsNullOrEmpty(saveParams.FileName))
     {
         string filePathToSave = saveParams.FileName;
         if (filePathToSave != null && filePathToSave != "")
         {
             try
             {
                 textScrollWidget.WriteToFile(filePathToSave);
             }
             catch (UnauthorizedAccessException e)
             {
                 Debug.Print(e.Message);
                 GuiWidget.BreakInDebugger();
                 PrinterOutputCache.Instance.PrinterLines.Add("");
                 PrinterOutputCache.Instance.PrinterLines.Add(writeFaildeWaring);
                 PrinterOutputCache.Instance.PrinterLines.Add(cantAccessPath.FormatWith(filePathToSave));
                 PrinterOutputCache.Instance.PrinterLines.Add("");
             }
         }
     }
 }
Пример #26
0
        public static async Task <GCodeFileLoaded> LoadInBackground(string fileName, Action <double, string> progressReporter)
        {
            if (Path.GetExtension(fileName).ToUpper() == ".GCODE")
            {
                try
                {
                    if (File.Exists(fileName) && !FileTooBigToLoad(fileName))
                    {
                        return(await Task.Run(() =>
                        {
                            return ParseFileContents(File.ReadAllText(fileName), CancellationToken.None, progressReporter);
                        }));
                    }
                }
                catch (IOException e)
                {
                    Debug.Print(e.Message);
                    GuiWidget.BreakInDebugger();
                }
            }

            return(null);
        }
Пример #27
0
        public ActiveTheme()
        {
            //Load the default theme by index
            if (string.IsNullOrEmpty(ActiveSliceSettings.Instance.ActiveValue("MatterControl.ActiveThemeIndex")))
            {
                bool foundOemColor = false;
                for (int i = 0; i < AvailableThemes.Count; i++)
                {
                    Theme current = AvailableThemes[i];
                    if (current.Name == OemSettings.Instance.ThemeColor)
                    {
                        ActiveSliceSettings.Instance.SetActiveValue("MatterControl.ActiveThemeIndex", i.ToString());
                        foundOemColor = true;
                        break;
                    }
                }

                if (!foundOemColor)
                {
                    ActiveSliceSettings.Instance.SetActiveValue("MatterControl.ActiveThemeIndex", defaultThemeIndex.ToString());
                }
            }

            int themeIndex;

            try
            {
                themeIndex = Convert.ToInt32(ActiveSliceSettings.Instance.ActiveValue("MatterControl.ActiveThemeIndex"));
            }
            catch
            {
                GuiWidget.BreakInDebugger();
                themeIndex = defaultThemeIndex;
            }

            LoadThemeSettings(themeIndex);
        }
Пример #28
0
        public ActiveTheme()
        {
            //Load the default theme by index
            if (UserSettings.Instance.get("ActiveThemeIndex") == null)
            {
                bool foundOemColor = false;
                for (int i = 0; i < AvailableThemes.Count; i++)
                {
                    Theme current = AvailableThemes[i];
                    if (current.Name == OemSettings.Instance.ThemeColor)
                    {
                        UserSettings.Instance.set("ActiveThemeIndex", i.ToString());
                        foundOemColor = true;
                        break;
                    }
                }

                if (!foundOemColor)
                {
                    UserSettings.Instance.set("ActiveThemeIndex", defaultThemeIndex.ToString());
                }
            }

            int themeIndex;

            try
            {
                themeIndex = Convert.ToInt32(UserSettings.Instance.get("ActiveThemeIndex"));
            }
            catch
            {
                GuiWidget.BreakInDebugger();
                themeIndex = defaultThemeIndex;
            }

            LoadThemeSettings(themeIndex);
        }
Пример #29
0
 public static bool SaveFileDialog(SaveFileDialogParams saveParams, Action <SaveFileDialogParams> callback)
 {
     return(FileDialogCreatorPlugin.SaveFileDialog(saveParams, (SaveFileDialogParams outputSaveParams) =>
     {
         try
         {
             if (outputSaveParams.FileName != "")
             {
                 string directory = Path.GetDirectoryName(outputSaveParams.FileName);
                 if (directory != null && directory != "")
                 {
                     lastDirectoryUsed = directory;
                 }
             }
         }
         catch (Exception e)
         {
             Debug.Print(e.Message);
             GuiWidget.BreakInDebugger();
         }
         callback(outputSaveParams);
     }
                                                   ));
 }
Пример #30
0
 public static void RestoreStaticDataAfterTesting(DataFolderState state, bool closeDataBase)
 {
     if (state.undoDataRename)
     {
         Thread.Sleep(500);
         if (closeDataBase)
         {
             Datastore.Instance.Exit();
         }
         Stopwatch timeTryingToDelete = Stopwatch.StartNew();
         while (Directory.Exists(state.userDataPath) &&
                timeTryingToDelete.Elapsed.TotalSeconds < 10)
         {
             try
             {
                 Directory.Delete(state.userDataPath, true);
             }
             catch (Exception e)
             {
                 Debug.Print(e.Message);
                 GuiWidget.BreakInDebugger();
             }
         }
         Stopwatch time = Stopwatch.StartNew();
         // Wait for up to some amount of time for the directory to be gone.
         while (Directory.Exists(state.userDataPath) &&
                time.ElapsedMilliseconds < 100)
         {
             Thread.Sleep(1);                     // make sure we are not eating all the cpu time.
         }
         if (!Directory.Exists(state.userDataPath))
         {
             Directory.Move(state.renamedUserDataPath, state.userDataPath);
         }
     }
 }