Beispiel #1
0
        /// <summary>
        /// Loads image at specified index
        /// </summary>
        /// <param name="index">The index of file to load from Pics</param>
        internal static async Task LoadPicAt(int index)
        {
            Preloader.PreloadValue preloadValue;
            // Error checking to fix rare cases of crashing
            if (Pics.Count < index)
            {
                preloadValue = await PicErrorFix(index).ConfigureAwait(true);

                if (preloadValue == null)
                {
                    /// Try to recover
                    /// TODO needs testing
                    Reload(true);
                    return;
                }
            }

            FolderIndex  = index;
            preloadValue = Preloader.Get(Pics[index]);

            // Initate loading behavior, if needed
            if (preloadValue == null || preloadValue.isLoading)
            {
                CanNavigate = false; // Dissallow changing image while loading

                if (!GalleryFunctions.IsOpen)
                {
                    // Show a thumbnail while loading
                    var thumb = GetThumb(index);
                    await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
                    {
                        // Set loading from translation service
                        SetLoadingString();

                        // Don't allow image size to stretch the whole screen
                        if (xWidth == 0)
                        {
                            ConfigureWindows.GetMainWindow.MainImage.Width = ConfigureWindows.GetMainWindow.ParentContainer.ActualWidth;
                            ConfigureWindows.GetMainWindow.MainImage.Height = ConfigureWindows.GetMainWindow.ParentContainer.ActualHeight;
                        }

                        if (thumb != null)
                        {
                            ConfigureWindows.GetMainWindow.MainImage.Source = thumb;
                        }
                    }));
                }

                if (preloadValue == null) // Error correctiom
                {
                    await Preloader.Add(Pics[index]).ConfigureAwait(true);

                    preloadValue = Preloader.Get(Pics[index]);
                }
                while (preloadValue.isLoading)
                {
                    // Wait for finnished result
                    await Task.Delay(3).ConfigureAwait(true);
                }
            }

            // Check if works, if not show error message
            if (preloadValue == null || preloadValue.bitmapSource == null)
            {
                preloadValue = new Preloader.PreloadValue(ImageDecoder.ImageErrorMessage(), false);
            }

            // Need to put UI change in dispatcher to fix slideshow bug
            await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, (Action)(() =>
            {
                // Scroll to top if scroll enabled
                if (IsScrollEnabled)
                {
                    ConfigureWindows.GetMainWindow.Scroller.ScrollToTop();
                }

                // Reset transforms if needed
                if (UILogic.TransformImage.Rotation.Flipped || UILogic.TransformImage.Rotation.Rotateint != 0)
                {
                    UILogic.TransformImage.Rotation.Flipped = false;
                    UILogic.TransformImage.Rotation.Rotateint = 0;
                    GetImageSettingsMenu.FlipButton.TheButton.IsChecked = false;

                    ConfigureWindows.GetMainWindow.MainImage.LayoutTransform = null;
                }

                ConfigureWindows.GetMainWindow.MainImage.Source = preloadValue.bitmapSource;
                FitImage(preloadValue.bitmapSource.PixelWidth, preloadValue.bitmapSource.PixelHeight);
                SetTitleString(preloadValue.bitmapSource.PixelWidth, preloadValue.bitmapSource.PixelHeight, index);
            }));

            // Update values
            CanNavigate  = true;
            FreshStartup = false;

            if (ConfigureWindows.GetImageInfoWindow != null)
            {
                if (ConfigureWindows.GetImageInfoWindow.IsVisible)
                {
                    ConfigureWindows.GetImageInfoWindow.UpdateValues();
                }
            }

            if (Pics.Count > 1)
            {
                Taskbar.Progress(index, Pics.Count);

                // Preload images \\
                await Preloader.PreLoad(index).ConfigureAwait(false);
            }

            // Add recent files, except when browing archive
            if (string.IsNullOrWhiteSpace(TempZipFile))
            {
                RecentFiles.Add(Pics[index]);
            }
        }
        public void File_Open(string fileName)
        {
            var oldFile      = File_Current;
            var oldDirectory = File_Directory;
            var oldLastWrite = File_LastWrite;
            var oldSaveMode  = File_SaveMode;
            var oldHandler   = Handler;

            var cancel = false;

            using (new Hourglass())
            {
                try
                {
                    Handler = new TabularModelHandler(fileName, Preferences.Current.GetSettings());

                    if (Handler.SourceType == ModelSourceType.Pbit)
                    {
                        switch (Handler.PowerBIGovernance.GovernanceMode)
                        {
                        case TOMWrapper.PowerBI.PowerBIGovernanceMode.ReadOnly:
                            MessageBox.Show("Editing a Power BI Template (.pbit) file that does not use the Enhanced Model Metadata (V3) format is not allowed, unless you enable Experimental Power BI Features under File > Preferences.\n\nTabular Editor will still load the file in read-only mode.", "Power BI Template Read-only", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            break;

                        case TOMWrapper.PowerBI.PowerBIGovernanceMode.V3Restricted:
                            break;

                        case TOMWrapper.PowerBI.PowerBIGovernanceMode.Unrestricted:
                            if (MessageBox.Show("Experimental Power BI features is enabled. You can edit any object and property of this Power BI Template file but be aware that many types of changes ARE NOT CURRENTLY SUPPORTED by Microsoft.\n\nKeep a backup of your .pbit file and proceed at your own risk.", "Power BI Template Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                            {
                                cancel = true;
                            }
                            break;
                        }
                    }

                    if (!cancel)
                    {
                        TabularModelHandler.Cleanup();
                        if (oldHandler != null && File_SaveMode == ModelSourceType.Database)
                        {
                            oldHandler.OnExternalChange -= Handler_OnExternalChange;
                        }
                        File_Current   = Handler.Source;
                        File_Directory = FileSystemHelper.DirectoryFromPath(Handler.Source);
                        File_SaveMode  = Handler.SourceType;

                        // TODO: Use a FileSystemWatcher to watch for changes to the currently loaded file(s)
                        // and handle them appropriately. For now, we just store the LastWriteDate of the loaded
                        // file, to ensure that we don't accidentally overwrite newer changes when saving.
                        File_LastWrite = File_SaveMode == ModelSourceType.Folder ? GetLastDirChange(File_Current) : File.GetLastWriteTime(File_Current);

                        LoadTabularModelToUI();
                        RecentFiles.Add(fileName);
                        RecentFiles.Save();
                        UI.FormMain.PopulateRecentFilesList();
                    }
                }
                catch (Exception ex)
                {
                    cancel = true;
                    MessageBox.Show(ex.Message, "Error loading Model from disk", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (cancel)
            {
                Handler        = oldHandler;
                File_Current   = oldFile;
                File_Directory = oldDirectory;
                File_SaveMode  = oldSaveMode;
                File_LastWrite = oldLastWrite;
            }
        }
Beispiel #3
0
        /// <summary>
        /// Loads image at specified index
        /// </summary>
        /// <param name="index">The index of file to load from Pics</param>
        internal static async void Pic(int index)
        {
            FolderIndex = index;

            // Declare variable to be used to set image source
            BitmapSource bitmapSource;

            // Error checking to fix rare cases of crashing
            if (Pics.Count < index)
            {
                bitmapSource = await PicErrorFix(index).ConfigureAwait(true);

                if (bitmapSource == null)
                {
                    /// Try to recover
                    /// TODO needs testing
                    Reload(true);
                    return;
                }
            }

            /// Retrieve from preloader if available
            /// if not, it will be null
            bitmapSource = Preloader.Get(Pics[index]);

            // Initate loading behavior, if needed
            if (bitmapSource == null)
            {
                // Dissallow changing image while loading
                CanNavigate = false;

                if (!GalleryFunctions.IsOpen)
                {
                    await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
                    {
                        // Set loading from translation service
                        SetLoadingString();
                    }));

                    // Show a thumbnail while loading
                    var thumb = GetThumb(index);
                    if (thumb != null && Properties.Settings.Default.PicGallery != 2)
                    {
                        await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
                        {
                            // Don't allow image size to stretch the whole screen
                            if (xWidth == 0)
                            {
                                ConfigureWindows.GetMainWindow.MainImage.Width = ConfigureWindows.GetMainWindow.MinWidth;
                                ConfigureWindows.GetMainWindow.MainImage.Height = ConfigureWindows.GetMainWindow.MinHeight;
                            }
                            else
                            {
                                ConfigureWindows.GetMainWindow.MainImage.Width = xWidth;
                                ConfigureWindows.GetMainWindow.MainImage.Height = xHeight;
                            }

                            ConfigureWindows.GetMainWindow.MainImage.Source = thumb;
                        }));
                    }
                }

                // Get it!
                await Preloader.Add(Pics[index]).ConfigureAwait(true);

                // Retry
                bitmapSource = Preloader.Get(Pics[index]);

                if (bitmapSource == null)
                {
                    // If pic is still null, image can't be rendered
                    bitmapSource = ImageDecoder.ImageErrorMessage();
                }
            }

            // Need to put UI change in dispatcher to fix slideshow bug
            await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, (Action)(() =>
            {
                // Scroll to top if scroll enabled
                if (IsScrollEnabled)
                {
                    ConfigureWindows.GetMainWindow.Scroller.ScrollToTop();
                }

                // Reset transforms if needed
                if (UILogic.TransformImage.Rotation.Flipped || UILogic.TransformImage.Rotation.Rotateint != 0)
                {
                    UILogic.TransformImage.Rotation.Flipped = false;
                    UILogic.TransformImage.Rotation.Rotateint = 0;
                    GetImageSettingsMenu.FlipButton.TheButton.IsChecked = false;

                    ConfigureWindows.GetMainWindow.MainImage.LayoutTransform = null;
                }

                ConfigureWindows.GetMainWindow.MainImage.Source = bitmapSource;
                FitImage(bitmapSource.PixelWidth, bitmapSource.PixelHeight);
                SetTitleString(bitmapSource.PixelWidth, bitmapSource.PixelHeight, index);
            }));

            // Update values
            CanNavigate  = true;
            FreshStartup = false;

            if (ConfigureWindows.GetImageInfoWindow != null)
            {
                if (ConfigureWindows.GetImageInfoWindow.IsVisible)
                {
                    ConfigureWindows.GetImageInfoWindow.UpdateValues();
                }
            }

            if (Pics.Count > 1)
            {
                Taskbar.Progress(index, Pics.Count);

                // Preload images \\
                await Preloader.PreLoad(index).ConfigureAwait(false);
            }

            if (string.IsNullOrWhiteSpace(TempZipFile))
            {
                RecentFiles.Add(Pics[index]);
            }
        }
