Esempio n. 1
0
        public SkiaTextLayout(
            string value,
            RectangleF rect,
            ITextAttributes textAttributes,
            LayoutLine callback,
            TextFlow textFlow = TextFlow.ClipBounds,
            SKPaint paint     = null)
        {
            _value          = value;
            _textAttributes = textAttributes;
            _rect           = rect;
            _callback       = callback;
            _textFlow       = textFlow;
            _paint          = paint;

            if (paint == null)
            {
                _paint = new SKPaint()
                {
                    Typeface = SkiaDelegatingFontService.Instance.GetTypeface(_textAttributes.FontName),
                    TextSize = _textAttributes.FontSize
                };

                _disposePaint = true;
            }

            var metrics = _paint.FontMetrics;

            _descent    = metrics.Descent;
            _lineHeight = _paint.FontSpacing;
        }
        private void Initialize()
        {
            this.font = Resources.GetFont(Resources.FontResources.droid_reg08);

            this.textFlow = new TextFlow();

            this.textFlow.TextRuns.Add(Instruction1 + GHIElectronics.TinyCLR.Native.DeviceInformation.DeviceName, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            var speed = Power.GetSystemClock() == SystemClock.High ? "Clock: 480MHz" : "Clock: 240MHz";

            this.textFlow.TextRuns.Add(speed, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction3, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction4 + (GHIElectronics.TinyCLR.Native.Memory.UnmanagedMemory.FreeBytes / 1024) + "KB", this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction5 + GHIElectronics.TinyCLR.Native.DeviceInformation.Version.ToString("x8").Substring(0, 3), this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction6 + GHIElectronics.TinyCLR.Native.DeviceInformation.ManufacturerName, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction7, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);
        }
        private void Initialize()
        {
            this.textFlow = new TextFlow();

            this.textFlow.TextRuns.Add(Instruction1, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction2, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction3, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            var yellowColor = System.Drawing.Color.Yellow;

            this.textFlow.TextRuns.Add(Instruction4, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(yellowColor.R, yellowColor.G, yellowColor.B));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction5, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction6, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction7, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction8, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);
        }
Esempio n. 4
0
        protected virtual Drawable AddCharacterToFlow(char c)
        {
            // Remove all characters to the right and store them in a local list,
            // such that their depth can be updated.
            List <Drawable> charsRight = new List <Drawable>();

            foreach (Drawable d in TextFlow.Children.Skip(selectionLeft))
            {
                charsRight.Add(d);
            }
            TextFlow.RemoveRange(charsRight);

            // Update their depth to make room for the to-be inserted character.
            int i = selectionLeft;

            foreach (Drawable d in charsRight)
            {
                d.Depth = getDepthForCharacterIndex(i++);
            }

            // Add the character
            Drawable ch = GetDrawableCharacter(c);

            ch.Depth = getDepthForCharacterIndex(selectionLeft);

            TextFlow.Add(ch);

            // Add back all the previously removed characters
            TextFlow.AddRange(charsRight);

            return(ch);
        }
Esempio n. 5
0
        private void Initialize()
        {
            this.font = Resources.GetFont(Resources.FontResources.droid_reg08);

            this.textFlow = new TextFlow();

            this.textFlow.TextRuns.Add(Instruction1, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction2, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction3, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction4, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction5, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction6, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction7, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction8, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);
        }
Esempio n. 6
0
        object TextFlow_UpdateWindow(object obj)
        {
            txtFlow = new TextFlow();
            if (_txtRun)
            {
                txtFlow.TextRuns.Add(tr1);
                txtFlow.TextRuns.Add("1st Text", _font, _color);
                txtFlow.TextRuns.Add(tr1);
            }

            if (_lineCount)
            {
                txtFlow.TextRuns.Add(_longStr, _font, _color);
                txtFlow.TextRuns.Add(TextRun.EndOfLine);
                for (int i = 0; i < count; i++)
                {
                    txtFlow.TextRuns.Add("Text " + i, _font, _color);
                    txtFlow.TextRuns.Add(TextRun.EndOfLine);
                }
            }

            trc = txtFlow.TextRuns;
            txtFlow.ScrollingStyle = _style;
            _getStyle        = txtFlow.ScrollingStyle;
            mainWindow.Child = txtFlow;

            return(obj);
        }
Esempio n. 7
0
        public Window CreateWindow()
        {
            // Create a window object and set its size to the
            // size of the display.
            mainWindow        = new Window();
            mainWindow.Height = SystemMetrics.ScreenHeight;
            mainWindow.Width  = SystemMetrics.ScreenWidth;

            Font font      = Resources.GetFont(Resources.FontResources.NinaB);
            Font smallFont = Resources.GetFont(Resources.FontResources.small);

            TextFlow textFlow = new TextFlow();

            textFlow.TextRuns.Add("Hello world.", font, Colors.Black);
            textFlow.TextRuns.Add(" Hello world.", smallFont, Colors.Red);
            textFlow.TextRuns.Add(TextRun.EndOfLine);
            textFlow.TextRuns.Add("Hello world.", font, Colors.Green);

            // Add the text flow to the window.
            mainWindow.Child = textFlow;

            // Set the window visibility to visible.
            mainWindow.Visibility = Visibility.Visible;

            return(mainWindow);
        }
Esempio n. 8
0
            /// <summary>
            /// Initialize console window with the given text and background colours
            /// </summary>
            /// <param name="textColor">text colour</param>
            /// <param name="backgroundColor">background colour</param>
            private ConsoleWindow(Color textColor, Color backgroundColor)
            {
                this.textColor       = textColor;
                this.backgroundColor = backgroundColor;
                Font       = Resource.GetFont(Resource.FontResources.Small);
                Background = new SolidColorBrush(this.backgroundColor);

                scrollViewer = new ScrollViewer
                {
                    LineHeight     = Font.Height,
                    ScrollingStyle = ScrollingStyle.LineByLine,
                    Width          = SystemMetrics.ScreenWidth,
                    Height         = SystemMetrics.ScreenHeight
                };

                numOfLines = scrollViewer.Height / scrollViewer.LineHeight;

                textFlow = new TextFlow
                {
                    VerticalAlignment   = VerticalAlignment.Top,
                    HorizontalAlignment = HorizontalAlignment.Left
                };

                scrollViewer.Child = textFlow;
                Child = scrollViewer;
            }
Esempio n. 9
0
        public static void Main301()
        {
            Console.WriteLine("Start Main301");

            // ============ Типы структур и значения с труктур в объектном представлении ===========
            // Создадим типы записи и последовательности записей
            PType tp1 = new PTypeRecord(
                new NamedType("name", new PType(PTypeEnumeration.sstring)),
                new NamedType("age", new PType(PTypeEnumeration.integer)));
            PType tp2 = new PTypeSequence(tp1);

            // Создадим структурные значения этих типов в объектном представлении
            object val1 = new object[] { "Иванов", 22 };
            object val2 = new object[]
            {
                new object[] { "Иванов", 22 },
                new object[] { "Петров", 33 },
                new object[] { "Сидоров", 44 }
            };

            // Визуализация структур в объектном представлении
            Console.WriteLine(tp1.Interpret(val1));
            Console.WriteLine(tp2.Interpret(val2));

            // ============== Сериализация/Десериализация =============
            // Сериализация выполняет отображение структуры на поток символов (текстовая сериализация) или
            // поток байтов (бинарная сериализация). Десериализация выполняет обратное преобразование.
            Stream stream = new MemoryStream();
            // сериализация делается через текстовый райтер
            TextWriter tw = new StreamWriter(stream);

            TextFlow.Serialize(tw, val2, tp2);
            tw.Flush();
            // посмотрим что записалось
            stream.Position = 0L;
            TextReader tr  = new StreamReader(stream);
            string     sss = tr.ReadToEnd();

            Console.WriteLine("Накопилось в стриме: " + sss);

            // десериализаця делатеся через текстовый ридер
            stream.Position = 0L;
            object val = TextFlow.Deserialize(tr, tp2);

            // Теперь надо посмотреть что в объекте
            Console.WriteLine("После цикла сериализация/десериализация: " + tp2.Interpret(val));

            // Бинарная сериализация
            // bool - 1 байт
            // byte - 1 байт
            // int - 4 байта
            // long, double - 8 байтов
            // строка - набор байтов определяемый BinaryWriter.Write((string)s)
            // запись - подряд стоящие сериализации полей записи
            // последовательность - long длина последовательности, подряд стоящие развертки элементов
            //
            // Бинарная сериализация совместима с BinaryWriter и BinaryReader

            // выполняется точно также, как текстовая сериализация (пример сделаю позже)
        }
Esempio n. 10
0
        public ConsoleUi(string windowTitle)
        {
            var panel = new StackPanel();

            _timeText = new Text(_arial14, windowTitle)
            {
                TextAlignment     = TextAlignment.Right,
                VerticalAlignment = VerticalAlignment.Top,
                ForeColor         = ColorUtility.ColorFromRGB(255, 255, 0)
            };

            panel.Children.Add(_timeText);

            var scroll = new ScrollViewer
            {
                Height         = SystemMetrics.ScreenHeight - _arial14.Height,
                Width          = SystemMetrics.ScreenWidth,
                ScrollingStyle = ScrollingStyle.Last,
                Background     = null,
                LineHeight     = _small.Height
            };

            panel.Children.Add(scroll);

            _log = new TextFlow
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top
            };

            scroll.Child = _log;

            Background = _solidBlack;
            Child      = panel;
        }
        protected override void UpdateState()
        {
            Action = incompatible.Value ? () => { } : (Action)Active.Toggle;

            if (incompatible.Value)
            {
                Colour4 backgroundColour     = ColourProvider.Background5;
                Colour4 textBackgroundColour = ColourProvider.Background4;

                Content.TransformTo(nameof(BorderColour), ColourInfo.GradientVertical(backgroundColour, textBackgroundColour), TRANSITION_DURATION, Easing.OutQuint);
                Background.FadeColour(backgroundColour, TRANSITION_DURATION, Easing.OutQuint);

                SwitchContainer.ResizeWidthTo(IDLE_SWITCH_WIDTH, TRANSITION_DURATION, Easing.OutQuint);
                SwitchContainer.FadeColour(Colour4.Gray, TRANSITION_DURATION, Easing.OutQuint);
                MainContentContainer.TransformTo(nameof(Padding), new MarginPadding
                {
                    Left  = IDLE_SWITCH_WIDTH,
                    Right = CORNER_RADIUS
                }, TRANSITION_DURATION, Easing.OutQuint);

                TextBackground.FadeColour(textBackgroundColour, TRANSITION_DURATION, Easing.OutQuint);
                TextFlow.FadeColour(Colour4.White.Opacity(0.5f), TRANSITION_DURATION, Easing.OutQuint);
                return;
            }

            SwitchContainer.FadeColour(Colour4.White, TRANSITION_DURATION, Easing.OutQuint);
            base.UpdateState();
        }
