Ejemplo n.º 1
0
        /// <summary>
        /// The ToColor
        /// </summary>
        /// <param name="htmlColor">The htmlColor<see cref="string" /></param>
        /// <returns>The <see cref="Color" /></returns>
        public static Color ToColor(this string htmlColor)
        {
            var convertFromString = ColorConverter.ConvertFromString(htmlColor);

            if (convertFromString == null)
            {
                return(default);
Ejemplo n.º 2
0
        private void UpdatePolylineActuel()
        {
            PolylineActuel.NomTrajet = TextBoxTrajet.Text;

            Color color = Colors.Black;

            try
            {
                color = (Color)ColorConverter.ConvertFromString(Couleur);
            }
            catch (Exception e)
            {
                MessageBox.Show("Erreur encodage de la couleur :\n" + e.Message, "", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            PolylineActuel.Couleur = color;

            Brush brush = new SolidColorBrush(PolylineActuel.Couleur);

            Console.WriteLine("DEBUG brush obtenu après conversion : " + brush.ToString());

            try
            {
                PolylineActuel.Epaisseur = Convert.ToInt32(TextBoxEpaisseur.Text);
            }
            catch (Exception e)
            {
                MessageBox.Show("Erreur encodage de l'épaisseur :\n" + e.Message, "", MessageBoxButton.OK, MessageBoxImage.Error);
                PolylineActuel.Epaisseur = _polylineDepart.Epaisseur;
            }
        }
Ejemplo n.º 3
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var color = (string) value;

            try
            {
                TypeConverter colorConverter = new ColorConverter();
                var baseColor = (Color) colorConverter.ConvertFromString(color);

                var c2 = Color.FromArgb(25, baseColor.R, baseColor.G, baseColor.B);

                var colorBrush = new LinearGradientBrush();
                colorBrush.StartPoint = new Point(0, 0);
                colorBrush.EndPoint = new Point(0, 1);
                colorBrush.GradientStops.Add(new GradientStop(c2, 0.15));
                colorBrush.GradientStops.Add(new GradientStop(baseColor, 0.85));
                colorBrush.GradientStops.Add(new GradientStop(c2, 1));

                return colorBrush;
            }
            catch (Exception)
            {
                return Brushes.DarkRed;
            }
        }
Ejemplo n.º 4
0
        public static System.Windows.Media.Color GetClassColor(string className, bool priestAsGray)
        {
            if (string.IsNullOrEmpty(className))
            {
                return(Colors.DimGray);
            }
            string color;

            if (Config.Instance.ClassColorScheme == ClassColorScheme.HearthStats)
            {
                HearthStatsClassColors.TryGetValue(className, out color);
            }
            else
            {
                if (className == "Priest" && priestAsGray)
                {
                    color = "#D2D2D2";
                }
                else
                if (!ClassicClassColors.TryGetValue(className, out color))
                {
                    color = "#808080";
                }
            }
            if (string.IsNullOrEmpty(color))
            {
                return(Colors.DimGray);
            }
            return((System.Windows.Media.Color)ColorConverter.ConvertFromString(color));
        }
Ejemplo n.º 5
0
        private Brush GetBrush(string symbol)
        {
            var   colour            = _service.GetColour(symbol);
            var   convertFromString = ColorConverter.ConvertFromString(colour);
            Brush brush             = convertFromString == null ? new SolidColorBrush(Color.FromRgb(255, 255, 255)) : new SolidColorBrush((Color)convertFromString);

            return(brush);
        }
Ejemplo n.º 6
0
 private void OnChangeWindowBackgroundColour(string a_colourHexCode)
 {
     if (string.IsNullOrEmpty(a_colourHexCode))
     {
         Color val = (Color)ColorConverter.ConvertFromString(a_colourHexCode);
         Application.Current.MainWindow.Background = new SolidColorBrush(val);;
     }
 }
Ejemplo n.º 7
0
        public static Color ParseColor(string S)
        {
            if (ColorConverter.ConvertFromString(S) is Color c)
            {
                return(c);
            }

            return(Colors.Transparent);
        }
Ejemplo n.º 8
0
 private static Color GetColor(string color)
 {
     if (string.IsNullOrWhiteSpace(color) ||
         color.Equals("Transparent", StringComparison.OrdinalIgnoreCase))
     {
         return(SystemParameters.WindowGlassColor);
     }
     // ReSharper disable once PossibleNullReferenceException
     return((Color)ColorConverter.ConvertFromString(color));
 }
        public DynamicDataExampleViewModel()
        {
            _sourceCache = new SourceCache <string, int>(x => x.GetHashCode());

            _disposable = _sourceCache.Connect()
                          .ObserveOnDispatcher()
                          .Transform(x => (Brush) new SolidColorBrush((Color)ColorConverter.ConvertFromString(x)))
                          .StartWithItem(CreateDrawingBrush(), 123)
                          .Bind(out _brushes)
                          .Subscribe();
        }
Ejemplo n.º 10
0
 private void ButtonAppliquer_Click(object sender, RoutedEventArgs e)
 {
     if (_temp == null)
     {
         _temp = new MyCartographyObjects.Polyline();
     }
     _temp.Color             = (Color)ColorConverter.ConvertFromString(Couleur);
     _temp.Epaisseur         = int.Parse(Epaisseur);
     _temp.Description       = Description;
     hasAppliquerBeenClicked = true;
 }
Ejemplo n.º 11
0
 private Color ConvertToColor(string colorString)
 {
     try
     {
         var colorConverter = new ColorConverter();
         return colorConverter.ConvertFromString(colorString);
     }
     catch (Exception)
     {
         throw new InvalidCastException("String provided is not in a recognized Hex format.");
     }
 }
Ejemplo n.º 12
0
        private void SetInfoMain(int row)
        {
            InfoMain.Inlines.Clear();
            string activityName = _resource.ExcelDataTable.Rows[row]["任务名称"].ToString();

            try
            {
                string xmlString = _resource.ExcelDataTable.Rows[row]["说明"].ToString();

                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml("<root>" + xmlString + "</root>");

                if (xmldoc.DocumentElement == null)
                {
                    return;
                }
                XmlNodeList xmlNodeList = xmldoc.DocumentElement.ChildNodes;

                foreach (XmlNode xmlNode in xmlNodeList)
                {
                    switch (xmlNode.Name)
                    {
                    case "T":
                        if (xmlNode.Attributes["c"] != null)
                        {
                            string colorString = Regex.Replace(xmlNode.Attributes["c"].Value, "^ff|^FF", "#");
                            Color  color       = (Color)ColorConverter.ConvertFromString(colorString);
                            InfoMain.Inlines.Add(new Run(xmlNode.Attributes["t"].Value)
                            {
                                Foreground = new SolidColorBrush(color)
                            });
                        }
                        else
                        {
                            InfoMain.Inlines.Add(new Run(xmlNode.Attributes["t"].Value));
                        }
                        break;

                    case "B":
                        InfoMain.Inlines.Add(new LineBreak());
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("“{0}”活动说明配置有错!\n\n", activityName) + e.Message);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Function which convert to polygon
        /// </summary>
        public Polygon ConvertToPolygon()
        {
            var polygon = new Polygon
            {
                Stroke          = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Stroke)),
                StrokeThickness = StrokeThickness,
                Fill            = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Fill))
            };

            foreach (var point in Points)
            {
                polygon.Points.Add(new Point(point.Item1, point.Item2));
            }
            EnableDrag(polygon);
            return(polygon);
        }
Ejemplo n.º 14
0
        public static System.Windows.Media.Color FromHex(this System.Windows.Media.Color c, string hex)
        {
            if (hex == null)
            {
                return(new System.Windows.Media.Color());
            }

            var convertFromString = ColorConverter.ConvertFromString(hex);

            if (convertFromString != null)
            {
                return((System.Windows.Media.Color)convertFromString);
            }

            throw new ArgumentException("Invalid hex color code");
        }
Ejemplo n.º 15
0
        private static Color GetBgColorFromReg()
        {
            var str = RegUtil.ReadRegKey("BgColor");

            if (string.IsNullOrWhiteSpace(str))
            {
                return(Color.FromArgb(byte.MaxValue, 0, 104, byte.MaxValue));
            }
            var obj = ColorConverter.ConvertFromString(str);

            if (obj != null)
            {
                return((Color)obj);
            }
            return(Color.FromArgb(byte.MaxValue, 0, 104, byte.MaxValue));
        }
Ejemplo n.º 16
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var airline = (Airline) value;

            try
            {
                TypeConverter colorConverter = new ColorConverter();
                var c = (Color) colorConverter.ConvertFromString(airline.Profile.Color);

                return new SolidColorBrush(c);
            }
            catch
            {
                return Brushes.White;
            }
        }
Ejemplo n.º 17
0
        public SecondWindow()
        {
            InitializeComponent();

            this.KeyDown += CommonMethods.KeyEvents;

            Settings.Theme.ApplyConfiguration(this);

            BtnClose.Click  += CommonMethods.CloseWindow_OnClick;
            BtnMaxMin.Click += CommonMethods.MaxMin_Click;

            Label_CategoryName.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.Theme.TextColor));
            Label_CategoryName.FontFamily = new FontFamily(Settings.Theme.TextFontFamily);


            ConfigurationButtons();
        }
Ejemplo n.º 18
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (value == null || value.ToString().Trim().Length == 0)
     {
         return(new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFA500")));
     }
     else if (value.ToString().ToLower().Contains("error"))
     {
         return(Brushes.Red);
     }
     else if (value.ToString().ToLower().Contains("pass"))
     {
         return(Brushes.Green);
     }
     else
     {
         return(new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFA500")));
     }
 }
Ejemplo n.º 19
0
        private void ConfigurationButtons()
        {
            SolidColorBrush color = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.Theme.ButtonBackgroundColor))
            {
                Opacity = Settings.Theme.ButtonTransparency / 100.0
            };
            var buttonStyle = Resources["btnStyle"] as Style;

            buttonStyle?.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString(Settings.Theme.ButtonTextColor))));
            buttonStyle?.Setters.Add(new Setter(FontFamilyProperty, new FontFamily(Settings.Theme.ButtonFontFamily)));
            buttonStyle?.Setters.Add(new Setter(BackgroundProperty, color));

            foreach (var button in Grid_Buttons.Children.OfType <Button>())
            {
                button.Content     = Settings.Game.CategoriesList[Convert.ToInt32(button.Tag) - 1];
                button.Style       = buttonStyle;
                button.Click      += Buttons_Click;
                button.MouseEnter += Buttons_MouseEnter;
                button.MouseLeave += Buttons_MouseLeave;
            }
        }
Ejemplo n.º 20
0
        public void ApplySetting(SettingStyle style)
        {
            tabControl.Width              = ps.Width;
            tabControl.Height             = ps.Height;
            border.Background.Opacity     = ps.Opacity ? 0 : 100;
            currentZodiac                 = ps.CurrentZodiac;
            border.Background             = new SolidColorBrush((Color)ColorConverter.ConvertFromString(ps.Background));
            gridOpacity.Opacity           = ps.WindowOrasity;
            WindowMain.FontSize           = ps.FontSize;
            WindowMain.FontFamily         = (System.Windows.Media.FontFamily) new FontFamilyConverter().ConvertFromString(ps.FontName);
            presentDay.Foreground.Opacity = ps.FontOpacity;
            tomorrow.Foreground.Opacity   = ps.FontOpacity;
            week.Foreground.Opacity       = ps.FontOpacity;

            var colorText = new SolidColorBrush((Color)ColorConverter.ConvertFromString(ps.Foreground));

            presentDay.Foreground = colorText;
            tomorrow.Foreground   = colorText;
            week.Foreground       = colorText;

            if (ps.FontStyle == "Normal")
            {
                WindowMain.FontStyle = FontStyles.Normal;
            }
            if (ps.FontStyle == "Italic")
            {
                WindowMain.FontStyle = FontStyles.Italic;
            }

            if (ps.FontWeight == "Normal")
            {
                WindowMain.FontWeight = FontWeights.Normal;
            }
            if (ps.FontWeight == "Bold")
            {
                WindowMain.FontWeight = FontWeights.Bold;
            }
        }