Beispiel #4
0
        public static void Read()
        {
            RecentFiles.Clear();
            Settings.Clear();
            Hotkeys.Clear();
            AdditionalSettings.Clear();
            FavouriteTextureFolders.Clear();

            var root = ReadSettingsFile();

            if (root == null)
            {
                return;
            }

            var settings = root.Children.FirstOrDefault(x => x.Name == "Settings");

            if (settings != null)
            {
                foreach (var key in settings.GetPropertyKeys())
                {
                    Settings.Add(new Setting {
                        Key = key, Value = settings[key]
                    });
                }
            }
            var recents = root.Children.FirstOrDefault(x => x.Name == "RecentFiles");

            if (recents != null)
            {
                foreach (var key in recents.GetPropertyKeys())
                {
                    int i;
                    if (int.TryParse(key, out i))
                    {
                        RecentFiles.Add(new RecentFile {
                            Location = recents[key], Order = i
                        });
                    }
                }
            }
            var hotkeys = root.Children.FirstOrDefault(x => x.Name == "Hotkeys");

            if (hotkeys != null)
            {
                foreach (var key in hotkeys.GetPropertyKeys())
                {
                    var spl = key.Split(':');
                    Hotkeys.Add(new Hotkey {
                        ID = spl[0], HotkeyString = hotkeys[key]
                    });
                }
            }

            Serialise.DeserialiseSettings(Settings.ToDictionary(x => x.Key, x => x.Value));
            CBRE.Settings.Hotkeys.SetupHotkeys(Hotkeys);

            var additionalSettings = root.Children.FirstOrDefault(x => x.Name == "AdditionalSettings");

            if (additionalSettings != null)
            {
                foreach (var child in additionalSettings.Children)
                {
                    if (child.Children.Count > 0)
                    {
                        AdditionalSettings.Add(child.Name, child.Children[0]);
                    }
                }
            }

            var favTextures = root.Children.FirstOrDefault(x => x.Name == "FavouriteTextures");

            if (favTextures != null && favTextures.Children.Any())
            {
                try {
                    var ft = GenericStructure.Deserialise <List <FavouriteTextureFolder> >(favTextures.Children[0]);
                    if (ft != null)
                    {
                        FavouriteTextureFolders.AddRange(ft);
                    }
                    FixFavouriteNames(FavouriteTextureFolders);
                } catch {
                    // Nope
                }
            }

            if (!File.Exists(SettingsFile))
            {
                Write();
            }
        }