Esempio n. 12
0
        private bool removeCharacterOrSelection(bool sound = true)
        {
            if (Current.Disabled)
            {
                return(false);
            }

            if (text.Length == 0)
            {
                return(false);
            }
            if (selectionLength == 0 && selectionLeft == 0)
            {
                return(false);
            }

            int count = Math.Clamp(selectionLength, 1, text.Length);
            int start = Math.Clamp(selectionLength > 0 ? selectionLeft : selectionLeft - 1, 0, text.Length - count);

            if (count == 0)
            {
                return(false);
            }

            if (sound)
            {
                audio.Samples.Get(@"Keyboard/key-delete")?.Play();
            }

            foreach (var d in TextFlow.Children.Skip(start).Take(count).ToArray()) //ToArray since we are removing items from the children in this block.
            {
                TextFlow.Remove(d);

                TextContainer.Add(d);

                // account for potentially altered height of textbox
                d.Y = TextFlow.BoundingBox.Y;

                d.Hide();
                d.Expire();
            }

            text = text.Remove(start, count);

            if (selectionLength > 0)
            {
                selectionStart = selectionEnd = selectionLeft;
            }
            else
            {
                selectionStart = selectionEnd = selectionLeft - 1;
            }

            cursorAndLayout.Invalidate();
            return(true);
        }
 public static void DrawString(
     this ICanvas target,
     string value,
     RectangleF bounds,
     HorizontalAlignment horizontalAlignment,
     VerticalAlignment verticalAlignment,
     TextFlow textFlow           = TextFlow.ClipBounds,
     float lineSpacingAdjustment = 0)
 {
     target.DrawString(value, bounds.X, bounds.Y, bounds.Width, bounds.Height, horizontalAlignment, verticalAlignment, textFlow, lineSpacingAdjustment);
 }