Ejemplo n.º 21
0
        private void speechRecognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            //lblDemo.Content = e.Result.Text;
            if (e.Result.Words.Count == 2)
            {
                string command = e.Result.Words[0].Text.ToLower();
                string value   = e.Result.Words[1].Text.ToLower();
                switch (command)
                {
                case "weight":
                    FontWeightConverter weightConverter = new FontWeightConverter();
                    lblDemo.FontWeight = (FontWeight)weightConverter.ConvertFromString(value);
                    break;

                case "color":
                    lblDemo.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(value));
                    break;

                case "size":
                    switch (value)
                    {
                    case "small":
                        lblDemo.FontSize = 12;
                        break;

                    case "medium":
                        lblDemo.FontSize = 24;
                        break;

                    case "large":
                        lblDemo.FontSize = 48;
                        break;
                    }
                    break;
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// カラープレビューの更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ColorCodeBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox sb = (TextBox)sender;

            try
            {
                Color   color = (Color)ColorConverter.ConvertFromString(sb.Text);
                Ellipse auter = new Ellipse
                {
                    Fill = System.Windows.Media.Brushes.Snow,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Center,
                    Width  = 25,
                    Height = 25
                };
                Ellipse inner = new Ellipse
                {
                    Fill = new SolidColorBrush(color),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment   = VerticalAlignment.Center,
                    Margin = new Thickness(1, 1, 1, 1),
                    Width  = 23,
                    Height = 23
                };
                if (ColorCanvas != null)
                {
                    ColorCanvas.Children.Clear();
                    ColorCanvas.Children.Add(auter);
                    ColorCanvas.Children.Add(inner);
                }
            }
            catch
            {
                //意図的に何もしない
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Навидение на кнопку
        /// </summary>
        /// <param name="sender">Button</param>
        /// <param name="e">MouseEnter</param>
        private void HoverButton(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Button bt = (sender as Button);

            if (bt.Name.Equals("contextBut"))
            {
                bt.Background = new ImageBrush(new BitmapImage(new Uri("Image/ContexButHover.png", UriKind.Relative)));
            }
            else if (bt.Name.Equals("strelkaBut"))
            {
                strelkaPopup.BorderBrush = Brushes.DarkBlue;
            }
            else
            {
                LinearGradientBrush gradientBrushBorder = (LinearGradientBrush)bt.BorderBrush;
                gradientBrushBorder.GradientStops[1].Color = (Color)ColorConverter.ConvertFromString("#FFFFD100");

                if ((LinearGradientBrush)bt.Background != null)
                {
                    LinearGradientBrush linearGradientBackground = (LinearGradientBrush)bt.Background;
                    linearGradientBackground.GradientStops[2].Color = Color.FromArgb(0, 0, 0, 0);
                }
            }
        }
Ejemplo n.º 24
0
 internal static bool IsMediaColor(string colorString)
 {
     try
     {
         var mediaColorConverter = new ColorConverter();
         mediaColorConverter.ConvertFromString(null, PNStatic.CultureInvariant, colorString);
         return true;
     }
     catch (FormatException)
     {
         return false;
     }
     catch (Exception ex)
     {
         PNStatic.LogException(ex);
         return true;
     }
 }
        protected override Bitmap GetThumbnailImage(uint width) // Implemented abstract function in the base class
        {
            string debug = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Marlin3DprinterTool", "Debug", "false");


            Logger(debug, "Creating Memorystream", EventLogEntryType.Information, 100);
            MemoryStream memStream = new MemoryStream();


            Logger(debug, "Creating Thread", EventLogEntryType.Information, 200);
            Thread thread = new Thread(() =>
            {
                Logger(debug, "Try Thread", EventLogEntryType.Information, 210);
                try
                {
                    Logger(debug, "Get Color", EventLogEntryType.Information, 220);
                    string color = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Marlin3DprinterTool", "Color", "Blue");

                    Logger(debug, $"Color: {color}", EventLogEntryType.Information, 222);

                    Logger(debug, "Start reader", EventLogEntryType.Information, 230);
                    var stlReader             = new StLReader();
                    stlReader.DefaultMaterial = new DiffuseMaterial(
                        new SolidColorBrush((Color)ColorConverter.ConvertFromString(color)));

                    Logger(debug, "Reader configured", EventLogEntryType.Information, 240);

                    //stlReader.DefaultMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Blue));

                    Logger(debug, "Start reader the model", EventLogEntryType.Information, 250);
                    var model = stlReader.Read(SelectedItemStream);
                    Logger(debug, "Model ok", EventLogEntryType.Information, 260);


                    Logger(debug, "Create UI control", EventLogEntryType.Information, 300);
                    //...create UI controls...

                    Logger(debug, "Create Viewport", EventLogEntryType.Information, 310);
                    Viewport3D viewport = new Viewport3D();
                    Logger(debug, "Viewport done", EventLogEntryType.Information, 320);


                    Logger(debug, $"viewport.Measure: {width}", EventLogEntryType.Information, 330);
                    // viewport.Measure(new System.Windows.Size(320, 240));
                    viewport.Measure(new Size(width, width));
                    // viewport.Arrange(new Rect(0, 0, 320, 240));
                    Logger(debug, $"viewport.Arrange: {width}", EventLogEntryType.Information, 340);
                    viewport.Arrange(new Rect(0, 0, width, width));


                    Logger(debug, "ModelVisual3D", EventLogEntryType.Information, 350);
                    ModelVisual3D root = new ModelVisual3D();

                    Logger(debug, "viewport.Children.Add", EventLogEntryType.Information, 360);
                    viewport.Children.Add(root);


                    Logger(debug, "Camera", EventLogEntryType.Information, 400);
                    var camera               = new PerspectiveCamera();
                    camera.Position          = new Point3D(2, 16, 20);
                    camera.LookDirection     = new Vector3D(-2, -16, -20);
                    camera.UpDirection       = new Vector3D(0, 0, 1);
                    camera.FieldOfView       = 45;
                    camera.NearPlaneDistance = 0.1;
                    camera.FarPlaneDistance  = double.PositiveInfinity;
                    viewport.Camera          = camera;
                    Logger(debug, "Camera Done", EventLogEntryType.Information, 410);



                    Logger(debug, "Add light", EventLogEntryType.Information, 420);
                    root.Children.Add(new DefaultLights());
                    Logger(debug, "Add model", EventLogEntryType.Information, 430);
                    root.Content = model;


                    Logger(debug, "Do camera.ZoomExtents", EventLogEntryType.Information, 440);
                    camera.ZoomExtents(viewport);


                    Logger(debug, "Do background", EventLogEntryType.Information, 450);
                    Brush background = new SolidColorBrush(Colors.Transparent);

                    Logger(debug, "Do a BitmapExporter", EventLogEntryType.Information, 460);
                    BitmapExporter exporter = new BitmapExporter
                    {
                        OversamplingMultiplier = 2,
                        Background             = background
                    };

                    Logger(debug, "Fill the exporter", EventLogEntryType.Information, 470);
                    exporter.Export(viewport, memStream);
                }
                catch (Exception errorException)
                {
                    Logger(debug, errorException.Message, EventLogEntryType.Error, errorException.HResult);
                    //TODO: Empty Catch
                }
            });


            Logger(debug, "Thread STA", EventLogEntryType.Information, 500);
            thread.SetApartmentState(ApartmentState.STA);
            Logger(debug, "Thread Sstart", EventLogEntryType.Information, 510);
            thread.Start();
            Logger(debug, "Thread Join", EventLogEntryType.Information, 520);
            thread.Join();

            Logger(debug, "Create bitmap from memstream", EventLogEntryType.Information, 530);
            Bitmap thumbnailBitmap = (Bitmap)Image.FromStream(memStream);

            Logger(debug, "Return Bitmap!", EventLogEntryType.Information, 500);
            return(thumbnailBitmap);
        }
Ejemplo n.º 26
0
        internal static void LoadNoteCustomProperties(PNote note, DataRow r)
        {
            try
            {
                if (!PNData.IsDBNull(r["BACK_COLOR"]) || !PNData.IsDBNull(r["CAPTION_FONT_COLOR"]) || !PNData.IsDBNull(r["CAPTION_FONT"]))
                {
                    var drawingColorConverter = new System.Drawing.ColorConverter();
                    var wfc = new WPFFontConverter();
                    var mediaColorConverter = new ColorConverter();

                    note.Skinless = new PNSkinlessDetails();
                    if (!PNData.IsDBNull(r["BACK_COLOR"]))
                    {
                        try
                        {
                            var clr = mediaColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                    (string)r["BACK_COLOR"]);
                            if (clr != null)
                            {
                                note.Skinless.BackColor = (Color)clr;
                            }
                        }
                        catch (FormatException)
                        {
                            //possible FormatException after synchronization with old database
                            var clr = drawingColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                    (string)r["BACK_COLOR"]);
                            if (clr != null)
                            {
                                var drawingColor = (System.Drawing.Color)clr;
                                note.Skinless.BackColor = Color.FromArgb(drawingColor.A, drawingColor.R, drawingColor.G,
                                    drawingColor.B);
                                var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET BACK_COLOR = '");
                                sb.Append(mediaColorConverter.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.BackColor));
                                sb.Append("' WHERE NOTE_ID = '");
                                sb.Append(r["NOTE_ID"]);
                                sb.Append("'");
                                PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                            }
                        }
                    }
                    if (!PNData.IsDBNull(r["CAPTION_FONT_COLOR"]))
                    {
                        try
                        {
                            var clr = mediaColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                    (string)r["CAPTION_FONT_COLOR"]);
                            if (clr != null)
                            {
                                note.Skinless.CaptionColor = (Color)clr;
                            }
                        }
                        catch (FormatException)
                        {
                            //possible FormatException after synchronization with old database
                            var clr = drawingColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                    (string)r["CAPTION_FONT_COLOR"]);
                            if (clr != null)
                            {
                                var drawingColor = (System.Drawing.Color)clr;
                                note.Skinless.CaptionColor = Color.FromArgb(drawingColor.A, drawingColor.R, drawingColor.G,
                                    drawingColor.B);
                                var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET CAPTION_FONT_COLOR = '");
                                sb.Append(mediaColorConverter.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.CaptionColor));
                                sb.Append("' WHERE NOTE_ID = '");
                                sb.Append(r["NOTE_ID"]);
                                sb.Append("'");
                                PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                            }
                        }
                    }
                    if (!PNData.IsDBNull(r["CAPTION_FONT"]))
                    {
                        var fontString = (string)r["CAPTION_FONT"];
                        //try
                        //{
                        var fonts = new InstalledFontCollection();
                        var arr = fontString.Split(',');
                        if (fontString.Any(ch => ch == '^'))
                        {
                            //old format font string
                            var lfc = new PNStaticFonts.LogFontConverter();
                            var lf = lfc.ConvertFromString((string)r["CAPTION_FONT"]);
                            note.Skinless.CaptionFont = PNStatic.FromLogFont(lf);
                            var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET CAPTION_FONT = '");
                            sb.Append(wfc.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.CaptionFont));
                            sb.Append("' WHERE NOTE_ID = '");
                            sb.Append(r["NOTE_ID"]);
                            sb.Append("'");
                            PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                        }
                        else if (fonts.Families.Any(ff => ff.Name == arr[0]))
                        {
                            note.Skinless.CaptionFont = (PNFont)wfc.ConvertFromString((string)r["CAPTION_FONT"]);
                        }
                        else
                        {
                            //possible note existing font name
                            arr[0] = PNStrings.DEF_CAPTION_FONT;
                            fontString = string.Join(",", arr);
                            note.Skinless.CaptionFont = (PNFont)wfc.ConvertFromString(fontString);
                            var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET CAPTION_FONT = '");
                            sb.Append(fontString);
                            sb.Append("' WHERE NOTE_ID = '");
                            sb.Append(r["NOTE_ID"]);
                            sb.Append("'");
                            PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                        }
                        //}
                        //catch (IndexOutOfRangeException)
                        //{
                        //    //possible IndexOutOfRangeException after synchronization with old database
                        //    var lfc = new PNStaticFonts.LogFontConverter();
                        //    var lf = lfc.ConvertFromString((string)r["CAPTION_FONT"]);
                        //    note.Skinless.CaptionFont = PNStatic.FromLogFont(lf);
                        //    var sb = new StringBuilder("UPDATE CUSTOM_NOTES_SETTINGS SET CAPTION_FONT = '");
                        //    sb.Append(wfc.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.CaptionFont));
                        //    sb.Append("' WHERE NOTE_ID = '");
                        //    sb.Append(r["NOTE_ID"]);
                        //    sb.Append("'");
                        //    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                        //}
                    }
                }
                if (!PNData.IsDBNull(r["SKIN_NAME"]))
                {
                    note.Skin = new PNSkinDetails { SkinName = (string)r["SKIN_NAME"] };
                    var path = Path.Combine(PNPaths.Instance.SkinsDir, note.Skin.SkinName);
                    path += ".pnskn";
                    if (File.Exists(path))
                    {
                        PNSkinsOperations.LoadSkin(path, note.Skin);
                    }
                }
                if (!PNData.IsDBNull(r["CUSTOM_OPACITY"]))
                {
                    note.CustomOpacity = (bool)r["CUSTOM_OPACITY"];
                }
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
            }
        }
Ejemplo n.º 27
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var str = value as string;
            if (str == null) return base.ConvertFrom(context, culture, value);
            var skl = new PNSkinlessDetails();
            var values = str.Split(DEL_INNER);
            if (values.Length != 3) return skl;
            var cr = new ColorConverter();
            var wpfFontConverter = new WPFFontConverter();
            var lfc = new LogFontConverter();
            object convertFromString;

            try
            {
                convertFromString = cr.ConvertFromString(null, PNStatic.CultureInvariant, values[0]);
                if (convertFromString != null)
                    skl.BackColor = (Color)convertFromString;
            }
            catch (FormatException)
            {
                var drawingColorConverter = new System.Drawing.ColorConverter();
                convertFromString = drawingColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                    values[0]);
                if (convertFromString != null)
                {
                    var clr = (System.Drawing.Color)convertFromString;
                    skl.BackColor = Color.FromArgb(clr.A, clr.R, clr.G, clr.B);
                }
            }

            try
            {
                convertFromString = cr.ConvertFromString(null, PNStatic.CultureInvariant, values[1]);
                if (convertFromString != null)
                    skl.CaptionColor = (Color)convertFromString;
            }
            catch (FormatException)
            {
                var drawingColorConverter = new System.Drawing.ColorConverter();
                convertFromString = drawingColorConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                    values[1]);
                if (convertFromString != null)
                {
                    var clr = (System.Drawing.Color)convertFromString;
                    skl.CaptionColor = Color.FromArgb(clr.A, clr.R, clr.G, clr.B);
                }
            }

            if (values[2].Any(c => c == '^'))
            {
                var logFont = lfc.ConvertFromString(values[2]);
                skl.CaptionFont = PNStatic.FromLogFont(logFont);
            }
            else
            {
                skl.CaptionFont = (PNFont) wpfFontConverter.ConvertFromString(values[2]);
            }
            return skl;
        }
Ejemplo n.º 28
0
        private static void DrawGridPatch(
            Vector3Collection positions, IntCollection indices, Color4Collection colors, int startX, int startY)
        {
            var c1 = (Color)ColorConverter.ConvertFromString("#c5d1d8");

            c1.Clamp();
            var c2 = (Color)ColorConverter.ConvertFromString("#ddeaf2");

            c2.Clamp();

            var darkGridColor  = new Color4(new Vector4(c1.ScR, c1.ScG, c1.ScB, 1));
            var lightGridColor = new Color4(new Vector4(c2.ScR, c2.ScG, c2.ScB, 1));

            const int size = 10;

            for (var x = startX; x <= startX + size; x++)
            {
                if (x == 0 && startY < 0)
                {
                    continue;
                }

                var v = new Vector3(x, -.001f, startY);
                positions.Add(v);
                indices.Add(positions.Count - 1);
                positions.Add(new Vector3(x, -.001f, startY + size));
                indices.Add(positions.Count - 1);

                if (x % 5 == 0)
                {
                    colors.Add(darkGridColor);
                    colors.Add(darkGridColor);
                }
                else
                {
                    colors.Add(lightGridColor);
                    colors.Add(lightGridColor);
                }
            }

            for (var y = startY; y <= startY + size; y++)
            {
                if (y == 0 && startX >= 0)
                {
                    continue;
                }

                positions.Add(new Vector3(startX, -.001f, y));
                indices.Add(positions.Count - 1);
                positions.Add(new Vector3(startX + size, -.001f, y));
                indices.Add(positions.Count - 1);

                if (y % 5 == 0)
                {
                    colors.Add(darkGridColor);
                    colors.Add(darkGridColor);
                }
                else
                {
                    colors.Add(lightGridColor);
                    colors.Add(lightGridColor);
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Prepares the Layout.. rendering all the necessary controls
        /// </summary>
        public void PrepareLayout(string layoutPath)
        {
            // Create a start record for this layout
            //  ClientManager.Instance.Stat = new Stat();
            // ClientManager.Instance.Stat.FileType = StatType.Layout;
            //   ClientManager.Instance.Stat.ScheduleID = ClientManager.Instance.ScheduleId;
            //    ClientManager.Instance.Stat.LayoutID = _layoutId;
            //   ClientManager.Instance.Stat.FromDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            LayoutModel layout;

            // Default or not
            if (layoutPath == Settings.Default.LibraryPath + @"\Default.xml" || String.IsNullOrEmpty(layoutPath))
            {
                throw new Exception("Default layout");
            }
            else
            {
                try
                {
                    // Get this layouts XML
                    using (var file = File.Open(layoutPath, FileMode.Open, FileAccess.Read, FileShare.Write))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(LayoutModel));
                        layout = (LayoutModel)serializer.Deserialize(file);
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Could not find the layout file {0}: {1}", layoutPath, ex.Message));
                    throw;
                }
            }

            // Attributes of the main layout node



            // Set the background and size of the form
            _layoutWidth  = layout.Width;
            _layoutHeight = layout.Height;


            //// Scaling factor, will be applied to all regions
            //_scaleFactor = Math.Max(_clientSize.Width / _layoutWidth, _clientSize.Height / _layoutHeight);

            //// Want to be able to center this shiv - therefore work out which one of these is going to have left overs
            int backgroundWidth  = _clientSize.Width;  // (int)(_layoutWidth * _scaleFactor);
            int backgroundHeight = _clientSize.Height; //(int)(_layoutHeight * _scaleFactor);

            //double leftOverX;
            //double leftOverY;

            //try
            //{
            //    leftOverX = Math.Abs(_clientSize.Width - backgroundWidth);
            //    leftOverY = Math.Abs(_clientSize.Height - backgroundHeight);

            //    if (leftOverX != 0) leftOverX = leftOverX / 2;
            //    if (leftOverY != 0) leftOverY = leftOverY / 2;
            //}
            //catch
            //{
            //    leftOverX = 0;
            //    leftOverY = 0;
            //}


            // New region and region options objects
            _regions = new Collection <Region>();
            RegionOptions options = new RegionOptions();

            // Deal with the color
            try
            {
                if (!String.IsNullOrEmpty(layout.Bgcolor))
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                    {
                        MediaCanvas.Background =
                            new SolidColorBrush((Color)ColorConverter.ConvertFromString(layout.Bgcolor));
                    }));
                    options.backgroundColor = layout.Bgcolor;
                }
            }
            catch
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                {
                    MediaCanvas.Background = new SolidColorBrush(Colors.Black); // Default black
                }));


                options.backgroundColor = "#000000";
            }

            // Get the background
            try
            {
                if (layout.Background == null)
                {
                    // Assume there is no background image
                    MediaCanvas.Background  = null;
                    options.backgroundImage = "";
                }
                else
                {
                    string bgFilePath = Settings.Default.LibraryPath + @"\backgrounds\" + backgroundWidth + "x" + backgroundHeight + "_" + layout.Background;
                    Utilities.CreateFolder(Path.GetDirectoryName(bgFilePath));
                    // Create a correctly sized background image in the temp folder
                    if (!File.Exists(bgFilePath))
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromFile(Settings.Default.LibraryPath + @"\" + layout.Background);

                        Bitmap            bmp = new Bitmap(img, backgroundWidth, backgroundHeight);
                        EncoderParameters encoderParameters = new EncoderParameters(1);
                        EncoderParameter  qualityParam      = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
                        encoderParameters.Param[0] = qualityParam;

                        ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

                        bmp.Save(bgFilePath, jpegCodec, encoderParameters);

                        img.Dispose();
                        bmp.Dispose();
                    }

                    Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                    {
                        MediaCanvas.Background = new ImageBrush(new BitmapImage(new Uri(bgFilePath.Replace("\\", "/"), UriKind.Relative)));
                    }));

                    options.backgroundImage = bgFilePath;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to set background: " + ex.Message);

                // Assume there is no background image
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() =>
                {
                    MediaCanvas.Background = Brushes.Black;
                }));

                options.backgroundImage = "";
            }

            // Get it to paint the background now
            App.DoEvents();

            // Get the regions
            var listRegions = layout.Regions;
            var listMedia   = layout.Regions.Select(r => r.Media).ToList();

            // Check to see if there are any regions on this layout.
            if (listRegions.Count == 0 || listMedia.Count == 0)
            {
                Trace.WriteLine(new LogMessage("PrepareLayout",
                                               string.Format("A layout with {0} regions and {1} media has been detected.", listRegions.Count.ToString(), listMedia.Count.ToString())),
                                LogType.Info.ToString());

                if (ClientManager.Instance.Schedule.ActiveLayouts == 1)
                {
                    Trace.WriteLine(new LogMessage("PrepareLayout", "Only 1 layout scheduled and it has nothing to show."), LogType.Info.ToString());

                    throw new Exception("Only 1 layout schduled and it has nothing to show");
                }
                else
                {
                    Trace.WriteLine(new LogMessage("PrepareLayout",
                                                   string.Format(string.Format("An empty layout detected, will show for {0} seconds.", Settings.Default.emptyLayoutDuration.ToString()))), LogType.Info.ToString());

                    // Put a small dummy region in place, with a small dummy media node - which expires in 10 seconds.
                    // Replace the list of regions (they mean nothing as they are empty)
                    listRegions = new List <LayoutRegion>()
                    {
                        new LayoutRegion()
                        {
                            Id    = "blah", Width = 1, Height = 1, Top = 1, Left = 1,
                            Media = new List <LayoutRegionMedia>()
                            {
                                new LayoutRegionMedia()
                                {
                                    Id       = "blah",
                                    Type     = "Text",
                                    Duration = 0,
                                    Raw      = new LayoutRegionMediaRaw()
                                    {
                                        Text = ""
                                    }
                                }
                            }
                        }
                    };
                }
            }

            foreach (var region in listRegions)
            {
                // Is there any media
                if (region.Media.Count == 0)
                {
                    if (region.Type != "Widget")
                    {
                        Debug.WriteLine("A region with no media detected");
                        continue;
                    }
                }

                //each region
                options.scheduleId = ClientManager.Instance.ScheduleId;
                options.layoutId   = _layoutId;
                options.regionId   = region.Id;
                options.Name       = region.Name;
                options.FileType   = region.Type;
                options.Width      = (int)((region.Width + 30.0) / _layoutWidth * _clientSize.Width);  //(int)((region.Width + 15.0) * _scaleFactor);
                options.Height     = (int)((region.Height + 30) / _layoutHeight * _clientSize.Height); //(int)((region.Height + 15.0) * _scaleFactor);
                var left = region.Left - 15;
                if (left < 0)
                {
                    left = 0;
                }

                var top = region.Top - 15;
                if (top < 0)
                {
                    top = 0;
                }

                options.Left = (int)(left / _layoutWidth * _clientSize.Width);  //(int)(region.Left * _scaleFactor);
                options.Top  = (int)(top / _layoutHeight * _clientSize.Height); //(int)(region.Top * _scaleFactor);

                options.ScaleFactor = _scaleFactor;

                // Set the backgrounds (used for Web content offsets)
                options.BackgroundLeft = options.Left * -1;
                options.BackgroundTop  = options.Top * -1;

                //Account for scaling
                //       options.Left = options.Left + (int)leftOverX;
                //        options.Top = options.Top + (int)leftOverY;

                // All the media nodes for this region / layout combination
                options.mediaNodes = region.Media;

                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action <RegionOptions>(
                                           (opts) =>
                {
                    Region temp = new Region(ClientManager.Instance.StatLog, ClientManager.Instance.CacheManager);
                    temp.DurationElapsedEvent += new Region.DurationElapsedDelegate(TempDurationElapsedEvent);

                    Debug.WriteLine("Created new region", "Charging Player - Prepare Layout");

                    // Dont be fooled, this innocent little statement kicks everything off
                    temp.RegionOptions = opts;

                    _regions.Add(temp);

                    temp.Opacity = 0;

                    MediaCanvas.Children.Add(temp);

                    temp.AnimateIn();

                    //          new TextBox(){
                    //Text                                                                        = "Hey",
                    //                                                                          Margin = new Thickness(options.left,options.top,0,0),
                    //                                                                          Height = options.Height,
                    //                                                                          Width = options.Width
                    //                                                                        })
                    ;
                    //   temp.Background = new SolidColorBrush(Colors.Coral);
                }), options);


                Debug.WriteLine("Adding region", "Charging - Prepare Layout");


                App.DoEvents();
            }

            // Null stuff
            listRegions = null;
            listMedia   = null;
        }