Beispiel #5
0
        public void File_SaveAs_ToFolder()
        {
            ExpressionEditor_AcceptEdit();

            // Save as a Folder structure:
            var saveFormat = SaveFormat.TabularEditorFolder;

            // This flag indicates whether we're currently connected to a database:
            var connectedToDatabase = Handler.SourceType == ModelSourceType.Database;

            // This flag indicates whether the "Current File" pointer should be set to the new file location, which
            // is the typical behaviour of Windows applications when choosing "Save As...". However, when connected
            // to a database, we do not want to do this, as users will probably want to keep working on the existing
            // connection.
            var changeFilePointer = !connectedToDatabase;

            // This flag indicates whether we should reset the undo-checkpoint after saving the model.
            // The purpose of resetting the checkpoint is to visually indicate to the user, that no
            // changes have been made to the model since the last save. We do this, only when changing
            // the "Current File" pointer:
            var resetCheckPoint = changeFilePointer;

            // This flag indicates whether the SerializationOptions annotations on the currently loaded
            // model will be restored to its original value, after the model is saved (possibly using
            // different serialization options, depending on the other arguments of the Save() method).
            // We should always restore when connected to a database, as we don't want our serialization
            // options to be saved to the database - only to the file/folder that we're currently saving to.
            var restoreSerializationOptions = connectedToDatabase;

            // The serialization options to use when saving (unless users check the "Use serialization settings from annotations" checkbox):
            var serializationOptions = Preferences.Current.GetSerializeOptions();

            // Only show the "Use serialize options from annotations" checkbox when the current model has these annotations:
            var showSfa = Handler.HasSerializeOptions;

            using (var dialog = SaveAsDialog.CreateFolderDialog(showSfa))
            {
                var res = dialog.ShowDialog();
                if (res == CommonFileDialogResult.Ok && !string.IsNullOrWhiteSpace(dialog.FileName))
                {
                    using (new Hourglass())
                    {
                        UI.StatusLabel.Text = "Saving...";

                        Handler.Save(dialog.FileName,
                                     saveFormat,
                                     serializationOptions,
                                     dialog.UseSerializationFromAnnotations,
                                     resetCheckPoint,
                                     restoreSerializationOptions);

                        RecentFiles.Add(dialog.FileName);
                        RecentFiles.Save();
                        UI.FormMain.PopulateRecentFilesList();

                        // If working with a file, change the current file pointer:
                        if (changeFilePointer)
                        {
                            File_SaveMode  = ModelSourceType.Folder;
                            File_Current   = dialog.FileName;
                            File_Directory = FileSystemHelper.DirectoryFromPath(File_Current);
                        }

                        UpdateUIText();
                    }
                }
            }
        }