Esempio n. 14
0
        /// <summary>
        /// Creates all WPF controls of the window
        /// </summary>
        private void InitializeComponents()
        {
            this.Width      = DisplayControl.ScreenWidth;
            this.Height     = DisplayControl.ScreenHeight;
            this.Background = new SolidColorBrush(Color.Black);

            #region Caption
            Text caption = new Text(nfResource.GetString(nfResource.StringResources.HighScore))
            {
                Font          = nfResource.GetFont(nfResource.FontResources.Consolas23),
                ForeColor     = Color.Red,
                TextAlignment = TextAlignment.Center
            };
            caption.SetMargin(0, 10, 0, 15);
            #endregion

            #region Score ListBox
            scoreListBox = new ListBox()
            {
                Background          = this.Background,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            foreach (ScoreRecord scoreRecord in parentApp.HighScore.Table)
            {
                ScoreItem scoreItem = new ScoreItem(scoreRecord.Name, scoreRecord.Score)
                {
                    Background = scoreListBox.Background,
                };
                scoreListBox.Items.Add(scoreItem);
            }
            #endregion

            #region HintLabel
            hintTextFlow = new TextFlow();
            hintTextFlow.SetMargin(0, 15, 0, 0);
            hintTextFlow.TextAlignment = TextAlignment.Center;
            UpdateHint();
            #endregion

            StackPanel mainStack = new StackPanel(Orientation.Vertical)
            {
                HorizontalAlignment = HorizontalAlignment.Center
            };
            mainStack.Children.Add(caption);
            mainStack.Children.Add(scoreListBox);
            mainStack.Children.Add(hintTextFlow);

            this.Child = mainStack;

            this.Visibility = Visibility.Visible;
            Buttons.Focus(this);
        }
Esempio n. 15
0
        private void Initialize()
        {
            this.textFlow = new TextFlow();

            this.textFlow.TextRuns.Add(Instruction1, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction2, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);

            this.textFlow.TextRuns.Add(Instruction3, this.font, GHIElectronics.TinyCLR.UI.Media.Color.FromRgb(0xFF, 0xFF, 0xFF));
            this.textFlow.TextRuns.Add(TextRun.EndOfLine);
        }
Esempio n. 16
0
        private void Deinitialize()
        {
            if (this.BottomBar != null)
            {
                this.OnBottomBarButtonUpEvent -= this.TemplateWindow_OnBottomBarButtonUpEvent;
            }

            this.textFlow.TextRuns.Clear();
            this.canvas.Children.Clear();

            this.font.Dispose();

            this.textFlow = null;
            this.canvas   = null;
        }
Esempio n. 17
0
        /// <summary>
        /// Removes a specified <paramref name="number"/> of characters left side of the current position.
        /// </summary>
        /// <remarks>
        /// If a selection persists, <see cref="removeSelection"/> must be called instead.
        /// </remarks>
        /// <returns>A string of the removed characters.</returns>
        private string removeCharacters(int number = 1)
        {
            if (Current.Disabled || text.Length == 0)
            {
                return(string.Empty);
            }

            int removeStart = Math.Clamp(selectionRight - number, 0, selectionRight);
            int removeCount = selectionRight - removeStart;

            if (removeCount == 0)
            {
                return(string.Empty);
            }

            Debug.Assert(selectionLength == 0 || removeCount == selectionLength);

            foreach (var d in TextFlow.Children.Skip(removeStart).Take(removeCount).ToArray()) //ToArray since we are removing items from the children in this block.
            {
                TextFlow.Remove(d);

                TextContainer.Add(d);

                // account for potentially altered height of textbox
                d.Y = TextFlow.BoundingBox.Y;

                d.Hide();
                d.Expire();
            }

            var removedText = text.Substring(removeStart, removeCount);

            text = text.Remove(removeStart, removeCount);

            // Reorder characters depth after removal to avoid ordering issues with newly added characters.
            for (int i = removeStart; i < TextFlow.Count; i++)
            {
                TextFlow.ChangeChildDepth(TextFlow[i], getDepthForCharacterIndex(i));
            }

            selectionStart = selectionEnd = removeStart;

            cursorAndLayout.Invalidate();

            return(removedText);
        }
Esempio n. 18
0
        static void Main201()
        {
            Console.WriteLine("Start Program201");
            // Определение поляровских типов
            PType tp_rec = new PTypeRecord(
                new NamedType("имя", new PType(PTypeEnumeration.sstring)),
                new NamedType("возраст", new PType(PTypeEnumeration.integer)),
                new NamedType("мужчина", new PType(PTypeEnumeration.boolean)));
            PType tp_seq = new PTypeSequence(tp_rec);
            // Задание поляровского объекта и его визуализация
            object seq_value = new object[]
            {
                new object[] { "Иванов", 24, true },
                new object[] { "Петрова", 18, false },
                new object[] { "Пупкин", 22, true }
            };

            Console.WriteLine(tp_seq.Interpret(seq_value));

            // Текстовая сериализация
            // Создадим поток байтов. Это мог бы быть файл, но сделали в памяти
            MemoryStream mstream = new MemoryStream();
            // Поработаем через текстовый интерфейс
            TextWriter tw = new StreamWriter(mstream);

            TextFlow.Serialize(tw, seq_value, tp_seq);
            tw.Flush();
            // Прочитаем то что записали
            TextReader tr = new StreamReader(mstream);

            mstream.Position = 0L;
            string instream = tr.ReadToEnd();

            Console.WriteLine($"======== instream={instream}");
            Console.WriteLine();

            // Теперь десериализуем
            object db = null;

            mstream.Position = 0L;
            db = TextFlow.Deserialize(tr, tp_seq);
            // проинтерпретируем объект и посмотрим
            Console.WriteLine(tp_seq.Interpret(db));
            Console.WriteLine();
        }
Esempio n. 19
0
        public void TestTextFlowSerializeDeserialize()
        {
            MemoryStream stream = new MemoryStream();
            TextWriter   tw     = new StreamWriter(stream);

            TextFlow.Serialize(tw, new object[] { 777, "Pupkin", 9.9999 }, tp_rec);
            tw.Flush();

            byte[] bytes = stream.ToArray();
            string res   = new string(bytes.Select(b => System.Convert.ToChar(b)).ToArray());

            Assert.AreEqual(res, "{777,\"Pupkin\",9.9999}");

            TextReader tr = new StreamReader(stream);

            stream.Position = 0L;
            object oval = TextFlow.Deserialize(tr, tp_rec);
            string val  = tp_rec.Interpret(oval);

            Assert.AreEqual(val, "{777,\"Pupkin\",9.9999}");
        }
Esempio n. 20
0
        public Window CreateWindow()
        {
            // Create a window object and set its size to the
            // size of the display.
            mainWindow        = new Window();
            mainWindow.Height = SystemMetrics.ScreenHeight;
            mainWindow.Width  = SystemMetrics.ScreenWidth;

            Font normalFont = Resources.GetFont(Resources.FontResources.NinaB);
            Font smallFont  = Resources.GetFont(Resources.FontResources.small);

            TextFlow textFlow = new TextFlow();

            // set the scrolling style to LineByLine or PageByPage
            textFlow.ScrollingStyle = ScrollingStyle.LineByLine;
            // Add text
            Color[] colors = new Color[] { Colors.Black, Colors.Gray,
                                           Colors.Red, Colors.Green, Colors.Blue };
            for (int i = 0; i < 100; ++i)
            {
                Font  font  = (i % 2 == 0) ? normalFont : smallFont;
                Color color = colors[i % colors.Length];
                textFlow.TextRuns.Add("Hello world. ", font, color);
                if (i % 2 == 0)
                {
                    textFlow.TextRuns.Add(TextRun.EndOfLine);
                }
            }

            // Add the text flow to the window.
            mainWindow.Child = textFlow;

            // Set the window visibility to visible.
            mainWindow.Visibility = Visibility.Visible;

            // Let the user scroll the text with buttons
            Buttons.Focus(textFlow);

            return(mainWindow);
        }
Esempio n. 21
0
        public ConsoleWindow()
        {
            StackPanel panel = new StackPanel();

            timeText = new Text(CourierRegular10, "Embarrassing second of silence.");
            timeText.TextAlignment     = TextAlignment.Right;
            timeText.VerticalAlignment = VerticalAlignment.Top;
            timeText.ForeColor         = ColorUtility.ColorFromRGB(255, 255, 0);
            panel.Children.Add(timeText);

            ScrollViewer scroll = new ScrollViewer();

            scroll.Height         = SystemMetrics.ScreenHeight - CourierRegular10.Height;
            scroll.Width          = SystemMetrics.ScreenWidth;
            scroll.ScrollingStyle = ScrollingStyle.Last;
            scroll.Background     = null;
            scroll.LineHeight     = Small.Height;

            panel.Children.Add(scroll);

            log = new TextFlow();
            log.HorizontalAlignment = HorizontalAlignment.Left;
            log.VerticalAlignment   = VerticalAlignment.Top;
            scroll.Child            = log;

            Background = solidBlack;
            Child      = panel;

            //ExtendedTimer clock = new ExtendedTimer(
            //    new System.Threading.TimerCallback(
            //        delegate
            //        {
            //            timeText.TextContent = DateTime.Now.ToString("ddd d. MMMM yyyy HH:mm:ss");
            //            timeText.Invalidate();
            //        }),
            //    null, ExtendedTimer.TimeEvents.Second);
        }
Esempio n. 22
0
        public static void Test()
        {
            PType tp_point = new PTypeRecord(
                new NamedType("x", new PType(PTypeEnumeration.real)),
                new NamedType("y", new PType(PTypeEnumeration.real)));
            PType tp_figure = new PTypeUnion(
                new NamedType("nothing", new PType(PTypeEnumeration.none)),
                new NamedType("point", tp_point),
                new NamedType("polygon", new PTypeSequence(tp_point)),
                new NamedType("circle", new PTypeRecord(
                                  new NamedType("center", tp_point),
                                  new NamedType("radius", new PType(PTypeEnumeration.real)))));
            PType  tp_sequ = new PTypeSequence(tp_figure);
            object sequ    = new object[]
            {
                new object[] { 1, new object[] { 3.5, 7.8 } },
                new object[] { 2, new object[] {
                                   new object[] { 0.0, 0.0 }, new object[] { 1.0, 0.0 }, new object[] { 1.0, 1.0 }, new object[] { 0.0, 1.0 }
                               } },
                new object[] { 3, new object[] { new object[] { 5.0, 5.0 }, 4.99 } }
            };

            // Выполним текстовую сериализацию
            TextFlow.Serialize(Console.Out, sequ, tp_sequ);
            Console.WriteLine();
            // Создадим Stream, сделаем бинарную сериализацию, будем считать, что это файл
            Stream stream = new MemoryStream();

            ByteFlow.Serialize(new BinaryWriter(stream), sequ, tp_sequ);
            // Десериализуем стрим (бинарный файл)
            stream.Position = 0L;
            object sequ_1 = ByteFlow.Deserialize(new BinaryReader(stream), tp_sequ);

            // Проверим полученное значение
            Console.WriteLine(tp_sequ.Interpret(sequ_1));
        }
Esempio n. 23
0
        public static void Demo101()
        {
            Console.WriteLine("Start Demo101");
            // === Демонстрация базовых действий со структурами ===
            // Создаем тип персоны
            PType tp_person = new PTypeRecord(
                new NamedType("id", new PType(PTypeEnumeration.integer)),
                new NamedType("name", new PType(PTypeEnumeration.sstring)),
                new NamedType("age", new PType(PTypeEnumeration.integer)));
            // делаем персону в объектном представлении
            object ivanov = new object[] { 7001, "Иванов", 20 };

            // интерпретируем объект в контексте типа
            Console.WriteLine(tp_person.Interpret(ivanov, true));
            // то же, но без имен полей
            Console.WriteLine(tp_person.Interpret(ivanov));
            Console.WriteLine();

            // Создадим поток байтов. Это мог бы быть файл:
            MemoryStream mstream = new MemoryStream();
            // Поработаем через текстовый интерфейс
            TextWriter tw = new StreamWriter(mstream);

            TextFlow.Serialize(tw, ivanov, tp_person);
            tw.Flush();
            // Прочитаем то что записали
            TextReader tr = new StreamReader(mstream);

            mstream.Position = 0L;
            string instream = tr.ReadToEnd();

            Console.WriteLine($"======== instream={instream}");
            Console.WriteLine();

            // Теперь десериализуем
            ivanov           = null;
            mstream.Position = 0L;
            ivanov           = TextFlow.Deserialize(tr, tp_person);
            // проинтерпретируем объект и посмотрим
            Console.WriteLine(tp_person.Interpret(ivanov));
            Console.WriteLine();

            // ===== Последовательности =====
            // Создаем тип последовательности персон
            PType tp_persons = new PTypeSequence(tp_person);
            // Сделаем генератор персон
            Random rnd = new Random();
            Func <int, IEnumerable <object> > GenPers = nper => Enumerable.Range(0, nper)
                                                        .Select(i => new object[] { i, "Иванов_" + i, rnd.Next(130) });

            // Сгенерируем пробу и проинтерпретируем
            object sequobj = GenPers(20).ToArray();

            Console.WriteLine(tp_persons.Interpret(sequobj));
            Console.WriteLine();

            // Чем плохо такое решение? Тем, что весь большой объект (последовательность записей) разворачивается в ОЗУ
            // Более экономным, как правило, является использование последовательностей

            string dbpath     = @"D:/Home/data/GetStarted/";
            Stream filestream = new FileStream(dbpath + "db0.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            UniversalSequenceBase usequence = new UniversalSequenceBase(tp_person, filestream);

            // Последовательность можно очистить, в нее можно добавлять элементы, в конце добавлений нужно сбросить буфер
            int npersons = 1_000_000;

            usequence.Clear();
            foreach (object record in GenPers(npersons))
            {
                usequence.AppendElement(record);
            }
            usequence.Flush();

            // Теперь можно сканировать последовательность
            int totalages = 0;

            usequence.Scan((off, ob) => { totalages += (int)((object[])ob)[2]; return(true); });
            Console.WriteLine($"total ages = {totalages}");

            //// Можно прочитать i-ый элемент
            //int ind = npersons * 2 / 3;
            //object ores = usequence.GetByIndex(ind);
            //Console.WriteLine($"element={tp_person.Interpret(ores)}");
            //// Но нет - облом: Размер элемента не фиксирован (есть строка), к таким элементам по индексу обращаться не надо
        }
Esempio n. 24
0
        public Window CreateUI()
        {
            Window     window = new Window();
            StackPanel panel  = new StackPanel();

            panel.Orientation = Orientation.Vertical;

            Text text = new Text();

            text.Font                = Resources.GetFont(Resources.FontResources.FONT);
            text.TextContent         = "Hello";
            text.ForeColor           = Colors.Red;
            text.HorizontalAlignment = Microsoft.SPOT.Presentation.HorizontalAlignment.Left;
            text.VerticalAlignment   = Microsoft.SPOT.Presentation.VerticalAlignment.Stretch;

            panel.Children.Add(text);

            text                     = new Text();
            text.Font                = Resources.GetFont(Resources.FontResources.FONT);
            text.TextContent         = "comma";
            text.ForeColor           = Colors.Green;
            text.HorizontalAlignment = Microsoft.SPOT.Presentation.HorizontalAlignment.Center;
            text.VerticalAlignment   = Microsoft.SPOT.Presentation.VerticalAlignment.Stretch;

            panel.Children.Add(text);

            text                     = new Text();
            text.Font                = Resources.GetFont(Resources.FontResources.FONT);
            text.TextContent         = "World!";
            text.ForeColor           = Colors.Blue;
            text.HorizontalAlignment = Microsoft.SPOT.Presentation.HorizontalAlignment.Right;
            text.VerticalAlignment   = Microsoft.SPOT.Presentation.VerticalAlignment.Stretch;

            panel.Children.Add(text);

            TextFlow textFlow = new TextFlow();

            textFlow.Height = 60;
            textFlow.TextRuns.Add("[BEGIN] ", Resources.GetFont(Resources.FontResources.FONT), Colors.Green);
            textFlow.TextRuns.Add("Call me Ishmael. ", Resources.GetFont(Resources.FontResources.FONT), Colors.Gray);
            textFlow.TextRuns.Add("Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. ", Resources.GetFont(Resources.FontResources.FONT), Colors.Gray);
            textFlow.TextRuns.Add("It is a way I have of driving off the spleen, and regulating the circulation. ", Resources.GetFont(Resources.FontResources.FONT), Colors.Gray);
            textFlow.TextRuns.Add("A_very_long_sentence_with_no_whitespace_that_should_trigger_an_emergency_break. ", Resources.GetFont(Resources.FontResources.FONT), Colors.Blue);
            textFlow.TextRuns.Add("[END] ", Resources.GetFont(Resources.FontResources.FONT), Colors.Green);

            panel.Children.Add(textFlow);

            text                     = new Text();
            text.Font                = Resources.GetFont(Resources.FontResources.FONT);
            text.TextContent         = "";
            text.ForeColor           = Colors.Gray;
            text.HorizontalAlignment = Microsoft.SPOT.Presentation.HorizontalAlignment.Center;
            text.VerticalAlignment   = Microsoft.SPOT.Presentation.VerticalAlignment.Stretch;

            panel.Children.Add(text);

            _buttonText = text;

            text                     = new Text();
            text.Font                = Resources.GetFont(Resources.FontResources.FONT);
            text.TextContent         = "";
            text.ForeColor           = Colors.Gray;
            text.HorizontalAlignment = Microsoft.SPOT.Presentation.HorizontalAlignment.Center;
            text.VerticalAlignment   = Microsoft.SPOT.Presentation.VerticalAlignment.Stretch;

            panel.Children.Add(text);

            _timeText = text;

            window.Child = panel;

            window.AddHandler(Buttons.ButtonDownEvent, new RoutedEventHandler(OnButtonDown), false);
            window.AddHandler(Buttons.GotFocusEvent, new RoutedEventHandler(OnGotFocus), false);

            window.Width      = SystemMetrics.ScreenWidth;
            window.Height     = SystemMetrics.ScreenHeight;
            window.Visibility = Visibility.Visible;

            // Buttons.Focus(window);

            Buttons.Focus(textFlow);

            return(window);
        }
 private void Deinitialize()
 {
     this.textFlow.TextRuns.Clear();
     this.textFlow = null;
 }
Esempio n. 26
0
 public void DrawString(string value, float x, float y, float width, float height, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment,
                        TextFlow textFlow = TextFlow.ClipBounds, float lineSpacingAdjustment = 0)
 {
     _commands.Add(canvas => canvas.DrawString(value, x, y, width, height, horizontalAlignment, verticalAlignment, textFlow, lineSpacingAdjustment));
 }
        public Window CreateWindow()
        {
            // Create a window object and set its size to the
            // size of the display.
            mainWindow        = new Window();
            mainWindow.Height = SystemMetrics.ScreenHeight;
            mainWindow.Width  = SystemMetrics.ScreenWidth;
            // Add a gradient color background to the window
            mainWindow.Background = new LinearGradientBrush(Colors.White, Colors.Red,
                                                            0, 0,
                                                            mainWindow.Width, mainWindow.Height);

            Font normalFont = Resources.GetFont(Resources.FontResources.NinaB);
            Font smallFont  = Resources.GetFont(Resources.FontResources.small);

            // Create a list box control and add text items
            ListBox listBox = new ListBox();

            // set the width so that it fills the entire screen
            listBox.Child.Width = mainWindow.Width;
            // make the list box transparent
            listBox.Background = null;
            // make the enclosed scroll viewer transparent also
            // we get the scroll viewer via the child property but
            // need to cast it to Control in order to clear the background
            ((Control)listBox.Child).Background = null;

            // Add simple text items
            for (int i = 0; i < 2; ++i)
            {
                string str  = "Simple text item";
                Text   text = new Text(normalFont, str);
                text.SetMargin(2);
                ListBoxItem item = new HighlightableListBoxItem(text);
                listBox.Items.Add(item);
            }

            // Add a separator
            listBox.Items.Add(new SeparatorListBoxItem());

            // Add a text item with icon
            {
                // Create the stack panel to align the elements
                StackPanel stackPanel = new StackPanel(Orientation.Horizontal);

                // Icon
                Bitmap bmp = Resources.GetBitmap(Resources.BitmapResources.Clock);
                // Make the bitmap transparent using
                // the color of the top left corner pixel.
                // Therefore the image should not be in the Bitmap and Jpeg format
                // because that requires to create a copy in order to make it
                // transparent. Use Gif instead.
                bmp.MakeTransparent(bmp.GetPixel(0, 0));
                Image image = new Image(bmp);
                image.SetMargin(2); // set a margin to separate the image
                // vertically center the icon within the item
                image.VerticalAlignment = VerticalAlignment.Center;
                stackPanel.Children.Add(image);

                // Text
                Text text = new Text(normalFont, "Item with a icon and text");
                text.SetMargin(2); // set margin to separate the text
                // vertically center the icon within the item
                text.VerticalAlignment = VerticalAlignment.Center;
                stackPanel.Children.Add(text);

                // Create a highlightable list box item
                ListBoxItem item = new HighlightableListBoxItem(stackPanel);
                listBox.Items.Add(item);
            }

            // Add a separator
            listBox.Items.Add(new SeparatorListBoxItem());

            // Add two items with multiple columns
            // use i to add a right aligned number to the first column
            for (int i = 0; i <= 100; i += 50)
            {
                //create the stack panel to align the elements
                StackPanel stackPanel = new StackPanel(Orientation.Horizontal);

                // Add right aligned text
                Text text1 = new Text(normalFont, i.ToString());
                text1.Width = 30;
                text1.SetMargin(2); // set margin to separate the text
                text1.TextAlignment = TextAlignment.Right;
                // vertically center the icon within the item
                text1.VerticalAlignment = VerticalAlignment.Center;
                stackPanel.Children.Add(text1);

                // Icon
                Bitmap bmp = Resources.GetBitmap(Resources.BitmapResources.Audio);
                // Make the bitmap transparent using
                // the color of the top left corner pixel.
                // Therefore the image should not be in the Bitmap and Jpeg format
                // because that requires to create a copy in order to make it
                // transparent. Use Gif instead.
                bmp.MakeTransparent(bmp.GetPixel(0, 0));
                Image image = new Image(bmp);
                image.SetMargin(2); // set a margin to separate the image
                // vertically center the icon within the item
                image.VerticalAlignment = VerticalAlignment.Center;
                stackPanel.Children.Add(image);

                // Text
                Text text = new Text(normalFont, "Item with multiple columns");
                text.SetMargin(2); // set margin to separate the text
                // vertically center the icon within the item
                text.VerticalAlignment = VerticalAlignment.Center;
                stackPanel.Children.Add(text);

                // Create a highlightable list box item
                ListBoxItem item = new HighlightableListBoxItem(stackPanel);
                listBox.Items.Add(item);
            }

            // Add a separator
            listBox.Items.Add(new SeparatorListBoxItem());

            // Add two multi line text item
            for (int i = 0; i < 2; ++i)
            {
                TextFlow textFlow = new TextFlow();
                textFlow.TextRuns.Add("This is the first line.", normalFont, Colors.Black);
                textFlow.TextRuns.Add(TextRun.EndOfLine);
                textFlow.TextRuns.Add("Second line.", normalFont, Colors.Green);
                textFlow.TextRuns.Add(TextRun.EndOfLine);
                textFlow.TextRuns.Add("Third line.", smallFont, Colors.Red);
                textFlow.SetMargin(2);

                ListBoxItem item = new HighlightableListBoxItem(textFlow);
                listBox.Items.Add(item);
            }

            // Add the text control to the window.
            mainWindow.Child = listBox;

            // Set the window visibility to visible.
            mainWindow.Visibility = Visibility.Visible;

            // Let the user select items with the up and down buttons.
            Buttons.Focus(listBox);
            // Get notified when the selected item was changed.
            listBox.SelectionChanged += new SelectionChangedEventHandler(listBox_SelectionChanged);
            // Get notified when a selected item was pressed
            // using the select button.
            listBox.AddHandler(Buttons.ButtonDownEvent, new ButtonEventHandler(listBox_ButtonDown), false);

            return(mainWindow);
        }
Esempio n. 28
0
        /// <summary>
        /// Creates the main window.
        /// </summary>
        /// <returns>The main window.</returns>
        public Window CreateWindow()
        {
            // Create a window object and set its size to the size of the
            // display.
            mainWindow        = new Window();
            mainWindow.Width  = SystemMetrics.ScreenWidth;
            mainWindow.Height = SystemMetrics.ScreenHeight;

            // Detect landscape or portrait so the program can adjust its
            // layout.
            bool portrait =
                SystemMetrics.ScreenWidth < SystemMetrics.ScreenHeight;

            // Create the main stack panel.
            StackPanel stack = new StackPanel(portrait ?
                                              Orientation.Vertical : Orientation.Horizontal);

            // Create stack panels for the current temperature and target
            // temperature.
            StackPanel stack1 = new StackPanel(Orientation.Vertical);
            StackPanel stack2 = new StackPanel(Orientation.Vertical);

            // Create border panels for the current temperature and target
            // temperature.
            BorderPanel panel1;
            BorderPanel panel2;

            // Detect portrait or landscape orientation.
            if (portrait)
            {
                // If in portrait mode, set the width to the screen width and
                // height to 1/4 and 3/4.
                panel1 = new BorderPanel(SystemMetrics.ScreenWidth,
                                         (int)(SystemMetrics.ScreenHeight * .25));
                panel2 = new BorderPanel(SystemMetrics.ScreenWidth,
                                         (int)(SystemMetrics.ScreenHeight * .75));
            }
            else
            {
                // Otherwise, set the width and height to 1/2 and 1/2,
                // respectively.
                panel1 = new BorderPanel(SystemMetrics.ScreenWidth / 2,
                                         SystemMetrics.ScreenHeight);
                panel2 = new BorderPanel(SystemMetrics.ScreenWidth / 2,
                                         SystemMetrics.ScreenHeight);
            }

            // Add the border panels to the panels containing the current
            // temperature and target temperature.
            panel1.Children.Add(stack1);
            panel2.Children.Add(stack2);

            // Add the stack panels to the border panels.
            stack.Children.Add(panel1);
            stack.Children.Add(panel2);

            // Create text controls for the current temperature.
            _textCurrentTemp      = new Text();
            _textCurrentTemp.Font =
                Resources.GetFont(Resources.FontResources.nina48);
            _textCurrentTemp.TextContent =
                Resources.GetString(Resources.StringResources.InitialTemp);
            _textCurrentTemp.HorizontalAlignment =
                Microsoft.SPOT.Presentation.HorizontalAlignment.Center;
            _textCurrentTemp.VerticalAlignment =
                Microsoft.SPOT.Presentation.VerticalAlignment.Center;

            Text currentLabel = new Text();

            currentLabel.Font =
                Resources.GetFont(Resources.FontResources.nina14);
            currentLabel.TextContent =
                Resources.GetString(Resources.StringResources.CurrentTemp);
            currentLabel.HorizontalAlignment =
                Microsoft.SPOT.Presentation.HorizontalAlignment.Center;
            currentLabel.VerticalAlignment =
                Microsoft.SPOT.Presentation.VerticalAlignment.Center;

            // Add the text controls to the current temperature stack panel.
            stack1.Children.Add(currentLabel);
            stack1.Children.Add(_textCurrentTemp);

            // Create controls for the target temperature.
            _textTargetTemp      = new Text();
            _textTargetTemp.Font =
                Resources.GetFont(Resources.FontResources.nina48);
            _textTargetTemp.TextContent =
                Resources.GetString(Resources.StringResources.InitialTemp);
            _textTargetTemp.HorizontalAlignment =
                HorizontalAlignment.Center;
            _textTargetTemp.VerticalAlignment =
                VerticalAlignment.Center;

            Text targetLabel = new Text();

            targetLabel.Font =
                Resources.GetFont(Resources.FontResources.nina14);
            targetLabel.TextContent =
                Resources.GetString(Resources.StringResources.TargetTemp);
            targetLabel.HorizontalAlignment = HorizontalAlignment.Center;
            targetLabel.VerticalAlignment   = VerticalAlignment.Center;

            // Create the air conditioner or heater status indicator.
            _statusIndicator = new StatusIndicator();

            // Add the controls to the target temperature stack panel.
            stack2.Children.Add(targetLabel);
            stack2.Children.Add(_textTargetTemp);
            stack2.Children.Add(_statusIndicator);

            // Add instructions to the target temperature stack panel.
            TextFlow instructions = new TextFlow();

            instructions.HorizontalAlignment = HorizontalAlignment.Center;
            instructions.VerticalAlignment   = VerticalAlignment.Center;
            instructions.TextAlignment       = TextAlignment.Center;
            instructions.TextRuns.Add(new TextRun("Up Button to Increase",
                                                  Resources.GetFont(Resources.FontResources.nina14), Color.Black));
            instructions.TextRuns.Add(TextRun.EndOfLine);
            instructions.TextRuns.Add(new TextRun("Down Button to Decrease",
                                                  Resources.GetFont(Resources.FontResources.nina14), Color.Black));
            instructions.TextRuns.Add(TextRun.EndOfLine);
            instructions.TextRuns.Add(new TextRun(
                                          "Select Button to Toggle Celsius / Fahrenheit",
                                          Resources.GetFont(Resources.FontResources.nina14), Color.Black));
            stack2.Children.Add(instructions);

            // Set the main window child to the main horizontal stack panel.
            mainWindow.Child = stack;

            // Connect the button handler to all of the buttons.
            mainWindow.AddHandler(Buttons.ButtonUpEvent,
                                  new RoutedEventHandler(OnButtonUp), false);

            // Set the window visibility to Visible.
            mainWindow.Visibility = Visibility.Visible;

            // Attach the button focus to the window.
            Buttons.Focus(mainWindow);

            // Create the timer that will check the current temperature.
            _timer          = new DispatcherTimer(mainWindow.Dispatcher);
            _timer.Interval = new TimeSpan(0, 0, 0, 0, 50);
            _timer.Tick    += new EventHandler(OnTimer);
            _timer.Start();

            return(mainWindow);
        }
        public void SaveFlowToPolarText(IEnumerable <object> flow, FileStream file)
        {
            TextWriter tw = new StreamWriter(file);

            TextFlow.SerializeFlowToSequenseFormatted(tw, flow, tp_Record, 0);
        }
Esempio n. 30
0
        static void Main1()
        {
            string root = "";

            Console.WriteLine("Start TestDataGenerators");
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            int npersons = 10;

            Phototeka.PhototekaRecordFlow rflow = new Phototeka.PhototekaRecordFlow(npersons);
            Console.WriteLine(rflow.GenerateAll().Count());
            sw.Stop();
            Console.WriteLine($"duration={sw.ElapsedMilliseconds}");

            PType tp_Arc = new PTypeUnion(
                new NamedType("field", new PTypeRecord(
                                  new NamedType("prop", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("value", new PType(PTypeEnumeration.sstring)))),
                new NamedType("text", new PTypeRecord(
                                  new NamedType("prop", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("value", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("lang", new PType(PTypeEnumeration.sstring)))),
                new NamedType("direct", new PTypeRecord(
                                  new NamedType("prop", new PType(PTypeEnumeration.sstring)),
                                  new NamedType("resource", new PType(PTypeEnumeration.sstring))))
                );
            PType tp_Record = new PTypeRecord(
                new NamedType("about", new PType(PTypeEnumeration.sstring)),
                new NamedType("typ", new PType(PTypeEnumeration.sstring)),
                new NamedType("arcs", new PTypeSequence(tp_Arc))
                );

            // string binpath = root+"phototeka.bin";
            // sw.Restart();
            // rflow.SaveFlowToSequence(rflow.GenerateAll(), binpath);
            // sw.Stop();
            // Console.WriteLine($"duration={sw.ElapsedMilliseconds}");

            // sw.Restart();
            // UniversalSequenceBase sequ = new UniversalSequenceBase(tp_Record,
            //     File.Open(binpath, FileMode.OpenOrCreate, FileAccess.ReadWrite));
            // sequ.Scan((off, obj) => true);
            // sw.Stop();
            // Console.WriteLine($"Scanning... duration={sw.ElapsedMilliseconds}");

            //sw.Restart();
            //rflow.SaveFlowToXml(rflow.GenerateAll(), root + "phototeka.xml");
            //sw.Stop();
            //Console.WriteLine($"duration={sw.ElapsedMilliseconds}");

            string filexmlpath = root + "phototeka.fogx";

            FileStream filexml = File.Open(filexmlpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            sw.Restart();
            rflow.SaveFlowToXElement(rflow.GenerateAll(), filexml);
            sw.Stop();
            Console.WriteLine($"duration={sw.ElapsedMilliseconds}");
            filexml.Close();

            //sw.Restart();root +
            //XElement db1 = XElement.Load(filexmlpath);
            //sw.Stop();
            //Console.WriteLine($"Scanning... duration={sw.ElapsedMilliseconds}");

            string ptpath = "phototeka.fogp";

            FileStream ptextfile = File.Open(ptpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            sw.Restart();
            rflow.SaveFlowToPolarText(rflow.GenerateAll(), ptextfile);
            sw.Stop();
            Console.WriteLine($"Loading and writing... duration={sw.ElapsedMilliseconds}");
            ptextfile.Close();

            ptextfile = File.Open(ptpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            sw.Restart();
            TextReader tr    = new StreamReader(ptextfile);
            int        nrecs = TextFlow.DeserializeSequenseToFlow(tr, tp_Record).Count();

            Console.WriteLine($"{nrecs} records read");
            sw.Stop();
            Console.WriteLine($"Scanning... duration={sw.ElapsedMilliseconds}");
        }