Ejemplo n.º 30
0
        public static void SetRichFormatText(this TextBlock textBlock, string text)
        {
            if (textBlock == null)
            {
                return;
            }
            string[] strs = text.Split('[');
            textBlock.ClearValue(TextBlock.TextProperty);
            var          solidColorBrush = textBlock.Foreground as SolidColorBrush;
            List <Color> colors          = new List <Color> {
                Colors.Black
            };
            List <double> fontSizes = new List <double> {
                textBlock.FontSize
            };
            List <FontWeight> weights = new List <FontWeight> {
                textBlock.FontWeight
            };

            if (solidColorBrush != null)
            {
                colors.Add(solidColorBrush.Color);
            }
            foreach (string str in strs)
            {
                string[] parts = str.Split(']');
                string   txt;
                if (parts.Length > 1)
                {
                    txt = parts[1];
                    string   format = parts[0];
                    string[] fParts = format.Split('=');
                    if (fParts.Length == 1)//end tag
                    {
                        switch (fParts[0])
                        {
                        case "color":
                            colors.RemoveAt(colors.Count - 1);
                            break;

                        case "weight":
                            weights.RemoveAt(weights.Count - 1);
                            break;

                        case "fsize":
                            fontSizes.RemoveAt(fontSizes.Count - 1);
                            break;
                        }
                    }
                    else
                    {
                        switch (fParts[0])
                        {
                        case "color":
                            string color    = fParts[1];
                            var    colorObj = ColorConverter.ConvertFromString(color);

                            if (colorObj != null)
                            {
                                colors.Add((Color)colorObj);
                            }
                            break;

                        case "weight":
                            var fontWeight = new FontWeightConverter().ConvertFromString(fParts[1]);
                            if (fontWeight != null)
                            {
                                weights.Add((FontWeight)fontWeight);
                            }
                            break;

                        case "fsize":
                            double fontSize = fontSizes.Last();
                            string fSize    = fParts[1];
                            if (fParts[1].StartsWith("+") || fParts[1].StartsWith("-"))
                            {
                                fSize = fParts[1].Substring(1);
                            }
                            var ok = double.TryParse(fSize, out fontSize);

                            if (ok)
                            {
                                if (fParts[1].StartsWith("+"))
                                {
                                    fontSize = fontSizes.Last() + fontSize;
                                }
                                if (fParts[1].StartsWith("-"))
                                {
                                    fontSize = fontSizes.Last() - fontSize;
                                }
                                fontSizes.Add(fontSize);
                            }

                            break;

                        case "image":
                            string imageUrl = fParts[1];
                            AddImage(textBlock, imageUrl, 1.2, BaselineAlignment.Center);
                            break;
                        }
                    }
                }
                else
                {
                    txt = parts[0];
                }
                if (!string.IsNullOrEmpty(txt))
                {
                    textBlock.Inlines.Add(new Run(txt)
                    {
                        Foreground        = new SolidColorBrush(colors.Last()),
                        FontWeight        = weights.Last(),
                        FontSize          = fontSizes.Last(),
                        BaselineAlignment = BaselineAlignment.Center
                    });
                }
            }
        }
Ejemplo n.º 31
0
        private async void ExportButton_Click(object sender, RoutedEventArgs e)
        {
            if (ImageConverter.IsLoaded)
            {
                ExportButton.IsEnabled      = false;
                Options.IsEnabled           = false;
                BrowsImageButton.IsEnabled  = false;
                BrowsFolderButton.IsEnabled = false;
                ButtonProgressAssist.SetValue(ExportButton, 0);
                int        coord     = CoordinateAxis.SelectedIndex;
                int        verAlig   = VerticalAlignmentBox.SelectedIndex;
                int        horAlig   = HorizontalAlignmentBox.SelectedIndex;
                Particle[] particles = ImageConverter.GetParticles(coord, verAlig, horAlig);
                ButtonProgressAssist.SetMaximum(ExportButton, particles.Length + 20);
                ButtonProgressAssist.SetValue(ExportButton, 20);
                ExportButton.UpdateLayout();
                string       fileName = System.IO.Path.GetFileNameWithoutExtension(FilePathBox.Text);
                string       filePath = FolderPathBox.Text + "\\" + fileName.ToLower() + ".mcfunction";
                Encoding     enc      = new System.Text.UTF8Encoding();;
                StreamWriter writer   = null;
                try
                {
                    string cs = "~";
                    switch (((ComboBoxItem)CoordinateModeBox.SelectedItem).Tag)
                    {
                    case "Relative":
                        cs = "~";
                        break;

                    case "Local":
                        cs = "^";
                        break;
                    }
                    if (!Directory.Exists(System.IO.Path.GetDirectoryName(filePath)))
                    {
                        Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
                    }
                    var fullname = typeof(App).Assembly.Location;
                    var info     = FileVersionInfo.GetVersionInfo(fullname);
                    var ver      = info.FileVersion;
                    writer = new StreamWriter(filePath, false, enc);
                    writer.WriteLine($"### Particle Image Function");
                    writer.WriteLine($"### Version: {ver}");
                    writer.WriteLine($"### Width: {ImageConverter.ResizedWidth}");
                    writer.WriteLine($"### Height: {ImageConverter.ResizedHeight}");
                    writer.WriteLine($"### ParticleType: {ParticleTypeBox.SelectedValue}");
                    writer.WriteLine($"");
                    writer.WriteLine($"### This file was generated by Kemo431's Particle-Converter.");
                    writer.WriteLine($"### Download Link: https://github.com/kemo14331/Particle-Converter");
                    writer.WriteLine($"");
                    for (int i = 0; i < particles.Length; i++)
                    {
                        var    p        = particles[i];
                        string axis     = $"{cs}{Math.Round(p.x, 7).ToString("R", format)} {cs}{Math.Round(p.y, 7).ToString("R", format)} {cs}{Math.Round(p.z, 7).ToString("R", format)}";
                        string particle = "minecraft:" + ParticleTypeBox.Text;
                        if (ParticleTypeBox.SelectedValue.Equals("dust"))
                        {
                            if (UseStaticDustColor.IsChecked.Value)
                            {
                                Color color = (Color)ColorConverter.ConvertFromString(ColorCodeBox.Text);
                                particle += $" {Math.Round(color.R / 255.0d, 2).ToString("R", format)} {Math.Round(color.G / 255.0d, 2).ToString("R", format)} {Math.Round(color.B / 255.0d, 2).ToString("R", format)} {double.Parse(ParticleSizeBox.Text).ToString("R", format)}";
                            }
                            else
                            {
                                particle += $" {Math.Round(p.r / 255.0d, 2).ToString("R", format)} {Math.Round(p.g / 255.0d, 2).ToString("R", format)} {Math.Round(p.b / 255.0d, 2).ToString("R", format)} {double.Parse(ParticleSizeBox.Text).ToString("R", format)}";
                            }
                        }
                        string particleString = $"particle {particle} {axis} 0 0 0 0 1 {((ComboBoxItem)DisplayModeBox.SelectedItem).Tag} {ParticleViewerBox.Text}";
                        await Task.Run(() =>
                        {
                            writer.WriteLine(particleString);
                        });

                        ButtonProgressAssist.SetValue(ExportButton, 20 + 1 + i);
                    }
                }
                catch (Exception exc)
                {
                    MessageBox.Show("ファイルの書き込みに失敗しました\nFailed to export a file.",
                                    "エラー/Error",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    Logger.WriteExceptionLog(exc);
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                    }
                }
                ButtonProgressAssist.SetValue(ExportButton, 0);
                Options.IsEnabled           = true;
                ExportButton.IsEnabled      = true;
                BrowsImageButton.IsEnabled  = true;
                BrowsFolderButton.IsEnabled = true;
                SystemSounds.Beep.Play();
            }
            else
            {
                SystemSounds.Beep.Play();
            }
        }