Beispiel #6
0
        public void ProcessIni(AppIniFile ini, bool allowSessionSettings)
        {
            var iniAction = ini.GetActionType("General", "ActionType");
            var iniAddNewDocumentsToFile = ini.GetBool("General", "AddNewDocumentsToFile");
            var iniAfterExtractHook      = ini.GetString("Hooks", "AfterExtract");
            var iniAutoRun                 = ini.GetBool("General", "AutoRun");
            var iniBeforePublishHook       = ini.GetString("Hooks", "BeforePublish");
            var iniDeleteDocumentsFromFile = ini.GetBool("General", "DeleteDocumentsFromFile");
            var iniDiffTool                = ini.GetString("DiffTool", "Path");
            var iniDiffToolParameters      = ini.GetString("DiffTool", "Parameters");
            var iniIgnoreEmpty             = ini.GetBool("General", "IgnoreEmpty");
            var iniFilePath                = ini.GetString("General", "FilePath");
            var iniFolderPath              = ini.GetString("General", "FolderPath");
            var iniLanguage                = ini.GetString("General", "Language");
            var iniPortable                = ini.GetBool("General", "Portable");
            var iniSearchSubdirectories    = ini.GetBool("General", "SearchRepositorySubdirectories");

            if (iniAction.HasValue && allowSessionSettings)
            {
                Action = iniAction.Value;
            }

            if (iniAddNewDocumentsToFile.HasValue && allowSessionSettings)
            {
                AddNewDocumentsToFile = iniAddNewDocumentsToFile.Value;
            }

            if (iniAfterExtractHook != null && allowSessionSettings)
            {
                AfterExtractHook = _hookFactory(iniAfterExtractHook);
            }

            if (iniAutoRun.HasValue && allowSessionSettings)
            {
                AutoRun = iniAutoRun.Value;
            }

            if (iniBeforePublishHook != null && allowSessionSettings)
            {
                BeforePublishHook = _hookFactory(iniBeforePublishHook);
            }

            if (iniDeleteDocumentsFromFile.HasValue && allowSessionSettings)
            {
                DeleteDocumentsFromFile = iniDeleteDocumentsFromFile.Value;
            }

            if (iniDiffTool != null)
            {
                DiffTool = iniDiffTool;
            }

            if (iniDiffToolParameters != null)
            {
                DiffToolParameters = iniDiffToolParameters;
            }

            if (iniIgnoreEmpty.HasValue && allowSessionSettings)
            {
                IgnoreEmpty = iniIgnoreEmpty.Value;
            }

            if (iniFilePath != null && allowSessionSettings)
            {
                FilePath = iniFilePath;
            }

            if (iniFolderPath != null && allowSessionSettings)
            {
                FolderPath = iniFolderPath;
            }

            if (iniLanguage != null)
            {
                Language = iniLanguage;
            }

            if (iniPortable.HasValue)
            {
                Portable = iniPortable.Value;
            }

            if (iniSearchSubdirectories.HasValue)
            {
                SearchRepositorySubdirectories = iniSearchSubdirectories.Value;
            }

            if (ini.GetString("RecentFiles", "1") != null)
            {
                RecentFiles.Clear();
                var j = 1;
                while (j <= 5 && !string.IsNullOrEmpty(ini.GetString("RecentFiles", j.ToString(CultureInfo.InvariantCulture))))
                {
                    RecentFiles.Add(ini.GetString("RecentFiles", j.ToString(CultureInfo.InvariantCulture)));
                    ++j;
                }
            }
        }
Beispiel #7
0
        public void File_Open(string fileName)
        {
            var oldFile      = File_Current;
            var oldDirectory = File_Directory;
            var oldLastWrite = File_LastWrite;
            var oldSaveMode  = File_SaveMode;
            var oldHandler   = Handler;

            var cancel = false;

            using (new Hourglass())
            {
                try
                {
                    Handler = new TabularModelHandler(fileName, Preferences.Current.GetSettings());

                    if (Handler.SourceType == ModelSourceType.Pbit)
                    {
                        var msg = Preferences.Current.AllowUnsupportedPBIFeatures ?
                                  "You have selected a Power BI Template (.pbit) file.\n\nEditing the Data Model of a .pbit file inside Tabular Editor may cause issues when subsequently loading the file in Power BI Desktop.\n\nMake sure to keep a backup of the file, and proceed at your own risk." :
                                  "You have selected a Power BI Template (.pbit) file.\n\nEditing the Data Model of a .pbit file inside Tabular Editor may cause issues when subsequently loading the file in Power BI Desktop. Properties that are known to be unsupported (such as Display Folders) have been disabled, but there is still a risk that certain changes made with Tabular Editor can corrupt the file.\n\nMake sure to keep a backup of the file, and proceed at your own risk.";
                        var mr = MessageBox.Show(msg,
                                                 "Opening Power BI Template", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                        if (mr == DialogResult.Cancel)
                        {
                            cancel = true;
                        }
                    }

                    if (!cancel)
                    {
                        File_Current   = Handler.Source;
                        File_Directory = FileSystemHelper.DirectoryFromPath(Handler.Source);
                        File_SaveMode  = Handler.SourceType;

                        // TODO: Use a FileSystemWatcher to watch for changes to the currently loaded file(s)
                        // and handle them appropriately. For now, we just store the LastWriteDate of the loaded
                        // file, to ensure that we don't accidentally overwrite newer changes when saving.
                        File_LastWrite = File_SaveMode == ModelSourceType.Folder ? GetLastDirChange(File_Current) : File.GetLastWriteTime(File_Current);

                        LoadTabularModelToUI();
                        RecentFiles.Add(fileName);
                        RecentFiles.Save();
                        UI.FormMain.PopulateRecentFilesList();
                    }
                }
                catch (Exception ex)
                {
                    cancel = true;
                    MessageBox.Show(ex.Message, "Error loading Model from disk", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (cancel)
            {
                Handler        = oldHandler;
                File_Current   = oldFile;
                File_Directory = oldDirectory;
                File_SaveMode  = oldSaveMode;
                File_LastWrite = oldLastWrite;
            }
        }
Beispiel #8
0
        public void File_SaveAs()
        {
            ExpressionEditor_AcceptEdit();

            // Only show the "Use serialize options from annotations" checkbox when the current model has these annotations,
            // and not when switching between file/folder:
            var showSfa = Handler.HasSerializeOptions;

            // If the model is currently loaded from a database or a folder structure, use the default "Model.bim" as a file
            // name. Otherwise, use the name of the current file:
            var defaultFileName = (Handler.SourceType == ModelSourceType.Database || Handler.SourceType == ModelSourceType.Folder) ? "Model.bim" : File_Current;

            // We only allow saving as a Power BI Template, if the current model was loaded from a template:
            var allowPbit = Handler.SourceType == ModelSourceType.Pbit;

            // This flag indicates whether we're currently connected to a database:
            var connectedToDatabase = Handler.SourceType == ModelSourceType.Database;

            // This flag indicates whether the "Current File" pointer should be set to the new file location, which
            // is the typical behaviour of Windows applications when choosing "Save As...". However, when connected
            // to a database, we do not want to do this, as users will probably want to keep working on the existing
            // connection.
            var changeFilePointer = !connectedToDatabase;

            // This flag indicates whether we should reset the undo-checkpoint after saving the model.
            // The purpose of resetting the checkpoint is to visually indicate to the user, that no
            // changes have been made to the model since the last save. We do this, only when changing
            // the "Current File" pointer:
            var resetCheckPoint = changeFilePointer;

            // This flag indicates whether the SerializationOptions annotations on the currently loaded
            // model will be restored to its original value, after the model is saved (possibly using
            // different serialization options, depending on the other arguments of the Save() method).
            // We should always restore when connected to a database, as we don't want our serialization
            // options to be saved to the database - only to the file/folder that we're currently saving to.
            var restoreSerializationOptions = connectedToDatabase;

            // The serialization options to use when saving (unless users check the "Use serialization settings from annotations" checkbox):
            var serializationOptions = Preferences.Current.GetSerializeOptions();

            using (var dialog = SaveAsDialog.CreateFileDialog(showSfa, defaultFileName, allowPbit))
            {
                var res = dialog.ShowDialog();

                if (res == CommonFileDialogResult.Ok && !string.IsNullOrWhiteSpace(dialog.FileName))
                {
                    using (new Hourglass())
                    {
                        UI.StatusLabel.Text = "Saving...";

                        // Save as a Power BI Template, if that's the type of file chosen in the dialog:
                        var saveFormat = dialog.FileType == "pbit" ? SaveFormat.PowerBiTemplate : SaveFormat.ModelSchemaOnly;

                        var fileName = dialog.FileName;
                        if (dialog.FileType == "pbit" && !fileName.EndsWith(".pbit"))
                        {
                            fileName += ".pbit";
                        }
                        else if (dialog.FileType == "bim" && !fileName.EndsWith(".bim"))
                        {
                            fileName += ".bim";
                        }

                        Handler.Save(fileName,
                                     saveFormat,
                                     serializationOptions,
                                     dialog.UseSerializationFromAnnotations,
                                     resetCheckPoint,
                                     restoreSerializationOptions);

                        RecentFiles.Add(dialog.FileName);
                        RecentFiles.Save();
                        UI.FormMain.PopulateRecentFilesList();

                        // If not connected to a database, change the current working file:
                        if (changeFilePointer)
                        {
                            File_Current   = dialog.FileName;
                            File_Directory = FileSystemHelper.DirectoryFromPath(File_Current);
                            File_LastWrite = DateTime.Now;
                            File_SaveMode  = dialog.FileType == "pbit" ? ModelSourceType.Pbit : ModelSourceType.File;
                        }

                        UpdateUIText();
                    }
                }
            }
        }
Beispiel #9
0
        public void SaveProject()
        {
            if (this.Project != null)
            {
                if (this.Project.IsDirty)
                {
                    if (!_fileService.IsExistFile(this.Project.SavePath)) //数据文件不存在
                    {
                        if (_projectDBService.CreateLocalDBFile())
                        {
                            Console.WriteLine("创建文件成功");
                        }
                        else
                        {
                            Console.WriteLine("创建文件失败");
                        }
                    }
                    if (!IsCreatedFundamentalTableStructure) //未建立项目基础表结构
                    {
                        if (_projectDBService != null)
                        {
                            if (_projectDBService.CreatFundamentalTableStructure())//;  //创建基础存储结构
                            {
                                Console.WriteLine("初始化成功");
                            }
                            else
                            {
                                Console.WriteLine("初始化失败");
                            }
                        }
                    }
                    //保存工程信息

                    if (_projectDBService.AddProject(this.Project) > 0)//;
                    {
                        Console.WriteLine("工程信息保存成功");
                    }
                    else
                    {
                        Console.WriteLine("工程信息保存失败");
                    }

                    //初始化“控制器类型信息”
                    if (_projectDBService.InitializeControllerTypeInfo())
                    {
                        Console.WriteLine("控制器类型初始化成功");
                    }
                    else
                    {
                        Console.WriteLine("控制器类型初始化失败");
                    }

                    //初始化此工程下的“器件类型”
                    int projectID = _projectDBService.GetMaxID();
                    IControllerConfig controllerConfig = ControllerConfigManager.GetConfigObject(ControllerType.NONE);

                    if (_deviceTypeDBService.InitializeDeviceTypeInfo(controllerConfig.GetALLDeviceTypeInfo(projectID)))
                    {
                        Console.WriteLine("器件类型初始化成功");
                    }
                    else
                    {
                        Console.WriteLine("器件类型初始化失败");
                    }

                    //保存此工程下的回路,器件,组态,手动盘
                    foreach (var c in this.Project.Controllers)
                    {
                        _deviceDBService = SCA.DatabaseAccess.DBContext.DeviceManagerDBServiceTest.GetDeviceDBContext(c.Type, _dbFileVersionService);
                        c.Project.ID     = projectID;
                        c.ProjectID      = projectID;
                        if (_controllerDBService.AddController(c))
                        {
                            Console.WriteLine(c.Name + "控制器保存成功");
                        }
                        else
                        {
                            Console.WriteLine(c.Name + "控制器保存失败");
                        }

                        //更新器件类型表的“匹配控制器信息”
                        controllerConfig = ControllerConfigManager.GetConfigObject(c.Type);
                        if (_deviceTypeDBService.UpdateMatchingController(c.Type, controllerConfig.GetDeviceTypeCodeInfo()))
                        {
                            Console.WriteLine(c.Name + "控制器匹配信息更新成功");
                        }
                        else
                        {
                            Console.WriteLine(c.Name + "控制器匹配信息更新失败");
                        }

                        //取得当前ControllerID
                        // int controllerID = _controllerDBService.GetMaxID();
                        if (_deviceDBService.CreateTableStructure())
                        {
                            Console.WriteLine("器件结构初始化成功");
                        }
                        else
                        {
                            Console.WriteLine("器件结构初始化失败");
                        }
                        foreach (var loop in c.Loops)
                        {
                            loop.Controller.ID = c.ID;
                            loop.ControllerID  = c.ID;
                            if (_loopDBService.AddLoopInfo(loop))
                            {
                                Console.WriteLine("回路信息初始化成功");
                            }
                            else
                            {
                                Console.WriteLine("回路信息初始化失败");
                            }
                            //取得当前LoopID
                            //  int loopID = _loopDBService.GetMaxID();
                            loop.ID = loop.ID;
                            if (_deviceDBService.AddDevice(loop))
                            {
                                Console.WriteLine("器件信息保存成功");
                            }
                            else
                            {
                                Console.WriteLine("器件信息保存失败");
                            }
                            //取得当前器件最大ID号
                            //int deviceID=_deviceDBService.GetMaxID();
                        }
                        if (c.StandardConfig.Count != 0)
                        {
                            if (_linkageConfigStandardDBService.AddStandardLinkageConfigInfo(c.StandardConfig))
                            {
                                Console.WriteLine("标准组态信息保存成功");
                            }
                            else
                            {
                                Console.WriteLine("标准组态信息保存失败");
                            }
                        }
                        if (c.GeneralConfig.Count != 0)
                        {
                            if (_linkageConfigGeneralDBService.AddGeneralLinkageConfigInfo(c.GeneralConfig))
                            {
                                Console.WriteLine("通用组态信息保存成功");
                            }
                            else
                            {
                                Console.WriteLine("通用组态信息保存失败");
                            }
                        }
                        if (c.MixedConfig.Count != 0)
                        {
                            if (_linkageConfigMixedDBService.AddMixedLinkageConfigInfo(c.MixedConfig))
                            {
                                Console.WriteLine("混合组态信息保存成功");
                            }
                            else
                            {
                                Console.WriteLine("混合组态信息保存失败");
                            }
                        }
                        if (c.ControlBoard.Count != 0)
                        {
                            if (_manualControlBoardDBService.AddManualControlBoardInfo(c.ControlBoard))
                            {
                                Console.WriteLine("手控盘保存成功");
                            }
                            else
                            {
                                Console.WriteLine("手控盘保存失败");
                            }
                        }
                    }
                }
                RecentFiles.Add(Project.SavePath);
                SaveRecentFiles();
                Project.IsDirty = false;
            }
        }
Beispiel #10
0
        public void Load()
        {
            var table = new DataTable("Settings");

            try
            {
                if (!Directory.Exists(FileName))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(FileName));
                }
                table.ReadXml(FileName);
            }
            catch
            {
            }

            if (table.Rows.Count <= 0)
            {
                return;
            }
            DataRow row = table.Rows[0];

            if (table.Columns.Contains("X"))
            {
                X = row.Field <int>("X");
            }
            if (table.Columns.Contains("Y"))
            {
                Y = row.Field <int>("Y");
            }
            if (table.Columns.Contains("Width"))
            {
                Width = row.Field <int>("Width");
            }
            if (table.Columns.Contains("Height"))
            {
                Height = row.Field <int>("Height");
            }
            if (table.Columns.Contains("Maximized"))
            {
                Maximized = row.Field <bool>("Maximized");
            }
            if (table.Columns.Contains("TextColor1"))
            {
                TextColor1 = row.Field <int>("TextColor1");
            }
            if (table.Columns.Contains("TextColor2"))
            {
                TextColor2 = row.Field <int>("TextColor2");
            }
            if (table.Columns.Contains("BackColor1"))
            {
                BackColor1 = row.Field <int>("BackColor1");
            }
            if (table.Columns.Contains("BackColor2"))
            {
                BackColor2 = row.Field <int>("BackColor2");
            }
            if (table.Columns.Contains("ColorSet"))
            {
                ColorSet = row.Field <int>("ColorSet");
            }

            RecentFiles.Clear();
            for (int i = 1; i <= MaxRecentFiles; i++)
            {
                if (table.Columns.Contains($"RecentFiles{i}"))
                {
                    RecentFiles.Add(row.Field <string>($"RecentFiles{i}"));
                }
            }
        }
Beispiel #11
0
 public void Add(string file)
 {
     RecentFiles.Add(file);
     OnPropertyChanged("RecentFiles");
 }
Beispiel #12
0
 public void InsertFile(string filepath)
 {
     RecentFiles.Add(new RecentFile(filepath));
 }
Beispiel #13
0
        /// <summary>
        /// Loads image at specified index
        /// </summary>
        /// <param name="index">The index of file to load from Pics</param>
        internal static async void Pic(int index)
        {
#if DEBUG
            var stopWatch = new Stopwatch();
            stopWatch.Start();
#endif
            // Declare variable to be used to set image source
            BitmapSource bitmapSource;

            // Error checking to fix rare cases of crashing
            if (Pics.Count < index)
            {
                bitmapSource = await PicErrorFix(index).ConfigureAwait(true);

                if (bitmapSource == null)
                {
                    /// Try to recover
                    /// TODO needs testing
                    Reload(true);
                    return;
                }
            }
            else if (File.Exists(Pics[index])) // Checking if file exists fixes rare crashes
            {
                /// Use the Load() function load image from memory if available
                /// if not, it will be null
                bitmapSource = Preloader.Load(Pics[index]);
            }
            else
            {
                /// Try to reload from backup if file does not exist
                /// TODO needs testing
                Reload(true);
                return;
            }

            // Initate loading behavior, if needed
            if (bitmapSource == null)
            {
                // Set loading from translation service
                SetLoadingString();

                // Show a thumbnail while loading
                var thumb = GetThumb(index, true);
                if (thumb != null && Properties.Settings.Default.PicGallery != 2)
                {
                    // Don't allow image size to stretch the whole screen
                    if (xWidth == 0)
                    {
                        var size = ImageDecoder.ImageSize(Pics[index]);
                        if (size.HasValue)
                        {
                            FitImage(size.Value.Width, size.Value.Height);
                        }
                        else
                        {
                            LoadWindows.GetMainWindow.MainImage.Width  = LoadWindows.GetMainWindow.MinWidth;
                            LoadWindows.GetMainWindow.MainImage.Height = LoadWindows.GetMainWindow.MinHeight;
                        }
                    }
                    else
                    {
                        LoadWindows.GetMainWindow.MainImage.Width  = xWidth;
                        LoadWindows.GetMainWindow.MainImage.Height = xHeight;
                    }

                    LoadWindows.GetMainWindow.MainImage.Source = thumb;
                }

                // Dissallow changing image while loading
                CanNavigate = false;

                // Get it!
                await Preloader.Add(Pics[index]).ConfigureAwait(true);

                // Retry
                bitmapSource = Preloader.Load(Pics[index]);

                if (bitmapSource == null)
                {
                    // Attempt to fix it
                    bitmapSource = await PicErrorFix(index).ConfigureAwait(true);

                    // If pic is still null, image can't be rendered
                    if (bitmapSource == null)
                    {
                        // Clean up
                        Pics.RemoveAt(index);
                        Preloader.Remove(index);

                        // Sync with gallery, if needed
                        if (GetPicGallery != null)
                        {
                            if (GetPicGallery.grid.Children.Count > index)
                            {
                                GetPicGallery.grid.Children.RemoveAt(index);
                            }
                        }

                        // Check if images still exists
                        if (Pics.Count == 0)
                        {
                            Unload();
                            return;
                        }

                        /// Retry
                        /// TODO needs testing
                        CanNavigate = true;
                        Pic();
                        return;
                    }
                }
            }

            // Reset transforms if needed
            if (UILogic.TransformImage.Rotation.Flipped || UILogic.TransformImage.Rotation.Rotateint != 0)
            {
                UILogic.TransformImage.Rotation.Flipped             = false;
                UILogic.TransformImage.Rotation.Rotateint           = 0;
                GetImageSettingsMenu.FlipButton.TheButton.IsChecked = false;

                LoadWindows.GetMainWindow.MainImage.LayoutTransform = null;
            }

            // Show the image! :)
            LoadWindows.GetMainWindow.MainImage.Source = bitmapSource;
            FitImage(bitmapSource.PixelWidth, bitmapSource.PixelHeight);
            SetTitleString(bitmapSource.PixelWidth, bitmapSource.PixelHeight, index);

            // Scroll to top if scroll enabled
            if (IsScrollEnabled)
            {
                LoadWindows.GetMainWindow.Scroller.ScrollToTop();
            }

            // Update values
            CanNavigate  = true;
            FolderIndex  = index;
            FreshStartup = false;

            if (LoadWindows.GetImageInfoWindow != null)
            {
                if (LoadWindows.GetImageInfoWindow.IsVisible)
                {
                    LoadWindows.GetImageInfoWindow.UpdateValues();
                }
            }

            if (Pics.Count > 1)
            {
                Taskbar.Progress(index, Pics.Count);

                // Preload images \\
                await Preloader.PreLoad(index).ConfigureAwait(false);
            }

            RecentFiles.Add(Pics[index]);

#if DEBUG
            stopWatch.Stop();
            var s = $"Pic(); executed in {stopWatch.Elapsed.TotalMilliseconds} milliseconds";
            Trace.WriteLine(s);
#endif
        }