Ejemplo n.º 32
0
        private void Update_Preview()
        {
            try
            {
                if (ImageConverter.IsLoaded && UsePreviewBox.IsChecked.Value)
                {
                    int coord   = CoordinateAxis.SelectedIndex;
                    int verAlig = VerticalAlignmentBox.SelectedIndex;
                    int horAlig = HorizontalAlignmentBox.SelectedIndex;
                    //Mat smat = ImageConverter.GetModifiedImage();
                    //System.Windows.Size size = ImageConverter.GetBlocks();
                    //Bitmap bitmap = smat.ToBitmap();
                    //var mb = new MeshBuilder(false, true);

                    //IList<Point3D> pnts = new List<Point3D>
                    //{
                    //    new Point3D(0, 0, 0),
                    //    new Point3D(size.Width, 0, 0),
                    //    new Point3D(size.Width, size.Height, 0),
                    //    new Point3D(0, size.Height, 0)
                    //};

                    //mb.AddPolygon(pnts);

                    //var mesh = mb.ToMesh(false);

                    //PointCollection pntCol = new PointCollection
                    //{
                    //    new System.Windows.Point(0, 0),
                    //    new System.Windows.Point(bitmap.Size.Width, 0),
                    //    new System.Windows.Point(bitmap.Size.Width, bitmap.Size.Height),
                    //    new System.Windows.Point(0, bitmap.Size.Height)
                    //};
                    //mesh.TextureCoordinates = pntCol;

                    //ImageBrush brush = new ImageBrush();

                    //using (Stream stream = new MemoryStream())
                    //{
                    //    bitmap.Save(stream, ImageFormat.Png);
                    //    stream.Seek(0, SeekOrigin.Begin);
                    //    BitmapImage img = new BitmapImage();
                    //    img.BeginInit();
                    //    img.CacheOption = BitmapCacheOption.OnLoad;
                    //    img.StreamSource = stream;
                    //    img.EndInit();
                    //    brush.ImageSource = img;
                    //}

                    //brush.TileMode = TileMode.Tile;
                    //brush.ViewportUnits = BrushMappingMode.Absolute;
                    //brush.ViewboxUnits = BrushMappingMode.Absolute;
                    //brush.Stretch = Stretch.None;
                    //brush.AlignmentX = AlignmentX.Left;
                    //brush.AlignmentY = AlignmentY.Top;
                    //brush.Viewport = new System.Windows.Rect(0, 0, brush.ImageSource.Width, brush.ImageSource.Height);
                    //DiffuseMaterial mat = new DiffuseMaterial(brush);

                    //GeometryModel3D gModel3D = new GeometryModel3D { Geometry = mesh, Material = mat, BackMaterial = mat };

                    //PreviewModel.Content = gModel3D;
                    Particle[] particles = ImageConverter.GetParticles(coord, verAlig, horAlig);
                    //ParticleModel.Children.Clear();
                    var points  = new PointGeometry3D();
                    var vectors = new Vector3Collection();
                    var colors  = new Color4Collection();
                    var ptIdx   = new IntCollection();
                    int i       = 0;
                    foreach (Particle particle in particles)
                    {
                        vectors.Add(new Vector3((float)particle.x, (float)particle.y, (float)particle.z));
                        if (UseStaticDustColor.IsChecked.Value)
                        {
                            Color c = (Color)ColorConverter.ConvertFromString(ColorCodeBox.Text);
                            colors.Add(new Color4(c.R / 255f, c.G / 255f, c.B / 255f, 1.0f));
                        }
                        else
                        {
                            colors.Add(new Color4(particle.r / 255f, particle.g / 255f, particle.b / 255f, 1.0f));
                        }
                        ptIdx.Add(i);
                        i++;
                    }
                    points.Positions       = vectors;
                    points.Colors          = colors;
                    points.Indices         = ptIdx;
                    ParticleModel.Geometry = points;
                    double size = double.Parse(ParticleSizeBox.Text);
                    ParticleModel.Size   = new System.Windows.Size(3 * Math.Sqrt(size), 3 * Math.Sqrt(size));
                    ParticleCounter.Text = $"Particles: {particles.Length}";
                    if (particles.Length >= 2000)
                    {
                        ParticleCounter.Foreground = new SolidColorBrush(Colors.Red);
                        CounterAlert.Visibility    = Visibility.Visible;
                    }
                    else
                    {
                        ParticleCounter.Foreground = new SolidColorBrush(Colors.Snow);
                        CounterAlert.Visibility    = Visibility.Hidden;
                    }
                }
            }
            catch (Exception e)
            {
                Logger.WriteExceptionLog(e);
                MessageBox.Show("プレビューの更新に失敗しました\nFailed to update preview.",
                                "エラー/Error",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
                this.Close();
            }
        }
Ejemplo n.º 33
0
        internal static void LoadDBSettings()
        {
            try
            {
                var mediaConverter = new ColorConverter();
                var drawingConverter = new System.Drawing.ColorConverter();
                var sc = new SizeConverter();
                var pc = new PointConverter();
                var wpfc = new WPFFontConverter();
                //var fc = new FontConverter();
                var v = Assembly.GetExecutingAssembly().GetName().Version;
                PNStatic.Settings = new PNSettings();
                SettingsConnectionString = SQLiteDataObject.CheckAndCreateDatabase(PNPaths.Instance.SettingsDBPath);
                using (var oData = new SQLiteDataObject(SettingsConnectionString))
                {
                    string sqlQuery;
                    //config
                    var pnc = PNStatic.Settings.Config;
                    if (!oData.TableExists("CONFIG"))
                    {
                        sqlQuery = "CREATE TABLE [CONFIG] ([LAST_PAGE] TEXT, [EXIT_FLAG] INT, [CP_LAST_GROUP] INT, [SKINNABLE] BOOLEAN, [CP_PVW_COLOR] TEXT, [CP_USE_CUST_PVW_COLOR] BOOLEAN, [CP_SIZE] TEXT, [CP_LOCATION] TEXT, [CONTROLS_STYLE] TEXT, [CP_PVW_RIGHT] BOOLEAN, [UI_FONT] TEXT, [PROGRAM_VERSION] TEXT, [CP_PVW_SHOW] BOOLEAN, [CP_GROUPS_SHOW] BOOLEAN, [NOTES_WITH_SHORTCUTS] TEXT, [SEARCH_NOTES_SETT] TEXT)";
                        oData.Execute(sqlQuery);
                        sqlQuery =
                            "INSERT INTO CONFIG VALUES(NULL, -1, NULL, NULL, NULL, NULL, '1000,600', NULL, NULL, NULL, NULL, '" +
                            v.ToString(3) + "', NULL, NULL, NULL, NULL)";
                        oData.Execute(sqlQuery);
                        PNSingleton.Instance.FontUser = new PNFont();
                        pnc.CPSize = new Size(1000, 600);
                    }
                    else
                    {
                        using (var t = oData.GetSchema("Columns"))
                        {
                            var rows = t.Select("COLUMN_NAME = 'PROGRAM_VERSION' AND TABLE_NAME = 'CONFIG'");
                            if (rows.Length == 0)
                            {
                                PNSingleton.Instance.PlatformChanged = true;
                                sqlQuery = "ALTER TABLE CONFIG ADD COLUMN [PROGRAM_VERSION] TEXT";
                                oData.Execute(sqlQuery);
                                //save previous edition files
                                PNStatic.SpTextProvider.SplashText = PNLang.Instance.GetMessageText("back_prev",
                                    "Backing up files from previous edition...");
                                savePreviousFiles();
                            }
                            rows = t.Select("COLUMN_NAME = 'CP_PVW_RIGHT' AND TABLE_NAME = 'CONFIG'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE CONFIG ADD COLUMN [CP_PVW_RIGHT] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'CP_PVW_SHOW' AND TABLE_NAME = 'CONFIG'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE CONFIG ADD COLUMN [CP_PVW_SHOW] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'CP_GROUPS_SHOW' AND TABLE_NAME = 'CONFIG'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE CONFIG ADD COLUMN [CP_GROUPS_SHOW] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'UI_FONT' AND TABLE_NAME = 'CONFIG'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE CONFIG ADD COLUMN [UI_FONT] TEXT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'NOTES_WITH_SHORTCUTS' AND TABLE_NAME = 'CONFIG'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE CONFIG ADD COLUMN [NOTES_WITH_SHORTCUTS] TEXT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'SEARCH_NOTES_SETT' AND TABLE_NAME = 'CONFIG'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE CONFIG ADD COLUMN [SEARCH_NOTES_SETT] TEXT";
                                oData.Execute(sqlQuery);
                            }
                        }
                        //store version
                        sqlQuery = "UPDATE CONFIG SET PROGRAM_VERSION = '" + v.ToString(3) + "'";
                        oData.Execute(sqlQuery);
                        //upgrade colors an fonts
                        if (PNSingleton.Instance.PlatformChanged)
                        {
                            var obj = oData.GetScalar("SELECT CP_PVW_COLOR FROM CONFIG");
                            if (obj != null && !IsDBNull(obj))
                            {
                                obj = drawingConverter.ConvertFromString(null, PNStatic.CultureInvariant, (string)obj);
                                if (obj != null)
                                {
                                    var clrD = (System.Drawing.Color)obj;
                                    var clrM = Color.FromArgb(clrD.A, clrD.R, clrD.G, clrD.B);
                                    var clrText = mediaConverter.ConvertToString(clrM);
                                    oData.Execute("UPDATE CONFIG SET CP_PVW_COLOR = '" + clrText + "'");
                                }
                            }
                            obj = oData.GetScalar("SELECT UI_FONT FROM CONFIG");
                            if (obj != null && !IsDBNull(obj))
                            {
                                var pnFonf = PNStatic.FromDrawingFont((string)obj);
                                var fontText = wpfc.ConvertToString(pnFonf);
                                oData.Execute("UPDATE CONFIG SET UI_FONT = '" + fontText + "'");
                            }
                        }
                        sqlQuery = "SELECT * FROM CONFIG";
                        using (var t = oData.FillDataTable(sqlQuery))
                        {
                            if (t.Rows.Count > 0)
                            {
                                var r = t.Rows[0];
                                if (!IsDBNull(r["LAST_PAGE"]))
                                {
                                    pnc.LastPage = Convert.ToInt32(r["LAST_PAGE"]);
                                }

                                if (!IsDBNull(r["EXIT_FLAG"]))
                                {
                                    pnc.ExitFlag = (int)r["EXIT_FLAG"];
                                }
                                if (!IsDBNull(r["CP_LAST_GROUP"]))
                                {
                                    pnc.CPLastGroup = (int)r["CP_LAST_GROUP"];
                                }
                                if (!IsDBNull(r["SKINNABLE"]))
                                {
                                    pnc.Skinnable = Convert.ToBoolean(r["SKINNABLE"]);
                                }
                                if (!IsDBNull(r["CP_PVW_COLOR"]))
                                {
                                    var convertFromString = mediaConverter.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["CP_PVW_COLOR"]);
                                    if (
                                        convertFromString != null)
                                        pnc.CPPvwColor = (Color)convertFromString;
                                }
                                if (!IsDBNull(r["CP_USE_CUST_PVW_COLOR"]))
                                {
                                    pnc.CPUseCustPvwColor = Convert.ToBoolean(r["CP_USE_CUST_PVW_COLOR"]);
                                }
                                if (!IsDBNull(r["CP_SIZE"]))
                                {
                                    var str = Convert.ToString(r["CP_LOCATION"]);
                                    if (!str.Contains('-'))
                                    {
                                        str = Convert.ToString(r["CP_SIZE"]);
                                        var convertFromString = sc.ConvertFromString(null, PNStatic.CultureInvariant,
                                            str);
                                        if (convertFromString != null)
                                            pnc.CPSize = (Size)convertFromString;
                                    }
                                }
                                if (!IsDBNull(r["CP_LOCATION"]))
                                {
                                    var convertFromString = pc.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["CP_LOCATION"]);
                                    if (
                                        convertFromString != null)
                                        pnc.CPLocation = (Point)convertFromString;
                                }
                                if (!IsDBNull(r["CONTROLS_STYLE"]))
                                {
                                    pnc.ControlsStyle = (string)r["CONTROLS_STYLE"];
                                }
                                if (!IsDBNull(r["CP_PVW_RIGHT"]))
                                {
                                    pnc.CPPvwRight = Convert.ToBoolean(r["CP_PVW_RIGHT"]);
                                }
                                if (!IsDBNull(r["CP_PVW_SHOW"]))
                                {
                                    pnc.CPPvwShow = Convert.ToBoolean(r["CP_PVW_SHOW"]);
                                }
                                if (!IsDBNull(r["CP_GROUPS_SHOW"]))
                                {
                                    pnc.CPGroupsShow = Convert.ToBoolean(r["CP_GROUPS_SHOW"]);
                                }
                                if (!IsDBNull(r["UI_FONT"]))
                                {
                                    var temp = (string)(r["UI_FONT"]);
                                    if (temp != "")
                                    {
                                        PNSingleton.Instance.FontUser = (PNFont)wpfc.ConvertFromString(temp);
                                    }
                                    else
                                    {
                                        PNSingleton.Instance.FontUser = new PNFont();
                                    }
                                }
                                else
                                {
                                    PNSingleton.Instance.FontUser = new PNFont();
                                }
                                if (!IsDBNull(r["SEARCH_NOTES_SETT"]))
                                {
                                    var arr = Convert.ToString(r["SEARCH_NOTES_SETT"]).Split('|');
                                    pnc.SearchNotesSettings.WholewWord = Convert.ToBoolean(arr[0]);
                                    pnc.SearchNotesSettings.MatchCase = Convert.ToBoolean(arr[1]);
                                    pnc.SearchNotesSettings.IncludeHidden = Convert.ToBoolean(arr[2]);
                                    pnc.SearchNotesSettings.Criteria = Convert.ToInt32(arr[3]);
                                    pnc.SearchNotesSettings.Scope = Convert.ToInt32(arr[4]);
                                }
                                SaveExitFlag(-1);
                            }
                            else
                            {
                                sqlQuery =
                                    "INSERT INTO CONFIG VALUES(NULL, -1, NULL, NULL, NULL, NULL, '1000,600', NULL, NULL, NULL, NULL, '" +
                                    v.ToString(3) + "', NULL, NULL, NULL, NULL)";
                                oData.Execute(sqlQuery);
                                PNSingleton.Instance.FontUser = new PNFont();
                                pnc.CPSize = new Size(1000, 600);
                            }
                        }
                    }

                    //general setting
                    var pngeneral = PNStatic.Settings.GeneralSettings;
                    if (!oData.TableExists("GENERAL_SETTINGS"))
                    {
                        sqlQuery = "CREATE TABLE [GENERAL_SETTINGS] ([LANGUAGE] TEXT, [RUN_ON_START] BOOLEAN, [SHOW_CP_ON_START] BOOLEAN, [CHECK_NEW_VERSION_ON_START] BOOLEAN, [HIDE_TOOLBAR] BOOLEAN, [USE_CUSTOM_FONTS] BOOLEAN, [SHOW_SCROLLBAR] BOOLEAN, [HIDE_DELETE_BUTTON] BOOLEAN, [CHANGE_HIDE_TO_DELETE] BOOLEAN, [HIDE_HIDE_BUTTON] BOOLEAN, [BULLETS_INDENT] INT, [MARGIN_WIDTH] INT, [SAVE_ON_EXIT] BOOLEAN, [CONFIRM_SAVING] BOOLEAN, [CONFIRM_BEFORE_DELETION] BOOLEAN, [SAVE_WITHOUT_CONFIRM_ON_HIDE] BOOLEAN, [WARN_ON_AUTOMATICAL_DELETE] BOOLEAN, [AUTO_SAVE] BOOLEAN, [AUTO_SAVE_PERIOD] INT, [REMOVE_FROM_BIN_PERIOD] INT, [DATE_FORMAT] TEXT, [TIME_FORMAT] TEXT, [SKINLESS_WIDTH] INT, [SKINLESS_HEIGHT] INT, [SPELL_COLOR] TEXT, [USE_SKINS] BOOLEAN, [SPELL_MODE] INT, [SPELL_DICT] TEXT, [DOCK_WIDTH] INT, [DOCK_HEIGHT] INT, [SHOW_PRIORITY_ON_START] BOOLEAN, [BUTTONS_SIZE] INT, [AUTOMATIC_SMILIES] BOOLEAN, [SPACE_POINTS] INT, [RESTORE_AUTO] BOOLEAN, [PARAGRAPH_INDENT] INT, [AUTO_HEIGHT] BOOLEAN, [CRITICAL_ON_START] BOOLEAN, [CRITICAL_PERIODICALLY] BOOLEAN, [DELETE_SHORTCUTS_ON_EXIT] BOOLEAN, [RESTORE_SHORTCUTS_ON_START] BOOLEAN, [CLOSE_ON_SHORTCUT] BOOLEAN)";
                        oData.Execute(sqlQuery);
                        sqlQuery = "INSERT INTO GENERAL_SETTINGS VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                        oData.Execute(sqlQuery);
                        //store default english language
                        var langPath = Path.Combine(PNPaths.Instance.LangDir, pngeneral.Language);
                        PNLang.Instance.LoadLanguage(langPath);
                    }
                    else
                    {
                        using (var t = oData.GetSchema("Columns"))
                        {
                            var rows = t.Select("COLUMN_NAME = 'BUTTONS_SIZE' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [BUTTONS_SIZE] INT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'AUTOMATIC_SMILIES' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [AUTOMATIC_SMILIES] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'SPACE_POINTS' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [SPACE_POINTS] INT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'RESTORE_AUTO' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [RESTORE_AUTO] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'PARAGRAPH_INDENT' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [PARAGRAPH_INDENT] INT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'AUTO_HEIGHT' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [AUTO_HEIGHT] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'CRITICAL_ON_START' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [CRITICAL_ON_START] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'CRITICAL_PERIODICALLY' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [CRITICAL_PERIODICALLY] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'DELETE_SHORTCUTS_ON_EXIT' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [DELETE_SHORTCUTS_ON_EXIT] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'RESTORE_SHORTCUTS_ON_START' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [RESTORE_SHORTCUTS_ON_START] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'CLOSE_ON_SHORTCUT' AND TABLE_NAME = 'GENERAL_SETTINGS'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE GENERAL_SETTINGS ADD COLUMN [CLOSE_ON_SHORTCUT] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                        }
                        sqlQuery = "SELECT * FROM GENERAL_SETTINGS";
                        using (var t = oData.FillDataTable(sqlQuery))
                        {
                            if (t.Rows.Count > 0)
                            {
                                var r = t.Rows[0];
                                if (!IsDBNull(r["LANGUAGE"]))
                                {
                                    pngeneral.Language = (string) r["LANGUAGE"];
                                }
                                var langPath = Path.Combine(PNPaths.Instance.LangDir, pngeneral.Language);
                                PNLang.Instance.LoadLanguage(langPath);
                                if (!IsDBNull(r["RUN_ON_START"]))
                                {
                                    pngeneral.RunOnStart = (bool)r["RUN_ON_START"];
                                }
                                if (!IsDBNull(r["HIDE_TOOLBAR"]))
                                {
                                    pngeneral.HideToolbar = (bool)r["HIDE_TOOLBAR"];
                                }
                                if (!IsDBNull(r["SHOW_CP_ON_START"]))
                                {
                                    pngeneral.ShowCPOnStart = (bool)r["SHOW_CP_ON_START"];
                                }
                                if (!IsDBNull(r["CHECK_NEW_VERSION_ON_START"]))
                                {
                                    pngeneral.CheckNewVersionOnStart = (bool)r["CHECK_NEW_VERSION_ON_START"];
                                }
                                if (!IsDBNull(r["USE_CUSTOM_FONTS"]))
                                {
                                    pngeneral.UseCustomFonts = (bool)r["USE_CUSTOM_FONTS"];
                                }
                                if (!IsDBNull(r["SHOW_SCROLLBAR"]))
                                {
                                        pngeneral.ShowScrollbar =
                                            (System.Windows.Forms.RichTextBoxScrollBars)
                                                Convert.ToInt32(r["SHOW_SCROLLBAR"]);
                                }
                                if (!IsDBNull(r["HIDE_DELETE_BUTTON"]))
                                {
                                    pngeneral.HideDeleteButton = (bool)r["HIDE_DELETE_BUTTON"];
                                }
                                if (!IsDBNull(r["CHANGE_HIDE_TO_DELETE"]))
                                {
                                    pngeneral.ChangeHideToDelete = (bool)r["CHANGE_HIDE_TO_DELETE"];
                                }
                                if (!IsDBNull(r["HIDE_HIDE_BUTTON"]))
                                {
                                    pngeneral.HideHideButton = (bool)r["HIDE_HIDE_BUTTON"];
                                }
                                if (!IsDBNull(r["BULLETS_INDENT"]))
                                {
                                    pngeneral.BulletsIndent = (short)(int)r["BULLETS_INDENT"];
                                }
                                if (!IsDBNull(r["MARGIN_WIDTH"]))
                                {
                                    pngeneral.MarginWidth = (short)(int)r["MARGIN_WIDTH"];
                                }
                                if (!IsDBNull(r["DATE_FORMAT"]))
                                {
                                    pngeneral.DateFormat =
                                        ((string)r["DATE_FORMAT"]).Replace("H", "")
                                            .Replace("h", "")
                                            .Replace("m", "")
                                            .Replace(":", "")
                                            .Trim();
                                    Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = pngeneral.DateFormat;
                                }
                                if (!IsDBNull(r["TIME_FORMAT"]))
                                {
                                    pngeneral.TimeFormat = (string)r["TIME_FORMAT"];
                                    Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern = pngeneral.TimeFormat;
                                }
                                if (!IsDBNull(r["SAVE_ON_EXIT"]))
                                {
                                    pngeneral.SaveOnExit = (bool)r["SAVE_ON_EXIT"];
                                }
                                if (!IsDBNull(r["CONFIRM_SAVING"]))
                                {
                                    pngeneral.ConfirmSaving = (bool)r["CONFIRM_SAVING"];
                                }
                                if (!IsDBNull(r["CONFIRM_BEFORE_DELETION"]))
                                {
                                    pngeneral.ConfirmBeforeDeletion = (bool)r["CONFIRM_BEFORE_DELETION"];
                                }
                                if (!IsDBNull(r["SAVE_WITHOUT_CONFIRM_ON_HIDE"]))
                                {
                                    pngeneral.SaveWithoutConfirmOnHide = (bool)r["SAVE_WITHOUT_CONFIRM_ON_HIDE"];
                                }
                                if (!IsDBNull(r["WARN_ON_AUTOMATICAL_DELETE"]))
                                {
                                    pngeneral.WarnOnAutomaticalDelete = (bool)r["WARN_ON_AUTOMATICAL_DELETE"];
                                }
                                if (!IsDBNull(r["REMOVE_FROM_BIN_PERIOD"]))
                                {
                                    pngeneral.RemoveFromBinPeriod = (int)r["REMOVE_FROM_BIN_PERIOD"];
                                }
                                if (!IsDBNull(r["AUTO_SAVE"]))
                                {
                                    pngeneral.Autosave = (bool)r["AUTO_SAVE"];
                                }
                                if (!IsDBNull(r["AUTO_SAVE_PERIOD"]))
                                {
                                    pngeneral.AutosavePeriod = (int)r["AUTO_SAVE_PERIOD"];
                                }
                                if (!IsDBNull(r["SKINLESS_WIDTH"]))
                                {
                                    pngeneral.Width = (int)r["SKINLESS_WIDTH"];
                                }
                                if (!IsDBNull(r["SKINLESS_HEIGHT"]))
                                {
                                    pngeneral.Height = (int)r["SKINLESS_HEIGHT"];
                                }
                                if (!IsDBNull(r["SPELL_COLOR"]))
                                {
                                    pngeneral.SpellColor = (System.Drawing.Color)
                                            drawingConverter.ConvertFromString(null, PNStatic.CultureInvariant,
                                                (string)r["SPELL_COLOR"]);
                                }
                                if (!IsDBNull(r["USE_SKINS"]))
                                {
                                    pngeneral.UseSkins = (bool)r["USE_SKINS"];
                                }
                                if (!IsDBNull(r["SPELL_MODE"]))
                                {
                                    pngeneral.SpellMode = (int)r["SPELL_MODE"];
                                }
                                if (!IsDBNull(r["SPELL_DICT"]))
                                {
                                    pngeneral.SpellDict = (string)r["SPELL_DICT"];
                                }
                                if (!IsDBNull(r["DOCK_WIDTH"]))
                                {
                                    pngeneral.DockWidth = (int)r["DOCK_WIDTH"];
                                }
                                if (!IsDBNull(r["DOCK_HEIGHT"]))
                                {
                                    pngeneral.DockHeight = (int)r["DOCK_HEIGHT"];
                                }
                                if (!IsDBNull(r["SHOW_PRIORITY_ON_START"]))
                                {
                                    pngeneral.ShowPriorityOnStart = (bool)r["SHOW_PRIORITY_ON_START"];
                                }
                                if (!IsDBNull(r["BUTTONS_SIZE"]))
                                {
                                    pngeneral.ButtonsSize = (ToolStripButtonSize)((int)r["BUTTONS_SIZE"]);
                                }
                                if (!IsDBNull(r["AUTOMATIC_SMILIES"]))
                                {
                                    pngeneral.AutomaticSmilies = (bool)r["AUTOMATIC_SMILIES"];
                                }
                                if (!IsDBNull(r["SPACE_POINTS"]))
                                {
                                    pngeneral.SpacePoints = (int)r["SPACE_POINTS"];
                                }
                                if (!IsDBNull(r["RESTORE_AUTO"]))
                                {
                                    pngeneral.RestoreAuto = (bool)r["RESTORE_AUTO"];
                                }
                                if (!IsDBNull(r["PARAGRAPH_INDENT"]))
                                {
                                    pngeneral.ParagraphIndent = (int)r["PARAGRAPH_INDENT"];
                                }
                                if (!IsDBNull(r["AUTO_HEIGHT"]))
                                {
                                    pngeneral.AutoHeight = (bool)r["AUTO_HEIGHT"];
                                }
                                if (!IsDBNull(r["CRITICAL_ON_START"]))
                                {
                                    pngeneral.CheckCriticalOnStart = (bool)r["CRITICAL_ON_START"];
                                }
                                if (!IsDBNull(r["CRITICAL_PERIODICALLY"]))
                                {
                                    pngeneral.CheckCriticalPeriodically = (bool)r["CRITICAL_PERIODICALLY"];
                                }
                                if (!IsDBNull(r["DELETE_SHORTCUTS_ON_EXIT"]))
                                {
                                    pngeneral.DeleteShortcutsOnExit = (bool)r["DELETE_SHORTCUTS_ON_EXIT"];
                                }
                                if (!IsDBNull(r["RESTORE_SHORTCUTS_ON_START"]))
                                {
                                    pngeneral.RestoreShortcutsOnStart = (bool)r["RESTORE_SHORTCUTS_ON_START"];
                                }
                                if (!IsDBNull(r["CLOSE_ON_SHORTCUT"]))
                                {
                                    pngeneral.CloseOnShortcut = (bool)r["CLOSE_ON_SHORTCUT"];
                                }
                            }
                            else
                            {
                                sqlQuery = "INSERT INTO GENERAL_SETTINGS VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                                oData.Execute(sqlQuery);
                            }
                        }
                    }

                    PNStatic.SpTextProvider.SplashText = PNLang.Instance.GetMessageText("load_program_settings", "Loading program settings");

                    //schedule
                    if (!oData.TableExists("SCHEDULE"))
                    {
                        sqlQuery = "CREATE TABLE [SCHEDULE] ([SOUND] TEXT, [DATE_FORMAT] TEXT, [TIME_FORMAT] TEXT, [VOICE] TEXT, [ALLOW_SOUND] BOOLEAN, [TRACK_OVERDUE] BOOLEAN, [VISUAL_NOTIFY] BOOLEAN, [CENTER_SCREEN] BOOLEAN, [VOICE_VOLUME] INT, [VOICE_SPEED] INT, [VOICE_PITCH] INT)";
                        oData.Execute(sqlQuery);
                        sqlQuery = "INSERT INTO SCHEDULE VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                        oData.Execute(sqlQuery);
                    }
                    else
                    {
                        sqlQuery = "SELECT * FROM SCHEDULE";
                        using (var t = oData.FillDataTable(sqlQuery))
                        {
                            if (t.Rows.Count > 0)
                            {
                                var r = t.Rows[0];
                                var pnsc = PNStatic.Settings.Schedule;
                                if (!IsDBNull(r["SOUND"]))
                                {
                                    pnsc.Sound = (string)r["SOUND"];
                                }
                                if (!IsDBNull(r["VOICE"]))
                                {
                                    pnsc.Voice = (string)r["VOICE"];
                                }
                                if (!IsDBNull(r["ALLOW_SOUND"]))
                                {
                                    pnsc.AllowSoundAlert = (bool)r["ALLOW_SOUND"];
                                }
                                if (!IsDBNull(r["TRACK_OVERDUE"]))
                                {
                                    pnsc.TrackOverdue = (bool)r["TRACK_OVERDUE"];
                                }
                                if (!IsDBNull(r["VISUAL_NOTIFY"]))
                                {
                                    pnsc.VisualNotification = (bool)r["VISUAL_NOTIFY"];
                                }
                                if (!IsDBNull(r["CENTER_SCREEN"]))
                                {
                                    pnsc.CenterScreen = (bool)r["CENTER_SCREEN"];
                                }
                                if (!IsDBNull(r["VOICE_VOLUME"]))
                                {
                                    pnsc.VoiceVolume = (int)r["VOICE_VOLUME"];
                                }
                                if (!IsDBNull(r["VOICE_SPEED"]))
                                {
                                    pnsc.VoiceSpeed = (int)r["VOICE_SPEED"];
                                }
                                if (!IsDBNull(r["VOICE_PITCH"]))
                                {
                                    pnsc.VoicePitch = (int)r["VOICE_PITCH"];
                                }
                            }
                            else
                            {
                                sqlQuery = "INSERT INTO SCHEDULE VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                                oData.Execute(sqlQuery);
                            }
                        }
                    }
                    //behavior
                    if (!oData.TableExists("BEHAVIOR"))
                    {
                        sqlQuery = "CREATE TABLE [BEHAVIOR] ([NEW_ALWAYS_ON_TOP] BOOLEAN, [RELATIONAL_POSITION] BOOLEAN, [HIDE_COMPLETED] BOOLEAN, [BIG_ICONS_ON_CP] BOOLEAN, [DO_NOT_SHOW_IN_LIST] BOOLEAN, [KEEP_VISIBLE_ON_SHOW_DESKTOP] BOOLEAN, [DBL_CLICK_ACTION] INT, [SINGLE_CLICK_ACTION] INT, [DEFAULT_NAMING] INT, [DEFAULT_NAME_LENGHT] INT, [CONTENT_COLUMN_LENGTH] INT, [HIDE_FLUENTLY] BOOLEAN, [PLAY_SOUND_ON_HIDE] BOOLEAN, [OPACITY] REAL, [RANDOM_COLOR] BOOLEAN, [INVERT_TEXT_COLOR] BOOLEAN, [ROLL_ON_DBLCLICK] BOOLEAN, [FIT_WHEN_ROLLED] BOOLEAN, [SHOW_SEPARATE_NOTES] BOOLEAN, [PIN_CLICK_ACTION] INT, [NOTE_START_POSITION] INT, [HIDE_MAIN_WINDOW] BOOLEAN, [THEME] TEXT, [PREVENT_RESIZING] BOOLEAN, [SHOW_PANEL] BOOLEAN, [PANEL_DOCK] INT, [PANEL_AUTO_HIDE] BOOLEAN, [PANEL_REMOVE_MODE] INT, [PANEL_SWITCH_OFF_ANIMATION] BOOLEAN, [PANEL_ENTER_DELAY] INT)";
                        oData.Execute(sqlQuery);
                        sqlQuery = "INSERT INTO BEHAVIOR VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                        oData.Execute(sqlQuery);
                    }
                    else
                    {
                        using (var t = oData.GetSchema("Columns"))
                        {
                            var rows = t.Select("COLUMN_NAME = 'NOTE_START_POSITION' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [NOTE_START_POSITION] INT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'HIDE_MAIN_WINDOW' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [HIDE_MAIN_WINDOW] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'THEME' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [THEME] TEXT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'PREVENT_RESIZING' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [PREVENT_RESIZING] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'SHOW_PANEL' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [SHOW_PANEL] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'PANEL_DOCK' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [PANEL_DOCK] INT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'PANEL_AUTO_HIDE' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [PANEL_AUTO_HIDE] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'PANEL_REMOVE_MODE' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [PANEL_REMOVE_MODE] INT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'PANEL_SWITCH_OFF_ANIMATION' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [PANEL_SWITCH_OFF_ANIMATION] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'PANEL_ENTER_DELAY' AND TABLE_NAME = 'BEHAVIOR'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE BEHAVIOR ADD COLUMN [PANEL_ENTER_DELAY] INT";
                                oData.Execute(sqlQuery);
                            }
                        }
                        sqlQuery = "SELECT * FROM BEHAVIOR";
                        using (var t = oData.FillDataTable(sqlQuery))
                        {
                            if (t.Rows.Count > 0)
                            {
                                var r = t.Rows[0];
                                var pnb = PNStatic.Settings.Behavior;
                                if (!IsDBNull(r["NEW_ALWAYS_ON_TOP"]))
                                {
                                    pnb.NewNoteAlwaysOnTop = (bool)r["NEW_ALWAYS_ON_TOP"];
                                }
                                if (!IsDBNull(r["RELATIONAL_POSITION"]))
                                {
                                    pnb.RelationalPositioning = (bool)r["RELATIONAL_POSITION"];
                                }
                                if (!IsDBNull(r["HIDE_COMPLETED"]))
                                {
                                    pnb.HideCompleted = (bool)r["HIDE_COMPLETED"];
                                }
                                if (!IsDBNull(r["BIG_ICONS_ON_CP"]))
                                {
                                    pnb.BigIconsOnCP = (bool)r["BIG_ICONS_ON_CP"];
                                }
                                if (!IsDBNull(r["DO_NOT_SHOW_IN_LIST"]))
                                {
                                    pnb.DoNotShowNotesInList = (bool)r["DO_NOT_SHOW_IN_LIST"];
                                }
                                if (!IsDBNull(r["KEEP_VISIBLE_ON_SHOW_DESKTOP"]))
                                {
                                    pnb.KeepVisibleOnShowDesktop = (bool)r["KEEP_VISIBLE_ON_SHOW_DESKTOP"];
                                }
                                if (!IsDBNull(r["DBL_CLICK_ACTION"]))
                                {
                                    var index = (int) r["DBL_CLICK_ACTION"];
                                    if (index < Enum.GetValues(typeof (TrayMouseAction)).Length)
                                        pnb.DoubleClickAction = (TrayMouseAction) index;
                                }
                                if (!IsDBNull(r["SINGLE_CLICK_ACTION"]))
                                {
                                    var index = (int)r["SINGLE_CLICK_ACTION"];
                                    if (index < Enum.GetValues(typeof (TrayMouseAction)).Length)
                                        pnb.SingleClickAction = (TrayMouseAction) index;
                                }
                                if (!IsDBNull(r["DEFAULT_NAMING"]))
                                {
                                    var index = (int)r["DEFAULT_NAMING"];
                                    if (index < Enum.GetValues(typeof(DefaultNaming)).Length)
                                        pnb.DefaultNaming = (DefaultNaming)index;
                                }
                                if (!IsDBNull(r["DEFAULT_NAME_LENGHT"]))
                                {
                                    pnb.DefaultNameLength = (int)r["DEFAULT_NAME_LENGHT"];
                                }
                                if (!IsDBNull(r["CONTENT_COLUMN_LENGTH"]))
                                {
                                    pnb.ContentColumnLength = (int)r["CONTENT_COLUMN_LENGTH"];
                                }
                                if (!IsDBNull(r["HIDE_FLUENTLY"]))
                                {
                                    pnb.HideFluently = (bool)r["HIDE_FLUENTLY"];
                                }
                                if (!IsDBNull(r["PLAY_SOUND_ON_HIDE"]))
                                {
                                    pnb.PlaySoundOnHide = (bool)r["PLAY_SOUND_ON_HIDE"];
                                }
                                if (!IsDBNull(r["OPACITY"]))
                                {
                                    pnb.Opacity = (double)r["OPACITY"];
                                }
                                if (!IsDBNull(r["RANDOM_COLOR"]))
                                {
                                    pnb.RandomBackColor = (bool)r["RANDOM_COLOR"];
                                }
                                if (!IsDBNull(r["INVERT_TEXT_COLOR"]))
                                {
                                    pnb.InvertTextColor = (bool)r["INVERT_TEXT_COLOR"];
                                }
                                if (!IsDBNull(r["ROLL_ON_DBLCLICK"]))
                                {
                                    pnb.RollOnDblClick = (bool)r["ROLL_ON_DBLCLICK"];
                                }
                                if (!IsDBNull(r["FIT_WHEN_ROLLED"]))
                                {
                                    pnb.FitWhenRolled = (bool)r["FIT_WHEN_ROLLED"];
                                }
                                if (!IsDBNull(r["SHOW_SEPARATE_NOTES"]))
                                {
                                    pnb.ShowSeparateNotes = (bool)r["SHOW_SEPARATE_NOTES"];
                                }
                                if (!IsDBNull(r["PIN_CLICK_ACTION"]))
                                {
                                    var index = (int)r["PIN_CLICK_ACTION"];
                                    if (index < Enum.GetValues(typeof(PinClickAction)).Length)
                                        pnb.PinClickAction = (PinClickAction)index;
                                }
                                if (!IsDBNull(r["NOTE_START_POSITION"]))
                                {
                                    var index = (int)r["NOTE_START_POSITION"];
                                    if (index < Enum.GetValues(typeof(NoteStartPosition)).Length)
                                        pnb.StartPosition = (NoteStartPosition)index;
                                }
                                if (!IsDBNull(r["HIDE_MAIN_WINDOW"]))
                                {
                                    pnb.HideMainWindow = (bool)r["HIDE_MAIN_WINDOW"];
                                }
                                if (!IsDBNull(r["THEME"]))
                                {
                                    pnb.Theme = (string) r["THEME"];
                                }
                                else
                                {
                                    pnb.Theme = PNStrings.DEF_THEME;
                                }
                                if (!IsDBNull(r["PREVENT_RESIZING"]))
                                {
                                    pnb.PreventAutomaticResizing = (bool)r["PREVENT_RESIZING"];
                                }
                                if (!IsDBNull(r["SHOW_PANEL"]))
                                {
                                    pnb.ShowNotesPanel = (bool)r["SHOW_PANEL"];
                                }
                                if (!IsDBNull(r["PANEL_DOCK"]))
                                {
                                    pnb.NotesPanelOrientation = (NotesPanelOrientation)r["PANEL_DOCK"];
                                }
                                if (!IsDBNull(r["PANEL_AUTO_HIDE"]))
                                {
                                    pnb.PanelAutoHide = (bool)r["PANEL_AUTO_HIDE"];
                                }
                                if (!IsDBNull(r["PANEL_REMOVE_MODE"]))
                                {
                                    pnb.PanelRemoveMode = (PanelRemoveMode)r["PANEL_REMOVE_MODE"];
                                }
                                if (!IsDBNull(r["PANEL_SWITCH_OFF_ANIMATION"]))
                                {
                                    pnb.PanelSwitchOffAnimation = (bool)r["PANEL_SWITCH_OFF_ANIMATION"];
                                }
                                if (!IsDBNull(r["PANEL_ENTER_DELAY"]))
                                {
                                    pnb.PanelEnterDelay = (int)r["PANEL_ENTER_DELAY"];
                                }
                            }
                            else
                            {
                                sqlQuery = "INSERT INTO BEHAVIOR VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                                oData.Execute(sqlQuery);
                            }
                        }
                    }
                    //protection
                    if (!oData.TableExists("PROTECTION"))
                    {
                        sqlQuery = "CREATE TABLE [PROTECTION] ([STORE_AS_ENCRYPTED] BOOLEAN, [HIDE_TRAY_ICON] BOOLEAN, [BACKUP_BEFORE_SAVING] BOOLEAN, [SILENT_FULL_BACKUP] BOOLEAN, [BACKUP_DEEPNESS] INT, [DO_NOT_SHOW_CONTENT] BOOLEAN, [INCLUDE_BIN_IN_SYNC] BOOLEAN, [PASSWORD_STRING] TEXT, [FULL_BACKUP_DAYS] TEXT, [FULL_BACKUP_TIME] TEXT, [FULL_BACKUP_DATE] TEXT, [PROMPT_PASSWORD] BOOLEAN)";
                        oData.Execute(sqlQuery);
                        sqlQuery = "INSERT INTO PROTECTION VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                        oData.Execute(sqlQuery);
                    }
                    else
                    {
                        using (var t = oData.GetSchema("Columns"))
                        {
                            var rows = t.Select("COLUMN_NAME = 'FULL_BACKUP_DAYS' AND TABLE_NAME = 'PROTECTION'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE PROTECTION ADD COLUMN [FULL_BACKUP_DAYS] TEXT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'FULL_BACKUP_TIME' AND TABLE_NAME = 'PROTECTION'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE PROTECTION ADD COLUMN [FULL_BACKUP_TIME] TEXT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'FULL_BACKUP_DATE' AND TABLE_NAME = 'PROTECTION'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE PROTECTION ADD COLUMN [FULL_BACKUP_DATE] TEXT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'PROMPT_PASSWORD' AND TABLE_NAME = 'PROTECTION'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE PROTECTION ADD COLUMN [PROMPT_PASSWORD] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                        }
                        sqlQuery = "SELECT * FROM PROTECTION";
                        using (var t = oData.FillDataTable(sqlQuery))
                        {
                            if (t.Rows.Count > 0)
                            {
                                var r = t.Rows[0];
                                var pnp = PNStatic.Settings.Protection;
                                if (!IsDBNull(r["STORE_AS_ENCRYPTED"]))
                                {
                                    pnp.StoreAsEncrypted = (bool)r["STORE_AS_ENCRYPTED"];
                                }
                                if (!IsDBNull(r["HIDE_TRAY_ICON"]))
                                {
                                    pnp.HideTrayIcon = (bool)r["HIDE_TRAY_ICON"];
                                }
                                if (!IsDBNull(r["BACKUP_BEFORE_SAVING"]))
                                {
                                    pnp.BackupBeforeSaving = (bool)r["BACKUP_BEFORE_SAVING"];
                                }
                                if (!IsDBNull(r["SILENT_FULL_BACKUP"]))
                                {
                                    pnp.SilentFullBackup = (bool)r["SILENT_FULL_BACKUP"];
                                }
                                if (!IsDBNull(r["BACKUP_DEEPNESS"]))
                                {
                                    pnp.BackupDeepness = (int)r["BACKUP_DEEPNESS"];
                                }
                                if (!IsDBNull(r["DO_NOT_SHOW_CONTENT"]))
                                {
                                    pnp.DontShowContent = (bool)r["DO_NOT_SHOW_CONTENT"];
                                }
                                if (!IsDBNull(r["INCLUDE_BIN_IN_SYNC"]))
                                {
                                    pnp.IncludeBinInSync = (bool)r["INCLUDE_BIN_IN_SYNC"];
                                }
                                if (!IsDBNull(r["PASSWORD_STRING"]))
                                {
                                    pnp.PasswordString = (string)r["PASSWORD_STRING"];
                                }
                                if (!IsDBNull(r["FULL_BACKUP_DAYS"]))
                                {
                                    var temp = Convert.ToString(r["FULL_BACKUP_DAYS"]);
                                    if (!string.IsNullOrEmpty(temp))
                                    {
                                        var days = temp.Split(',');
                                        foreach (var d in days)
                                        {
                                            pnp.FullBackupDays.Add((DayOfWeek)Convert.ToInt32(d));
                                        }
                                    }
                                }
                                if (!IsDBNull(r["FULL_BACKUP_TIME"]))
                                {
                                    pnp.FullBackupTime = DateTime.Parse((string)r["FULL_BACKUP_TIME"], PNStatic.CultureInvariant);
                                }
                                if (!IsDBNull(r["FULL_BACKUP_DATE"]))
                                {
                                    pnp.FullBackupDate = DateTime.Parse((string)r["FULL_BACKUP_DATE"], PNStatic.CultureInvariant);
                                }
                                if (!IsDBNull(r["PROMPT_PASSWORD"]))
                                {
                                    pnp.PromptForPassword = (bool)r["PROMPT_PASSWORD"];
                                }
                            }
                            else
                            {
                                sqlQuery = "INSERT INTO PROTECTION VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                                oData.Execute(sqlQuery);
                            }
                        }
                    }
                    //diary
                    if (!oData.TableExists("DIARY"))
                    {
                        sqlQuery = "CREATE TABLE [DIARY] ([CUSTOM_SETTINGS] BOOLEAN, [ADD_WEEKDAY] BOOLEAN, [FULL_WEEKDAY_NAME] BOOLEAN, [WEEKDAY_AT_THE_END] BOOLEAN, [DO_NOT_SHOW_PREVIOUS] BOOLEAN, [ASC_ORDER] BOOLEAN, [NUMBER_OF_PAGES] INT, [DATE_FORMAT] TEXT)";
                        oData.Execute(sqlQuery);
                        sqlQuery = "INSERT INTO DIARY VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                        oData.Execute(sqlQuery);
                    }
                    else
                    {
                        sqlQuery = "SELECT * FROM DIARY";
                        using (var t = oData.FillDataTable(sqlQuery))
                        {
                            if (t.Rows.Count > 0)
                            {
                                var r = t.Rows[0];
                                var pndr = PNStatic.Settings.Diary;
                                if (!IsDBNull(r["CUSTOM_SETTINGS"]))
                                {
                                    pndr.CustomSettings = (bool)r["CUSTOM_SETTINGS"];
                                }
                                if (!IsDBNull(r["ADD_WEEKDAY"]))
                                {
                                    pndr.AddWeekday = (bool)r["ADD_WEEKDAY"];
                                }
                                if (!IsDBNull(r["FULL_WEEKDAY_NAME"]))
                                {
                                    pndr.FullWeekdayName = (bool)r["FULL_WEEKDAY_NAME"];
                                }
                                if (!IsDBNull(r["WEEKDAY_AT_THE_END"]))
                                {
                                    pndr.WeekdayAtTheEnd = (bool)r["WEEKDAY_AT_THE_END"];
                                }
                                if (!IsDBNull(r["DO_NOT_SHOW_PREVIOUS"]))
                                {
                                    pndr.DoNotShowPrevious = (bool)r["DO_NOT_SHOW_PREVIOUS"];
                                }
                                if (!IsDBNull(r["ASC_ORDER"]))
                                {
                                    pndr.AscendingOrder = (bool)r["ASC_ORDER"];
                                }
                                if (!IsDBNull(r["NUMBER_OF_PAGES"]))
                                {
                                    pndr.NumberOfPages = (int)r["NUMBER_OF_PAGES"];
                                }
                                if (!IsDBNull(r["DATE_FORMAT"]))
                                {
                                    pndr.DateFormat = (string)r["DATE_FORMAT"];
                                }
                            }
                            else
                            {
                                sqlQuery = "INSERT INTO DIARY VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                                oData.Execute(sqlQuery);
                            }
                        }
                    }
                    //network
                    if (!oData.TableExists("NETWORK"))
                    {
                        sqlQuery = "CREATE TABLE [NETWORK] ([INCLUDE_BIN_IN_SYNC] BOOLEAN, [SYNC_ON_START] BOOLEAN, [SAVE_BEFORE_SYNC] BOOLEAN, [ENABLE_EXCHANGE] BOOLEAN, [SAVE_BEFORE_SEND] BOOLEAN, [NO_NOTIFY_ON_ARRIVE] BOOLEAN, [SHOW_RECEIVED_ON_CLICK] BOOLEAN, [SHOW_INCOMING_ON_CLICK] BOOLEAN, [NO_SOUND_ON_ARRIVE] BOOLEAN, [NO_NOTIFY_ON_SEND] BOOLEAN, [SHOW_AFTER_ARRIVE] BOOLEAN, [HIDE_AFTER_SEND] BOOLEAN, [NO_CONTACTS_IN_CONTEXT_MENU] BOOLEAN, [EXCHANGE_PORT] INT, [POST_COUNT] INT, [ALLOW_PING] BOOLEAN, [RECEIVED_ON_TOP] BOOLEAN)";
                        oData.Execute(sqlQuery);
                        sqlQuery = "INSERT INTO NETWORK VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                        oData.Execute(sqlQuery);
                    }
                    else
                    {
                        using (var t = oData.GetSchema("Columns"))
                        {
                            var rows = t.Select("COLUMN_NAME = 'POST_COUNT' AND TABLE_NAME = 'NETWORK'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE NETWORK ADD COLUMN [POST_COUNT] INT";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'ALLOW_PING' AND TABLE_NAME = 'NETWORK'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE NETWORK ADD COLUMN [ALLOW_PING] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                            rows = t.Select("COLUMN_NAME = 'RECEIVED_ON_TOP' AND TABLE_NAME = 'NETWORK'");
                            if (rows.Length == 0)
                            {
                                sqlQuery = "ALTER TABLE NETWORK ADD COLUMN [RECEIVED_ON_TOP] BOOLEAN";
                                oData.Execute(sqlQuery);
                            }
                        }
                        sqlQuery = "SELECT * FROM NETWORK";
                        using (var t = oData.FillDataTable(sqlQuery))
                        {
                            if (t.Rows.Count > 0)
                            {
                                var r = t.Rows[0];
                                var pnw = PNStatic.Settings.Network;
                                if (!IsDBNull(r["INCLUDE_BIN_IN_SYNC"]))
                                {
                                    pnw.IncludeBinInSync = (bool)r["INCLUDE_BIN_IN_SYNC"];
                                }
                                if (!IsDBNull(r["SYNC_ON_START"]))
                                {
                                    pnw.SyncOnStart = (bool)r["SYNC_ON_START"];
                                }
                                if (!IsDBNull(r["SAVE_BEFORE_SYNC"]))
                                {
                                    pnw.SaveBeforeSync = (bool)r["SAVE_BEFORE_SYNC"];
                                }
                                if (!IsDBNull(r["ENABLE_EXCHANGE"]))
                                {
                                    pnw.EnableExchange = (bool)r["ENABLE_EXCHANGE"];
                                }
                                if (!IsDBNull(r["SAVE_BEFORE_SEND"]))
                                {
                                    pnw.SaveBeforeSending = (bool)r["SAVE_BEFORE_SEND"];
                                }
                                if (!IsDBNull(r["NO_NOTIFY_ON_ARRIVE"]))
                                {
                                    pnw.NoNotificationOnArrive = (bool)r["NO_NOTIFY_ON_ARRIVE"];
                                }
                                if (!IsDBNull(r["SHOW_RECEIVED_ON_CLICK"]))
                                {
                                    pnw.ShowReceivedOnClick = (bool)r["SHOW_RECEIVED_ON_CLICK"];
                                }
                                if (!IsDBNull(r["SHOW_INCOMING_ON_CLICK"]))
                                {
                                    pnw.ShowIncomingOnClick = (bool)r["SHOW_INCOMING_ON_CLICK"];
                                }
                                if (!IsDBNull(r["NO_SOUND_ON_ARRIVE"]))
                                {
                                    pnw.NoSoundOnArrive = (bool)r["NO_SOUND_ON_ARRIVE"];
                                }
                                if (!IsDBNull(r["NO_NOTIFY_ON_SEND"]))
                                {
                                    pnw.NoNotificationOnSend = (bool)r["NO_NOTIFY_ON_SEND"];
                                }
                                if (!IsDBNull(r["SHOW_AFTER_ARRIVE"]))
                                {
                                    pnw.ShowAfterArrive = (bool)r["SHOW_AFTER_ARRIVE"];
                                }
                                if (!IsDBNull(r["HIDE_AFTER_SEND"]))
                                {
                                    pnw.HideAfterSending = (bool)r["HIDE_AFTER_SEND"];
                                }
                                if (!IsDBNull(r["NO_CONTACTS_IN_CONTEXT_MENU"]))
                                {
                                    pnw.NoContactsInContextMenu = (bool)r["NO_CONTACTS_IN_CONTEXT_MENU"];
                                }
                                if (!IsDBNull(r["EXCHANGE_PORT"]))
                                {
                                    pnw.ExchangePort = (int)r["EXCHANGE_PORT"];
                                }
                                if (!IsDBNull(r["POST_COUNT"]))
                                {
                                    pnw.PostCount = (int)r["POST_COUNT"];
                                }
                                if (!IsDBNull(r["ALLOW_PING"]))
                                {
                                    pnw.AllowPing = (bool)r["ALLOW_PING"];
                                }
                                if (!IsDBNull(r["RECEIVED_ON_TOP"]))
                                {
                                    pnw.ReceivedOnTop = (bool)r["RECEIVED_ON_TOP"];
                                }
                            }
                            else
                            {
                                sqlQuery = "INSERT INTO NETWORK VALUES(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
                                oData.Execute(sqlQuery);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
            }
        }
Ejemplo n.º 34
0
        private static Color DetectBestColor(Bitmap bmp)
        {
            var colorThief = new ColorThief();
            var colors     = colorThief.GetPalette(bmp, 8);

            var pluginColors = new List <PluginColor>();

            var maxPopulation = (from pluginColor in colors select pluginColor.Population).Max();

            foreach (var color in colors)
            {
                var    col = ColorTranslator.FromHtml(color.Color.ToHexString());
                var    populationWeight = 0.5;
                var    saturationWeight = (float)Math.Tanh(col.GetSaturation());
                double darkWeight;

                var populationPercent = (double)color.Population / maxPopulation;

                if (populationPercent > 0.3)
                {
                    populationWeight = 0.3;
                }

                if (populationPercent < 0.1 && populationPercent > 0.01)
                {
                    populationWeight = 0.8;
                }

                if (populationPercent <= 0.01)
                {
                    populationWeight = 0.2;
                }

                if (color.IsDark)
                {
                    darkWeight = 1;
                }
                else
                {
                    darkWeight = 0.3;
                }

                if (col.GetBrightness() > 0.5)
                {
                    darkWeight = 0;
                }


                var weight = populationWeight + darkWeight + saturationWeight;

                pluginColors.Add(new PluginColor
                {
                    ColorCode = color.Color.ToHexString(),
                    Weight    = weight
                });
            }


            var orderedColors = (from pluginColor in pluginColors
                                 orderby pluginColor.Weight descending
                                 select pluginColor).ToList();


            var bestColor = orderedColors.FirstOrDefault();

            var resultColor = NiResourceColor.GetRandomColor();

            if (bestColor == null)
            {
                return(resultColor);
            }

            var colorCode = bestColor.ColorCode;

            var convertedColor = ColorConverter.ConvertFromString(colorCode);

            if (convertedColor != null)
            {
                resultColor = (Color)convertedColor;
            }

            return(resultColor);
        }
Ejemplo n.º 35
0
        private Dictionary<int, int> importGroups()
        {
            try
            {
                var dict = new Dictionary<int, int>();
                var size = 1024;

                string iniPath = txtIniPath.Text.Trim();
                // get all notes ids
                string buffer = new string(' ', size);
                while (PNInterop.GetPrivateProfileString(null, null, null, buffer, size, iniPath) == size - 2)
                {
                    // loop until sufficient buffer size
                    size *= 2;
                    buffer = new string(' ', size);
                }
                // section names are delimeted by '\0' character with additional '\0' character at the end
                var names = buffer.ToString(CultureInfo.InvariantCulture).Split('\0');
                var groupSection = names.FirstOrDefault(s => s == "groups");
                if (groupSection == null) return null;
                // get ids of all groups under section
                size = 1024;
                buffer = new string(' ', size);
                while (PNInterop.GetPrivateProfileString(groupSection, null, null, buffer, size, iniPath) == size - 2)
                {
                    // loop until sufficient buffer size
                    size *= 2;
                    buffer = new string(' ', size);
                }
                names =
                    buffer.ToString(CultureInfo.InvariantCulture)
                          .Split('\0')
                          .Where(s => s.Trim().Length > 0 && s.Trim() != "0")
                          .ToArray();
                var png = new PNGROUP();
                var crc = new ColorConverter();
                var crd = new System.Drawing.ColorConverter();
                foreach (var id in names)
                {
                    int structSize = Marshal.SizeOf(typeof(PNGROUP));
                    int intSize = Marshal.SizeOf(typeof(int));
                    int boolSize = Marshal.SizeOf(typeof(bool));
                    int hkSize = Marshal.SizeOf(typeof(HK_TYPE));
                    png = PNInterop.ReadINIStructure(iniPath, "groups", id, png, structSize);
                    if (png.Equals(default(PNGROUP)))
                    {
                        structSize -= (intSize * 3 + boolSize * 4 + 2 * 64);
                        png = PNInterop.ReadINIStructure(iniPath, "groups", id, png, structSize);
                        if (png.Equals(default(PNGROUP)))
                        {
                            structSize -= 2 * 256;
                            png = PNInterop.ReadINIStructure(iniPath, "groups", id, png, structSize);
                            if (png.Equals(default(PNGROUP)))
                            {
                                structSize -= hkSize * 2;
                                png = PNInterop.ReadINIStructure(iniPath, "groups", id, png, structSize);
                                if (!png.Equals(default(PNGROUP)))
                                {
                                    png.customCRCaption = png.customCRFont = png.customCRWindow = png.customSkin = false;
                                    png.szSkin = "";
                                    png.szLock = "";
                                    png.hotKeyHide = png.hotKeyShow = default(HK_TYPE);
                                }
                            }
                            else
                            {
                                png.customCRCaption = png.customCRFont = png.customCRWindow = png.customSkin = false;
                                png.szSkin = "";
                                png.szLock = "";
                            }
                        }
                        else
                        {
                            png.customCRCaption = png.customCRFont = png.customCRWindow = png.customSkin = false;
                            png.szSkin = "";
                        }
                    }
                    if (png.Equals(default(PNGROUP))) return null;

                    var pg = new PNGroup();
                    var idNew = PNData.GetNewGroupID();
                    var idOld = png.id;
                    pg.Name = png.szName;
                    pg.ID = idNew;
                    pg.ParentID = -1;
                    if (png.customCRWindow)
                    {
                        var fromString = crc.ConvertFromString(null, PNStatic.CultureInvariant, PNStatic.FromIntToColorString(png.crWindow));
                        if (fromString != null)
                            pg.Skinless.BackColor = (Color)fromString;
                    }
                    if (png.customCRCaption)
                    {
                        var fromString = crc.ConvertFromString(null, PNStatic.CultureInvariant, PNStatic.FromIntToColorString(png.crCaption));
                        if (fromString != null)
                            pg.Skinless.CaptionColor = (Color)fromString;
                    }
                    if (png.customCRFont)
                    {
                        var fromString = crd.ConvertFromString(null, PNStatic.CultureInvariant, PNStatic.FromIntToDrawinfColorString(png.crFont));
                        if (fromString != null)
                            pg.FontColor = (System.Drawing.Color)fromString;
                    }
                    if (png.customSkin)
                    {
                        pg.Skin.SkinName = png.szSkin;
                        var path = Path.Combine(PNPaths.Instance.SkinsDir, pg.Skin.SkinName + PNStrings.SKIN_EXTENSION);
                        if (File.Exists(path))
                        {
                            PNSkinsOperations.LoadSkin(path, pg.Skin);
                        }
                    }
                    pg.Image = TryFindResource("gr") as BitmapImage;
                    pg.IsDefaultImage = true;
                    var parent = PNStatic.Groups.GetGroupByID((int)SpecialGroups.AllGroups);
                    if (parent == null) continue;
                    parent.Subgroups.Add(pg);
                    PNData.InsertNewGroup(pg);
                    dict.Add(idOld, idNew);
                }
                return dict;
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
                return null;
            }
        }
Ejemplo n.º 36
0
        private static void Elapsed()
        {
            if (theme)
            {
                Application.Current.Resources["BackgroundBrush"] = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#333333"));
                Application.Current.Resources["TextColor"]       = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F5F5F5"));
                Application.Current.Resources["LighterBG"]       = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#444444"));
                Application.Current.Resources["LightestBG"]      = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#555555"));
                Application.Current.Resources["TransparentBG"]   = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#CC202020"));
                LightIcons();
                theme = false;
            }
            else
            {
                Application.Current.Resources["BackgroundBrush"] = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DDDDDD"));
                Application.Current.Resources["TextColor"]       = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#202020"));
                Application.Current.Resources["LighterBG"]       = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#CCCCCC"));
                Application.Current.Resources["LightestBG"]      = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#BBBBBB"));
                Application.Current.Resources["TransparentBG"]   = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#CCBBBBBB"));

                DarkIcons();
                theme = true;
            }
        }
Ejemplo n.º 37
0
        protected override Bitmap GetThumbnailImage(uint width) // Implemented abstract function in the base class
        {
            MemoryStream memStream = new MemoryStream();



            Thread thread = new Thread(() =>
            {
                try
                {
                    string color              = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Marlin3DprinterTool", "Color", "Blue");
                    var stlReader             = new StLReader();
                    stlReader.DefaultMaterial = new DiffuseMaterial(
                        new SolidColorBrush((Color)ColorConverter.ConvertFromString(color)));



                    //stlReader.DefaultMaterial = new DiffuseMaterial(new SolidColorBrush(Colors.Blue));
                    var model = stlReader.Read(SelectedItemStream);



                    //...create UI controls...

                    Viewport3D viewport = new Viewport3D();


                    // viewport.Measure(new System.Windows.Size(320, 240));
                    viewport.Measure(new Size(width, width));
                    // viewport.Arrange(new Rect(0, 0, 320, 240));
                    viewport.Arrange(new Rect(0, 0, width, width));

                    ModelVisual3D root = new ModelVisual3D();

                    viewport.Children.Add(root);


                    var camera               = new PerspectiveCamera();
                    camera.Position          = new Point3D(2, 16, 20);
                    camera.LookDirection     = new Vector3D(-2, -16, -20);
                    camera.UpDirection       = new Vector3D(0, 0, 1);
                    camera.FieldOfView       = 45;
                    camera.NearPlaneDistance = 0.1;
                    camera.FarPlaneDistance  = double.PositiveInfinity;
                    viewport.Camera          = camera;


                    root.Children.Add(new DefaultLights());

                    root.Content = model;



                    camera.ZoomExtents(viewport);

                    Brush background        = new SolidColorBrush(Colors.Transparent);
                    BitmapExporter exporter = new BitmapExporter
                    {
                        OversamplingMultiplier = 2,
                        Background             = background
                    };


                    exporter.Export(viewport, memStream);
                }
                catch (Exception treadException)
                {
                }
            });


            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();


            Bitmap thumbnailBitmap = (Bitmap)Image.FromStream(memStream);

            return(thumbnailBitmap);
        }
Ejemplo n.º 38
0
        /// <summary>
        /// This function is called when the file containing
        /// path and view info is updated.
        /// </summary>
        /// <param name="filename">unused.</param>
        private void onFileChange(string filename)
        {
            #if LOGGING
            logEvent( "* Tracked file Change" );
            #endif

            try
            {
                using (FileStream fs = File.OpenRead(filename))
                using (TextReader reader = new StreamReader(fs))
                {
                    string line = "";

                    try { line = reader.ReadLine(); }
                    catch (IOException)
                    {   /* can happen, not a problem in this case. */
            #if LOGGING
                        logEvent("|-> IOException while reading wake file");
            #endif
                        return;
                    }
                    catch (ArgumentOutOfRangeException)
                    { /* we're searching for a PID and a path, nothing big
                   * Ignore if to big */
            #if LOGGING
                        logEvent("|-> Argument out of range, while reading wake file");
            #endif
                        Application.Current.Shutdown();
                    }

            #if LOGGING
                logEvent( "- Loading : " + line );
            #endif

                    switch (line)
                    {
                        case "quit":
                            // RESTORE SOMETHING
                            if (currentState == TrackingState.Maximized)
                                unMaximize();
                            Application.Current.Shutdown();
                            break;

                        default:
                            string[] infos = line.Split('?');
                            string file = infos[infos.Length - 1];

                            if (!File.Exists(file))
                                return;

                            BitmapImage newOverview = new BitmapImage();

                            try
                            {

                                newOverview.BeginInit();
                                newOverview.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                                newOverview.CacheOption = BitmapCacheOption.OnLoad;
                                newOverview.UriSource = new Uri(file);
                                newOverview.EndInit();

                                newOverview.Freeze();

                                if (newOverview.Height > this.ActualHeight)
                                    pictureViewer.Stretch = Stretch.Fill;
                                else
                                    pictureViewer.Stretch = Stretch.None;
                                pictureViewer.Source = newOverview;
                            }
                            catch (UriFormatException)
                            {
            #if LOGGING
                            logEvent("|-> UriFormatException");
            #endif
                                /* Bad image... putting empty image instead */
                                pictureViewer.Source = null;
                            }
                            catch (Exception)
                            {   /* It's WPF nasty way to tell us that
                             * the file is broken...
                             * normally a TargetInvocationException but
                             * it's not caught in a specific catch for a
                             * reason that is beyond me.
                             */
                                pictureViewer.Source = null;
                            }

                            try
                            {
                                double viewHeight = Math.Min(this.Height, newOverview.Height);
                                double realTop = ((double)int.Parse(infos[0])) / pictureViewer.Source.Height * viewHeight;
                                double realBottom = ((double)int.Parse(infos[1])) / pictureViewer.Source.Height * viewHeight;

                                ViewRectTop = realTop;
                                ViewRectHeight = realBottom - realTop;

                                TypeConverter cConvert = new ColorConverter();
                                Background = new SolidColorBrush((Color)cConvert.ConvertFromString(infos[2]));
                            }
                            catch (System.Exception)
                            {   /* don't care about parsing errors for this one */
            #if LOGGING
                            logEvent("|-> Exception while parsing INT");
            #endif
                                ViewRectTop = 0.0;
                                ViewRectHeight = 0.0;
                            }

                            InvalidateVisual();
                            break;

                    }
                }
            }
            catch (Exception) { Application.Current.Shutdown(); }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Creates the bitmap data for the models in the character category
        /// </summary>
        /// <remarks>
        /// Because the original textures use channel packing, this method gets the pixel data of each texture
        /// and then recombines them to create the unpacked textures to use in the 3D model.
        /// <see cref="http://wiki.polycount.com/wiki/ChannelPacking"/>
        /// </remarks>
        /// <param name="normalTexData">The texture data of the normal map</param>
        /// <param name="diffuseTexData">The texture data of the diffuse map</param>
        /// <param name="maskTexData">The texture data of the mask map</param>
        /// <param name="specularTexData">The texture data of the normal map</param>
        /// <returns>An array of bitmaps to be used on the model</returns>
        public static BitmapSource[] MakeCharacterMaps(TEXData normalTexData, TEXData diffuseTexData, TEXData maskTexData, TEXData specularTexData, string itemName, string path)
        {
            int   height       = normalTexData.Height;
            int   width        = normalTexData.Width;
            int   tSize        = height * width;
            var   normalBitmap = normalTexData.BMPSouceAlpha;
            Color charaColor;

            if (path.Contains("/body/b"))
            {
                charaColor = (Color)ColorConverter.ConvertFromString(Properties.Settings.Default.Skin_Color);
            }
            else if (path.Contains("/hair/h"))
            {
                charaColor = (Color)ColorConverter.ConvertFromString(Properties.Settings.Default.Hair_Color);
            }
            else if (path.Contains("/face/f"))
            {
                if (path.Contains("_etc_"))
                {
                    charaColor = (Color)ColorConverter.ConvertFromString(Properties.Settings.Default.Etc_Color);
                }
                else if (path.Contains("_iri_"))
                {
                    charaColor = (Color)ColorConverter.ConvertFromString(Properties.Settings.Default.Iris_Color);
                }
                else
                {
                    charaColor = (Color)ColorConverter.ConvertFromString(Properties.Settings.Default.Skin_Color);
                }
            }
            else if (path.Contains("tail/t"))
            {
                if (!path.Contains("c1401") && !path.Contains("c1301"))
                {
                    charaColor = (Color)ColorConverter.ConvertFromString(Properties.Settings.Default.Hair_Color);
                }
                else
                {
                    charaColor = Color.FromArgb(255, 255, 255, 255);
                }
            }
            else
            {
                charaColor = Color.FromArgb(255, 96, 57, 19);
            }

            if (diffuseTexData != null && (diffuseTexData.Height * diffuseTexData.Width) > tSize)
            {
                height = diffuseTexData.Height;
                width  = diffuseTexData.Width;
                tSize  = height * width;
            }

            if (maskTexData != null && (maskTexData.Height * maskTexData.Width) > tSize)
            {
                height = maskTexData.Height;
                width  = maskTexData.Width;
                tSize  = height * width;
            }

            if (specularTexData != null && (specularTexData.Height * specularTexData.Width) > tSize)
            {
                height = specularTexData.Height;
                width  = specularTexData.Width;
                tSize  = height * width;
            }

            byte[] maskPixels     = null;
            byte[] specularPixels = null;
            byte[] normalPixels   = null;
            byte[] diffusePixels  = null;

            BitmapSource[] texBitmaps = new BitmapSource[4];

            if (maskTexData != null)
            {
                if (tSize > (maskTexData.Height * maskTexData.Width))
                {
                    var resized = CreateResizedImage(maskTexData.BMPSouceAlpha, width, height);
                    maskPixels = GetBytesFromBitmapSource((BitmapSource)resized);
                }
                else
                {
                    maskPixels = GetBytesFromBitmapSource(maskTexData.BMPSouceAlpha);
                }
            }

            if (diffuseTexData != null)
            {
                try
                {
                    if (tSize > (diffuseTexData.Height * diffuseTexData.Width))
                    {
                        var resized = CreateResizedImage(diffuseTexData.BMPSouceAlpha, width, height);
                        diffusePixels = GetBytesFromBitmapSource((BitmapSource)resized);
                    }
                    else
                    {
                        diffusePixels = GetBytesFromBitmapSource(diffuseTexData.BMPSouceAlpha);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                }
            }

            if (specularTexData != null)
            {
                try
                {
                    if (tSize > (specularTexData.Height * specularTexData.Width))
                    {
                        var resized = CreateResizedImage(specularTexData.BMPSouceAlpha, width, height);
                        specularPixels = GetBytesFromBitmapSource((BitmapSource)resized);
                    }
                    else
                    {
                        specularPixels = GetBytesFromBitmapSource(specularTexData.BMPSouceAlpha);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                }
            }

            if (normalTexData != null)
            {
                if (tSize > (normalTexData.Height * normalTexData.Width))
                {
                    var resized = CreateResizedImage(normalTexData.BMPSouceAlpha, width, height);
                    normalBitmap = (BitmapSource)resized;
                    normalPixels = GetBytesFromBitmapSource((BitmapSource)resized);
                }
                else
                {
                    normalPixels = GetBytesFromBitmapSource(normalTexData.BMPSouceAlpha);
                }
            }

            List <byte> diffuseMap  = new List <byte>();
            List <byte> specularMap = new List <byte>();
            List <byte> alphaMap    = new List <byte>();

            BitmapSource bitmapSource;

            System.Drawing.Color diffuseColor;
            System.Drawing.Color specularColor;
            System.Drawing.Color alphaColor;

            int stride = (int)normalBitmap.Width * (32 / 8);

            var scale = 1;

            if (width >= 4096 || height >= 4096)
            {
                scale = 4;
            }
            else if (width >= 2048 || height >= 2048)
            {
                scale = 2;
            }

            var nWidth  = width / scale;
            var nHeight = height / scale;

            if (diffuseTexData == null)
            {
                for (int i = 3; i < normalPixels.Length; i += 4)
                {
                    int alpha = normalPixels[i];

                    diffuseColor = System.Drawing.Color.FromArgb(alpha, (int)((charaColor.R / 255f) * specularPixels[i - 1]), (int)((charaColor.G / 255f) * specularPixels[i - 1]), (int)((charaColor.B / 255f) * specularPixels[i - 1]));

                    specularColor = System.Drawing.Color.FromArgb(255, (int)(specularPixels[i - 2] * 0.1), (int)(specularPixels[i - 2] * 0.1), (int)(specularPixels[i - 2] * 0.1));

                    alphaColor = System.Drawing.Color.FromArgb(255, alpha, alpha, alpha);

                    diffuseMap.AddRange(BitConverter.GetBytes(diffuseColor.ToArgb()));
                    specularMap.AddRange(BitConverter.GetBytes(specularColor.ToArgb()));
                    alphaMap.AddRange(BitConverter.GetBytes(alphaColor.ToArgb()));
                }

                bitmapSource  = BitmapSource.Create(width, height, normalBitmap.DpiX, normalBitmap.DpiY, PixelFormats.Bgra32, null, diffuseMap.ToArray(), stride);
                texBitmaps[0] = (BitmapSource)CreateResizedImage(bitmapSource, nWidth, nHeight);
            }
            else
            {
                for (int i = 3; i < normalPixels.Length; i += 4)
                {
                    int alpha = normalPixels[i - 3];

                    diffuseColor = System.Drawing.Color.FromArgb(alpha, (int)((charaColor.R / 255f) * diffusePixels[i - 1]), (int)((charaColor.G / 255f) * diffusePixels[i - 2]), (int)((charaColor.B / 255f) * diffusePixels[i - 3]));
                    diffuseMap.AddRange(BitConverter.GetBytes(diffuseColor.ToArgb()));

                    specularColor = System.Drawing.Color.FromArgb(255, (int)(specularPixels[i - 2] * 0.1), (int)(specularPixels[i - 2] * 0.1), (int)(specularPixels[i - 2] * 0.1));
                    specularMap.AddRange(BitConverter.GetBytes(specularColor.ToArgb()));

                    alphaColor = System.Drawing.Color.FromArgb(255, alpha, alpha, alpha);
                    alphaMap.AddRange(BitConverter.GetBytes(alphaColor.ToArgb()));
                }

                bitmapSource  = BitmapSource.Create(width, height, normalBitmap.DpiX, normalBitmap.DpiY, PixelFormats.Bgra32, null, diffuseMap.ToArray(), stride);
                texBitmaps[0] = (BitmapSource)CreateResizedImage(bitmapSource, nWidth, nHeight);
            }

            bitmapSource  = BitmapSource.Create(width, height, normalBitmap.DpiX, normalBitmap.DpiY, PixelFormats.Bgra32, null, specularMap.ToArray(), stride);
            texBitmaps[1] = (BitmapSource)CreateResizedImage(bitmapSource, nWidth, nHeight);

            texBitmaps[2] = (BitmapSource)CreateResizedImage(normalTexData.BMPSouceNoAlpha, nWidth, nHeight);

            bitmapSource  = BitmapSource.Create(width, height, normalBitmap.DpiX, normalBitmap.DpiY, PixelFormats.Bgra32, null, alphaMap.ToArray(), stride);
            texBitmaps[3] = (BitmapSource)CreateResizedImage(bitmapSource, nWidth, nHeight);

            foreach (var tb in texBitmaps)
            {
                tb.Freeze();
            }

            return(texBitmaps);
        }
Ejemplo n.º 40
0
        private void fillGroup(PNGroup gr, DataRow r)
        {
            try
            {
                var c = new ColorConverter();
                var wfc = new WPFFontConverter();
                var lfc = new LogFontConverter();
                var dcc = new System.Drawing.ColorConverter();

                gr.ID = (int)r["GROUP_ID"];
                gr.ParentID = (int)r["PARENT_ID"];
                gr.Name = (string)r["GROUP_NAME"];
                gr.PasswordString = (string)r["PASSWORD_STRING"];
                gr.IsDefaultImage = (bool)r["IS_DEFAULT_IMAGE"];
                if (!PNData.IsDBNull(r["ICON"]))
                {
                    var base64String = (string)r["ICON"];
                    if (!base64String.EndsWith(PNStrings.PNG_EXT))
                    {
                        try
                        {
                            var buffer = Convert.FromBase64String(base64String);
                            if (gr.ID.In((int)SpecialGroups.AllGroups, 0, (int)SpecialGroups.Diary,
                                (int)SpecialGroups.Backup, (int)SpecialGroups.SearchResults,
                                (int)SpecialGroups.Favorites, (int)SpecialGroups.Incoming, (int)SpecialGroups.Docking,
                                (int)SpecialGroups.RecycleBin) || base64String.StartsWith("resource."))
                            {
                                //possible image data stored as string when data directory just copied into new edition folder
                                upgradeGroupIcon(gr, gr.ID, (string)r["ICON"]);
                            }
                            else
                            {
                                using (var ms = new MemoryStream(buffer))
                                {
                                    ms.Position = 0;
                                    gr.Image = new BitmapImage();
                                    gr.Image.BeginInit();
                                    gr.Image.CacheOption = BitmapCacheOption.OnLoad;
                                    gr.Image.StreamSource = ms;
                                    gr.Image.EndInit();
                                }
                                if (gr.IsDefaultImage)
                                {
                                    gr.IsDefaultImage = false;
                                    var sb = new StringBuilder("UPDATE GROUPS SET IS_DEFAULT_IMAGE = 0");
                                    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                                }
                            }
                        }
                        catch (FormatException)
                        {
                            //possible exception when data directory just copied into new edition folder
                            upgradeGroupIcon(gr, gr.ID, (string)r["ICON"]);
                        }
                    }
                    else
                    {
                        gr.Image = TryFindResource(Path.GetFileNameWithoutExtension(base64String)) as BitmapImage;// new BitmapImage(new Uri(base64String));
                    }
                }

                try
                {
                    var clr = c.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["BACK_COLOR"]);
                    if (clr != null)
                        gr.Skinless.BackColor = (Color)clr;
                }
                catch (FormatException)
                {
                    //possible FormatException after synchronization with old database
                    var clr = dcc.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["BACK_COLOR"]);
                    if (clr != null)
                    {
                        var drawingColor = (System.Drawing.Color)clr;
                        gr.Skinless.BackColor = Color.FromArgb(drawingColor.A, drawingColor.R,
                            drawingColor.G, drawingColor.B);
                        var sb = new StringBuilder("UPDATE GROUPS SET BACK_COLOR = '");
                        sb.Append(c.ConvertToString(null, PNStatic.CultureInvariant, gr.Skinless.BackColor));
                        sb.Append("' WHERE GROUP_ID = ");
                        sb.Append(gr.ID);
                        PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                    }
                }

                try
                {
                    var clr = c.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["CAPTION_FONT_COLOR"]);
                    if (clr != null)
                        gr.Skinless.CaptionColor = (Color)clr;
                }
                catch (FormatException)
                {
                    //possible FormatException after synchronization with old database
                    var clr = dcc.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["CAPTION_FONT_COLOR"]);
                    if (clr != null)
                    {
                        var drawingColor = (System.Drawing.Color)clr;
                        gr.Skinless.CaptionColor = Color.FromArgb(drawingColor.A, drawingColor.R,
                            drawingColor.G, drawingColor.B);
                        var sb = new StringBuilder("UPDATE GROUPS SET CAPTION_FONT_COLOR = '");
                        sb.Append(c.ConvertToString(null, PNStatic.CultureInvariant, gr.Skinless.CaptionColor));
                        sb.Append("' WHERE GROUP_ID = ");
                        sb.Append(gr.ID);
                        PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                    }
                }

                var fontString = (string)r["CAPTION_FONT"];
                //try
                //{
                var fonts = new InstalledFontCollection();
                var arr = fontString.Split(',');
                if (fontString.Any(ch => ch == '^'))
                {
                    //old format font string
                    var lf = lfc.ConvertFromString(fontString);
                    gr.Skinless.CaptionFont = PNStatic.FromLogFont(lf);
                    var sb = new StringBuilder("UPDATE GROUPS SET CAPTION_FONT = '");
                    sb.Append(wfc.ConvertToString(null, PNStatic.CultureInvariant, gr.Skinless.CaptionFont));
                    sb.Append("' WHERE GROUP_ID = ");
                    sb.Append(gr.ID);
                    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                }
                else if (fonts.Families.Any(ff => ff.Name == arr[0]))
                {
                    //normal font string
                    gr.Skinless.CaptionFont = (PNFont)wfc.ConvertFromString(fontString);
                }
                else
                {
                    //possible not existing font name
                    arr[0] = PNStrings.DEF_CAPTION_FONT;
                    fontString = string.Join(",", arr);
                    gr.Skinless.CaptionFont = (PNFont)wfc.ConvertFromString(fontString);
                    var sb = new StringBuilder("UPDATE GROUPS SET CAPTION_FONT = '");
                    sb.Append(fontString);
                    sb.Append("' WHERE GROUP_ID = ");
                    sb.Append(gr.ID);
                    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                }
                //}
                //catch (IndexOutOfRangeException)
                //{
                //    //possible IndexOutOfRangeException after synchronization with old database
                //    var lf = lfc.ConvertFromString(fontString);
                //    gr.Skinless.CaptionFont = PNStatic.FromLogFont(lf);
                //    var sb = new StringBuilder("UPDATE GROUPS SET CAPTION_FONT = '");
                //    sb.Append(wfc.ConvertToString(null, PNStatic.CultureInvariant, gr.Skinless.CaptionFont));
                //    sb.Append("' WHERE GROUP_ID = ");
                //    sb.Append(gr.ID);
                //    PNData.ExecuteTransactionForStringBuilder(sb, PNData.ConnectionString);
                //}

                var skinName = (string)r["SKIN_NAME"];
                if (skinName != PNSkinDetails.NO_SKIN)
                {
                    gr.Skin.SkinName = skinName;
                    //load skin
                    var path = Path.Combine(PNPaths.Instance.SkinsDir, gr.Skin.SkinName) + ".pnskn";
                    if (File.Exists(path))
                    {
                        PNSkinsOperations.LoadSkin(path, gr.Skin);
                    }
                }
                if (!PNData.IsDBNull(r["FONT"]))
                {
                    gr.Font = lfc.ConvertFromString((string)r["FONT"]);
                }
                if (!PNData.IsDBNull(r["FONT_COLOR"]))
                {
                    var clr = dcc.ConvertFromString(null, PNStatic.CultureInvariant, (string)r["FONT_COLOR"]);
                    if (clr != null)
                        gr.FontColor = (System.Drawing.Color)clr;
                }
            }
            catch (Exception ex)
            {
                PNStatic.LogException(ex);
            }
        }
Ejemplo n.º 41
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string color = (string)value;
            try
            {
                TypeConverter colorConverter = new ColorConverter();
                Color c = (Color)colorConverter.ConvertFromString(color);

                return new SolidColorBrush(c);
            }
            catch
            {
                return Brushes.White;
            }
        }
Ejemplo n.º 42
0
        private void asyncOutputBoxColorAppend(RichTextBox targetBox, string text, string color)
        {
            targetBox.Dispatcher.Invoke(new Action(() =>
            {
                TypeConverter colorConverter = new ColorConverter();
                Color colorColor = (Color)colorConverter.ConvertFromString(color);
                SolidColorBrush colorBrush = new SolidColorBrush(colorColor);

                TextRange tr = new TextRange(targetBox.Document.ContentEnd, targetBox.Document.ContentEnd);
                tr.Text = text;
                tr.ApplyPropertyValue(TextElement.ForegroundProperty, colorBrush);
            }));
        }