Ejemplo n.º 1
0
        protected override void CreateTextMarkerGroup(Canvas gauge, double gaugeR)
        {
            ChartModel model = Model;
            Canvas     gElem = new Canvas();

            gauge.Children.Add(gElem);

            LookAndFeel lf = CurrentLookAndFeel;

            int    majorMarkerCount = YMajorGridCount;
            int    minorMarkerCount = YMinorGridCount;
            string majorMarkerXAML  = lf.GetGauageMarkerMajorXAML(),
                   minorMarkerXAML  = lf.GetGauageMarkerMinorXAML();
            string    textXAML      = lf.GetGauageTextXAML();
            TextBlock textElem;

            Canvas markerContainerCanvas = gauge.FindName("markerContainer") as Canvas;

            double markerContainerR = markerContainerCanvas.Width / 2;
            double minValue = model.MinYValue, maxValue = model.MaxYValue;

            double x, y, angle, textMargin = 0.0;

            for (int i = 0; i <= majorMarkerCount; ++i)
            {
                double theta = i * Math.PI / majorMarkerCount;
                x     = gaugeR - markerContainerR * (Math.Cos(theta));
                y     = gaugeR - markerContainerR * (Math.Sin(theta));
                angle = theta * 180 / Math.PI;

                Path marker = XamlReader.Load(majorMarkerXAML) as Path;

                TransformGroup     tg = new TransformGroup();
                TranslateTransform tt = new TranslateTransform();
                RotateTransform    rt = new RotateTransform();

                tt.X     = x;
                tt.Y     = y;
                rt.Angle = angle;
                tg.Children.Add(rt);
                tg.Children.Add(tt);
                marker.RenderTransform = tg;
                gElem.Children.Add(marker);


                double value = minValue + i * (maxValue - minValue) / (majorMarkerCount);

                textElem      = XamlReader.Load(textXAML) as TextBlock;
                textElem.Text = value.ToString(Format);

                if (i == 0)
                {
                    textMargin = textElem.ActualHeight / 2;
                }
                x = gaugeR - (markerContainerR - textMargin) * (Math.Cos(theta));
                y = gaugeR - (markerContainerR - textMargin) * (Math.Sin(theta));

                if (theta >= Math.PI / 3 && theta <= 2 * Math.PI / 3)
                {
                    x -= textElem.ActualWidth / 2;
                }
                else
                {
                    y -= textElem.ActualHeight / 2;
                    if (theta < Math.PI / 2)
                    {
                        x += 2 * _TEXT_MARGIN;
                    }
                    else
                    {
                        x -= textElem.ActualWidth + 2 * _TEXT_MARGIN;
                    }
                }

                tt   = new TranslateTransform();
                tt.X = x;
                tt.Y = y;

                textElem.RenderTransform = tt;
                gElem.Children.Add(textElem);
            }

            for (int i = 1; i <= (majorMarkerCount) * minorMarkerCount; ++i)
            {
                if (i % minorMarkerCount == 0)
                {
                    continue;
                }

                double theta = i * Math.PI / (majorMarkerCount * minorMarkerCount);
                x = gaugeR - markerContainerR * (Math.Cos(theta));
                y = gaugeR - markerContainerR * (Math.Sin(theta));

                angle = theta * 180 / Math.PI;

                Path               marker = XamlReader.Load(minorMarkerXAML) as Path;
                TransformGroup     tg     = new TransformGroup();
                TranslateTransform tt     = new TranslateTransform();
                RotateTransform    rt     = new RotateTransform();

                tt.X     = x;
                tt.Y     = y;
                rt.Angle = angle;
                tg.Children.Add(rt);
                tg.Children.Add(tt);
                marker.RenderTransform = tg;
                gElem.Children.Add(marker);
            }
        }
Ejemplo n.º 2
0
        private void NestedRepeaterWithDataTemplateScenario(bool disableAnimation)
        {
            if (!disableAnimation && PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone5))
            {
                Log.Warning("This test is showing consistent issues with not scrolling enough on RS5 and 19H1 when animations are enabled, tracked by microsoft-ui-xaml#779");
                return;
            }

            // Example of how to include debug tracing in an ApiTests.ItemsRepeater test's output.
            // using (PrivateLoggingHelper privateLoggingHelper = new PrivateLoggingHelper("Repeater"))
            // {
            ItemsRepeater    rootRepeater = null;
            ScrollViewer     scrollViewer = null;
            ManualResetEvent viewChanged  = new ManualResetEvent(false);

            RunOnUIThread.Execute(() =>
            {
                var anchorProvider = (ItemsRepeaterScrollHost)XamlReader.Load(
                    @"<controls:ItemsRepeaterScrollHost Width='400' Height='600'
                        xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                        xmlns:controls='using:Microsoft.UI.Xaml.Controls'>
                    <controls:ItemsRepeaterScrollHost.Resources>
                        <DataTemplate x:Key='ItemTemplate' >
                            <TextBlock Text='{Binding}' />
                        </DataTemplate>
                        <DataTemplate x:Key='GroupTemplate'>
                            <StackPanel>
                                <TextBlock Text='{Binding}' />
                                <controls:ItemsRepeater ItemTemplate='{StaticResource ItemTemplate}' ItemsSource='{Binding}' VerticalCacheLength='0'/>
                            </StackPanel>
                        </DataTemplate>
                    </controls:ItemsRepeaterScrollHost.Resources>
                    <ScrollViewer x:Name='scrollviewer'>
                        <controls:ItemsRepeater x:Name='rootRepeater' ItemTemplate='{StaticResource GroupTemplate}' VerticalCacheLength='0' />
                    </ScrollViewer>
                </controls:ItemsRepeaterScrollHost>");

                rootRepeater              = (ItemsRepeater)anchorProvider.FindName("rootRepeater");
                rootRepeater.SizeChanged += (sender, args) =>
                {
                    Log.Comment($"SizeChanged: Size=({rootRepeater.ActualWidth} x {rootRepeater.ActualHeight})");
                };

                scrollViewer = (ScrollViewer)anchorProvider.FindName("scrollviewer");
                scrollViewer.ViewChanging += (sender, args) =>
                {
                    Log.Comment($"ViewChanging: Next VerticalOffset={args.NextView.VerticalOffset}, Final VerticalOffset={args.FinalView.VerticalOffset}");
                };
                scrollViewer.ViewChanged += (sender, args) =>
                {
                    Log.Comment($"ViewChanged: VerticalOffset={scrollViewer.VerticalOffset}, IsIntermediate={args.IsIntermediate}");

                    if (!args.IsIntermediate)
                    {
                        viewChanged.Set();
                    }
                };

                var itemsSource = new ObservableCollection <ObservableCollection <int> >();
                for (int i = 0; i < 100; i++)
                {
                    itemsSource.Add(new ObservableCollection <int>(Enumerable.Range(0, 5)));
                }
                ;

                rootRepeater.ItemsSource = itemsSource;
                Content = anchorProvider;
            });

            // scroll down several times to cause recycling of elements
            for (int i = 1; i < 10; i++)
            {
                IdleSynchronizer.Wait();
                RunOnUIThread.Execute(() =>
                {
                    Log.Comment($"Size=({rootRepeater.ActualWidth} x {rootRepeater.ActualHeight})");
                    Log.Comment($"ChangeView(VerticalOffset={i * 200})");
                    scrollViewer.ChangeView(null, i * 200, null, disableAnimation);
                });

                Log.Comment("Waiting for view change completion...");
                Verify.IsTrue(viewChanged.WaitOne(DefaultWaitTimeInMS));
                viewChanged.Reset();
                Log.Comment("View change completed");

                RunOnUIThread.Execute(() =>
                {
                    Verify.AreEqual(i * 200, scrollViewer.VerticalOffset);
                });
            }
            // }
        }
Ejemplo n.º 3
0
        public void VerifyStoreScenarioCache()
        {
            ItemsRepeater rootRepeater = null;

            RunOnUIThread.Execute(() =>
            {
                var scrollhost = (ItemsRepeaterScrollHost)XamlReader.Load(
                    @" <controls:ItemsRepeaterScrollHost Width='400' Height='200'
                        xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                        xmlns:controls='using:Microsoft.UI.Xaml.Controls'>
                        <controls:ItemsRepeaterScrollHost.Resources>
                            <DataTemplate x:Key='ItemTemplate' >
                                <TextBlock Text='{Binding}' Height='100' Width='100'/>
                            </DataTemplate>
                            <DataTemplate x:Key='GroupTemplate'>
                                <StackPanel>
                                    <TextBlock Text='{Binding}' />
                                    <controls:ItemsRepeaterScrollHost>
                                        <ScrollViewer HorizontalScrollMode='Enabled' VerticalScrollMode='Disabled' HorizontalScrollBarVisibility='Auto' VerticalScrollBarVisibility='Hidden'>
                                            <controls:ItemsRepeater ItemTemplate='{StaticResource ItemTemplate}' ItemsSource='{Binding}'>
                                                <controls:ItemsRepeater.Layout>
                                                    <controls:StackLayout Orientation='Horizontal' />
                                                </controls:ItemsRepeater.Layout>
                                            </controls:ItemsRepeater>
                                        </ScrollViewer>
                                    </controls:ItemsRepeaterScrollHost>
                                </StackPanel>
                            </DataTemplate>
                        </controls:ItemsRepeaterScrollHost.Resources>
                        <ScrollViewer x:Name='scrollviewer'>
                            <controls:ItemsRepeater x:Name='rootRepeater' ItemTemplate='{StaticResource GroupTemplate}'/>
                        </ScrollViewer>
                    </controls:ItemsRepeaterScrollHost>");

                rootRepeater = (ItemsRepeater)scrollhost.FindName("rootRepeater");

                List <List <int> > items = new List <List <int> >();
                for (int i = 0; i < 100; i++)
                {
                    items.Add(Enumerable.Range(0, 4).ToList());
                }
                rootRepeater.ItemsSource = items;
                Content = scrollhost;
            });

            IdleSynchronizer.Wait();

            // Verify that first items outside the visible range but in the realized range
            // for the inner of the nested repeaters are realized.
            RunOnUIThread.Execute(() =>
            {
                // Group2 will be outside the visible range but within the realized range.
                var group2 = rootRepeater.TryGetElement(2) as StackPanel;
                Verify.IsNotNull(group2);

                var group2Repeater = ((ItemsRepeaterScrollHost)group2.Children[1]).ScrollViewer.Content as ItemsRepeater;
                Verify.IsNotNull(group2Repeater);

                Verify.IsNotNull(group2Repeater.TryGetElement(0));
            });
        }
Ejemplo n.º 4
0
        public void ValidateDataTemplateSelectorAsItemTemplate()
        {
            RunOnUIThread.Execute(() =>
            {
                var dataTemplateOdd = (DataTemplate)XamlReader.Load(
                    @"<DataTemplate  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                            <TextBlock Text='{Binding}' Height='30' />
                        </DataTemplate>");
                var dataTemplateEven = (DataTemplate)XamlReader.Load(
                    @"<DataTemplate  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                            <TextBlock Text='{Binding}' Height='40' />
                        </DataTemplate>");
                ItemsRepeater repeater = null;
                const int numItems     = 10;
                var selector           = new MySelector()
                {
                    TemplateOdd  = dataTemplateOdd,
                    TemplateEven = dataTemplateEven
                };

                Content = CreateAndInitializeRepeater
                          (
                    itemsSource: Enumerable.Range(0, numItems),
                    elementFactory: selector,
                    layout: new StackLayout(),
                    repeater: ref repeater
                          );

                Content.UpdateLayout();
                Verify.AreEqual(numItems, VisualTreeHelper.GetChildrenCount(repeater));
                for (int i = 0; i < numItems; i++)
                {
                    var element = (TextBlock)repeater.TryGetElement(i);
                    Verify.AreEqual(i.ToString(), element.Text);
                    Verify.AreEqual(i % 2 == 0 ? 40 : 30, element.Height);
                }

                repeater.ItemsSource = null;
                Content.UpdateLayout();

                // In versions below RS5 we faked the recycling behaivor on data template
                // so we can get to the recycle pool that we addded internally in ItemsRepeater.
                if (PlatformConfiguration.IsOSVersionLessThan(OSVersion.Redstone5))
                {
                    // All the created items should be in the recycle pool now.
                    var oddPool     = RecyclePool.GetPoolInstance(dataTemplateOdd);
                    var oddElements = GetAllElementsFromPool(oddPool);
                    Verify.AreEqual(5, oddElements.Count);
                    foreach (var element in oddElements)
                    {
                        Verify.AreEqual(30, ((TextBlock)element).Height);
                    }

                    var evenPool     = RecyclePool.GetPoolInstance(dataTemplateEven);
                    var evenElements = GetAllElementsFromPool(evenPool);
                    Verify.AreEqual(5, evenElements.Count);
                    foreach (var element in evenElements)
                    {
                        Verify.AreEqual(40, ((TextBlock)element).Height);
                    }
                }
            });
        }
Ejemplo n.º 5
0
        public bool OpenEncryptedDocument(string xpsFile)
        {
            // Check to see if the document is encrypted.
            // If not encrypted, use OpenDocument().
            if (!EncryptedPackageEnvelope.IsEncryptedPackageEnvelope(xpsFile))
                return OpenDocument(xpsFile);

            ShowStatus("Opening encrypted '" + Filename(xpsFile) + "'");

            // Get the ID of the current user log-in.
            string currentUserId;
            try
                { currentUserId = GetDefaultWindowsUserName(); }
            catch
                { currentUserId = null; }
            if (currentUserId == null)
            {
                MessageBox.Show("No valid user ID available", "Invalid User ID",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                ShowStatus("   No valid user ID available.");
                return false;
            }

            ShowStatus("   Current user ID:  '" + currentUserId + "'");
            ShowStatus("   Using " + _authentication + " authentication.");
            ShowStatus("   Checking rights list for user:\n       " +
                           currentUserId);
            ShowStatus("   Initializing the environment.");

            try
            {
                string applicationManifest = "<manifest></manifest>";
                if (File.Exists("rvc.xml"))
                {
                    ShowStatus("   Reading manifest 'rvc.xml'.");
                    StreamReader manifestReader = File.OpenText("rvc.xml");
                    applicationManifest = manifestReader.ReadToEnd();
                }

                //<SnippetRmPkgViewSecEnv>
                ShowStatus("   Initiating SecureEnvironment as user: \n       " +
                    currentUserId + " [" + _authentication + "]");
                if (SecureEnvironment.IsUserActivated(
                    new ContentUser(currentUserId, _authentication)))
                {
                    ShowStatus("   User is already activated.");
                    _secureEnv = SecureEnvironment.Create(applicationManifest,
                                    new ContentUser(currentUserId, _authentication));
                }
                else // if user is not yet activated.
                {
                    ShowStatus("   User is NOT activated,\n       activating now....");
                    // If using the current Windows user, no credentials are
                    // required and we can use UserActivationMode.Permanent.
                    _secureEnv = SecureEnvironment.Create(applicationManifest,
                                    _authentication, UserActivationMode.Permanent);

                    // If not using the current Windows user, use
                    // UserActivationMode.Temporary to display the Windows
                    // credentials pop-up window.
                    ///_secureEnv = SecureEnvironment.Create(applicationManifest,
                    ///     a_authentication, UserActivationMode.Temporary);
                }
                ShowStatus("   Created SecureEnvironment for user:\n       " +
                    _secureEnv.User.Name +
                    " [" + _secureEnv.User.AuthenticationType + "]");
                //</SnippetRmPkgViewSecEnv>

                //<SnippetRmPkgViewOpenPkg>
                ShowStatus("   Opening the encrypted Package.");
                EncryptedPackageEnvelope ePackage =
                    EncryptedPackageEnvelope.Open(xpsFile, FileAccess.ReadWrite);
                RightsManagementInformation rmi =
                    ePackage.RightsManagementInformation;

                ShowStatus("   Looking for an embedded UseLicense for user:\n       " +
                           currentUserId + " [" + _authentication + "]");
                UseLicense useLicense =
                    rmi.LoadUseLicense(
                        new ContentUser(currentUserId, _authentication));

                ReadOnlyCollection<ContentGrant> grants;
                if (useLicense == null)
                {
                    ShowStatus("   No Embedded UseLicense found.\n       " +
                               "Attempting to acqure UseLicnese\n       " +
                               "from the PublishLicense.");
                    PublishLicense pubLicense = rmi.LoadPublishLicense();

                    ShowStatus("   Referral information:");

                    if (pubLicense.ReferralInfoName == null)
                        ShowStatus("       Name: (null)");
                    else
                        ShowStatus("       Name: " + pubLicense.ReferralInfoName);

                    if (pubLicense.ReferralInfoUri == null)
                        ShowStatus("    Uri: (null)");
                    else
                        ShowStatus("    Uri: " +
                            pubLicense.ReferralInfoUri.ToString());

                    useLicense = pubLicense.AcquireUseLicense(_secureEnv);
                    if (useLicense == null)
                    {
                        ShowStatus("   User DOES NOT HAVE RIGHTS\n       " +
                            "to access this document!");
                        return false;
                    }
                }// end:if (useLicense == null)
                ShowStatus("   UseLicense acquired.");
                //</SnippetRmPkgViewOpenPkg>

                //<SnippetRmPkgViewBind>
                ShowStatus("   Binding UseLicense with the SecureEnvironment" +
                         "\n       to obtain the CryptoProvider.");
                rmi.CryptoProvider = useLicense.Bind(_secureEnv);

                ShowStatus("   Obtaining BoundGrants.");
                grants = rmi.CryptoProvider.BoundGrants;

                // You can access the Package via GetPackage() at this point.

                rightsBlock.Text = "GRANTS LIST\n-----------\n";
                foreach (ContentGrant grant in grants)
                {
                    rightsBlock.Text += "USER  :"******" [" +
                        grant.User.AuthenticationType + "]\n";
                    rightsBlock.Text += "RIGHT :" + grant.Right.ToString()+"\n";
                    rightsBlock.Text += "    From:  " + grant.ValidFrom + "\n";
                    rightsBlock.Text += "    Until: " + grant.ValidUntil + "\n";
                }
                //</SnippetRmPkgViewBind>

                //<SnippetRmPkgViewDecrypt>
                if (rmi.CryptoProvider.CanDecrypt == true)
                    ShowStatus("   Decryption granted.");
                else
                    ShowStatus("   CANNOT DECRYPT!");

                ShowStatus("   Getting the Package from\n" +
                           "      the EncryptedPackage.");
                _xpsPackage = ePackage.GetPackage();
                if (_xpsPackage == null)
                {
                    MessageBox.Show("Unable to get Package.");
                    return false;
                }

                // Set a PackageStore Uri reference for the encrypted stream.
                // ("sdk://packLocation" is a pseudo URI used by
                //  PackUriHelper.Create to define the parserContext.BaseURI
                //  that XamlReader uses to access the encrypted data stream.)
                Uri packageUri = new Uri(@"sdk://packLocation", UriKind.Absolute);
                // Add the URI package
                PackageStore.AddPackage(packageUri, _xpsPackage);
                // Determine the starting part for the package.
                PackagePart startingPart = GetPackageStartingPart(_xpsPackage);

                // Set the DocViewer.Document property.
                ShowStatus("   Opening in DocumentViewer.");
                ParserContext parserContext = new ParserContext();
                parserContext.BaseUri = PackUriHelper.Create(
                                            packageUri, startingPart.Uri);
                parserContext.XamlTypeMapper = XamlTypeMapper.DefaultMapper;
                DocViewer.Document = XamlReader.Load(
                    startingPart.GetStream(), parserContext)
                        as IDocumentPaginatorSource;

                // Enable document menu controls.
                menuFileClose.IsEnabled = true;
                menuFilePrint.IsEnabled = true;
                menuViewIncreaseZoom.IsEnabled = true;
                menuViewDecreaseZoom.IsEnabled = true;

                // Give the DocumentViewer focus.
                DocViewer.Focus();
                //</SnippetRmPkgViewDecrypt>
            }// end:try
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                    ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                    "Exception",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            this.Title = "RightsManagedPackageViewer SDK Sample - " +
                         Filename(xpsFile) + " (encrypted)";
            return true;
        }// end:OpenEncryptedDocument()
Ejemplo n.º 6
0
        // Add Connector
        private ConnectorViewModel Connect(NodeViewModel headnode, NodeViewModel tailnode, NodePort headport = null, NodePort tailport = null, ConnectorViewModel connector = null, ConnectorPort connectorheadport = null, ConnectorPort connectortailport = null, String label1 = null, String label2 = null, Style style = null, Thickness margin = new Thickness())
        {
            ConnectorViewModel conn = new ConnectorViewModel();

            conn.SourceNode = headnode;
            conn.TargetNode = tailnode;
            if (label2 != null)
            {
                //To Represent Annotation Property
                conn.Annotations = new ObservableCollection <IAnnotation>()
                {
                    new AnnotationEditorViewModel()
                    {
                        Content      = label2,
                        WrapText     = TextWrapping.Wrap,
                        UnitWidth    = 150,
                        Margin       = margin,
                        ReadOnly     = true,
                        ViewTemplate = XamlReader.Load(SequenceDiagramTemplate.vTemplate) as DataTemplate,
                        EditTemplate = XamlReader.Load(SequenceDiagramTemplate.eTemplate) as DataTemplate,
                        //ViewTemplate=this.Resources["viewtemplate1"] as DataTemplate,
                        //EditTemplate=this.Resources["edittemplate"] as DataTemplate
                    }
                };
            }

            if (headport != null)
            {
                conn.SourcePort = headport;
            }
            else
            {
                conn.SourcePort = connectorheadport;
            }

            if (tailport != null)
            {
                conn.TargetPort = tailport;
            }
            else
            {
                conn.TargetPort = connectortailport;
            }

            if (tailnode != null)
            {
                conn.SourceConnector = connector;
            }
            else
            {
                conn.TargetConnector = connector;
            }

            conn.TargetDecoratorStyle = this.Resources["DecoratorStyle"] as Style;

            if ((label1 == "c3") || (label1 == "c4") || (label1 == "c5") || (label1 == "c6"))
            {
                conn.TargetDecorator = null;

                conn.TargetDecoratorStyle = null;
            }

            if (style != null)
            {
                conn.ConnectorGeometryStyle = style;
            }
            //Constraints used to enable/disable connector selection
            conn.Constraints = conn.Constraints & ~ConnectorConstraints.Selectable;
            diagramcontrol.DefaultConnectorType = ConnectorType.Line;
            (diagramcontrol.Connectors as ICollection <ConnectorViewModel>).Add(conn);
            return(conn);
        }
Ejemplo n.º 7
0
        public async Task ValidateXBindWithoutPhasing()
        {
            ItemsRepeater repeater  = null;
            int           numPhases = 1;   // Just Phase 0 for x:Bind
            bool          ElementLoadedCompleted = false;

            RunOnUIThread.Execute(() =>
            {
                var itemTemplate = (DataTemplate)XamlReader.Load(
                    @"<DataTemplate  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                            <Button Width='100' Height='100'/>
                        </DataTemplate>");
                repeater = new ItemsRepeater()
                {
                    ItemsSource  = Enumerable.Range(0, 10),
                    ItemTemplate = new CustomElementFactory(numPhases),
                    Layout       = new StackLayout(),
                };

                repeater.ElementPrepared += (sender, args) =>
                {
                    if (args.Index == expectedLastRealizedIndex)
                    {
                        Log.Comment("Item 8 Created!");
                        ElementLoadedCompleted = true;
                    }
                };

                Content = new ItemsRepeaterScrollHost()
                {
                    Width        = 400,
                    Height       = 400,
                    ScrollViewer = new ScrollViewer
                    {
                        Content = repeater
                    }
                };
            });

            await TestServices.WindowHelper.WaitFor(() => ElementLoadedCompleted, 2000);

            if (ElementLoadedCompleted)
            {
                RunOnUIThread.Execute(() =>
                {
                    var calls = ElementPhasingManager.ProcessedCalls;

                    Verify.AreEqual(calls.Count, 9);
                    calls[0].RemoveAt(0);                     // Remove the create we did for first measure.
                    foreach (var index in calls.Keys)
                    {
                        var phases = calls[index];
                        Verify.AreEqual(1, phases.Count);                         // Just phase 0
                    }

                    ElementPhasingManager.ProcessedCalls.Clear();
                });
            }
            else
            {
                Verify.Fail("Failed on waiting on build tree.");
            }
        }
Ejemplo n.º 8
0
        private object CloneVisual(object o)
        {
            string xamlCode = XamlWriter.Save(o).Replace("Name=", "Tag=");

            return(XamlReader.Load(new System.Xml.XmlTextReader(new StringReader(xamlCode))));
        }
 public EurekaSettingsDialog()
 {
     XamlReader.Load(this);
 }
Ejemplo n.º 10
0
        private Model3DGroup GetModel(GameObject newObject, String resourceName, String fileExt)
        {
            Transform3DGroup     TransformGroup     = new Transform3DGroup();
            TranslateTransform3D TranslateTransform = new TranslateTransform3D(newObject.Position * ViewportScalingFactor);
            ModelVisual3D        newModel           = null;
            Model3DGroup         newGroup           = new Model3DGroup();
            string assemblyLocation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            string resourceBase = "pack://*****:*****@"\GameAssets\" + resourceName);
                break;

            case "3ds":
                ModelImporter importer = new ModelImporter();
                newGroup = importer.Load(assemblyLocation + @"\GameAssets\" + resourceName);
                foreach (var material in newObject.Model.Materials)
                {
                    MaterialGroup materialGroup = new MaterialGroup();

                    Brush materialBrush = new SolidColorBrush(material.DiffuseColor);
                    materialBrush.Opacity = material.Opacity;
                    materialGroup.Children.Add(MaterialHelper.CreateMaterial(materialBrush, material.SpecularPower));

                    if (!String.IsNullOrWhiteSpace(material.TextureFile))
                    {
                        if (File.Exists(assemblyLocation + @"\GameAssets\" + material.TextureFile))
                        {
                            var texture = MaterialHelper.CreateImageMaterial(new BitmapImage(new Uri(assemblyLocation + @"\GameAssets\" + material.TextureFile, UriKind.Relative)), material.Opacity);
                            materialGroup.Children.Add(texture);
                        }
                    }

                    var specular = new SpecularMaterial();
                    specular.SpecularPower = material.SpecularPower;
                    specular.Color         = material.SpecularColor;

                    var emissive = new EmissiveMaterial();
                    emissive.Color = material.EmissiveColor;

                    materialGroup.Children.Add(specular);
                    materialGroup.Children.Add(emissive);

                    ((GeometryModel3D)newGroup.Children[material.MeshIndex]).Material = materialGroup;
                }
                break;
            }

#if DEBUG
            if (resourceName.IndexOf("Rink") < 0)
            {
                HelixToolkit.Wpf.MeshBuilder meshBuilder = new MeshBuilder();

                var boundingRect = newGroup.Bounds;
                meshBuilder.AddBoundingBox(boundingRect, 3);
            }
#endif
            double           CenterX        = newGroup.Bounds.SizeX / 2;
            double           CenterY        = newGroup.Bounds.SizeY / 2;
            double           CenterZ        = newGroup.Bounds.SizeZ / 2;
            ScaleTransform3D ScaleTransform = new ScaleTransform3D(newObject.Scale.X, newObject.Scale.Y, newObject.Scale.Z, CenterX, CenterY, CenterZ);

            TransformGroup.Children.Add(TranslateTransform);
            TransformGroup.Children.Add(ScaleTransform);

            newGroup.Transform = TransformGroup;

            if (newObject.ApplyPhysics)
            {
                var rinkBounds = _gameObjects.Where(x => x.Key.Model.IsGameWorld).First().Value.Content.Bounds;
                TranslateTransform.OffsetZ -= (newGroup.Bounds.Z - rinkBounds.Z);
            }
            newObject.Bounds = newGroup.Bounds;

            return(newGroup);
        }
Ejemplo n.º 11
0
        public void CanBringIntoViewElements()
        {
            if (!PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone5))
            {
                // Note that UIElement.BringIntoViewRequested was added in RS4, and effective viewport was added in RS5
                Log.Warning("Skipping since version is less than RS5 and effective viewport feature is not available below RS5");
                return;
            }

            Scroller      scroller         = null;
            ItemsRepeater repeater         = null;
            var           rootLoadedEvent  = new AutoResetEvent(initialState: false);
            var           viewChangedEvent = new AutoResetEvent(initialState: false);
            var           waitingForIndex  = -1;
            var           indexRealized    = new AutoResetEvent(initialState: false);

            var viewChangedOffsets = new List <double>();

            RunOnUIThread.Execute(() =>
            {
                var lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam laoreet erat vel massa rutrum, eget mollis massa vulputate. Vivamus semper augue leo, eget faucibus nulla mattis nec. Donec scelerisque lacus at dui ultricies, eget auctor ipsum placerat. Integer aliquet libero sed nisi eleifend, nec rutrum arcu lacinia. Sed a sem et ante gravida congue sit amet ut augue. Donec quis pellentesque urna, non finibus metus. Proin sed ornare tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam laoreet erat vel massa rutrum, eget mollis massa vulputate. Vivamus semper augue leo, eget faucibus nulla mattis nec. Donec scelerisque lacus at dui ultricies, eget auctor ipsum placerat. Integer aliquet libero sed nisi eleifend, nec rutrum arcu lacinia. Sed a sem et ante gravida congue sit amet ut augue. Donec quis pellentesque urna, non finibus metus. Proin sed ornare tellus.";
                var root  = (Grid)XamlReader.Load(TestUtilities.ProcessTestXamlForRepo(
                                                      @"<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
                             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                             xmlns:controls='using:Microsoft.UI.Xaml.Controls' 
                             xmlns:primitives='using:Microsoft.UI.Xaml.Controls.Primitives'> 
                         <Grid.Resources>
                           <controls:StackLayout x:Name='VerticalStackLayout' />
                           <controls:RecyclingElementFactory x:Key='ElementFactory'>
                             <controls:RecyclingElementFactory.RecyclePool>
                               <controls:RecyclePool />
                             </controls:RecyclingElementFactory.RecyclePool>
                             <DataTemplate x:Key='ItemTemplate'>
                               <Border Background='LightGray' Margin ='5'>
                                 <TextBlock Text='{Binding}' TextWrapping='WrapWholeWords' />
                               </Border>
                             </DataTemplate>
                           </controls:RecyclingElementFactory>
                         </Grid.Resources>
                         <primitives:Scroller x:Name='Scroller' Width='400' Height='600' ContentOrientation='Vertical' Background='Gray'>
                           <controls:ItemsRepeater
                             x:Name='ItemsRepeater'
                             ItemTemplate='{StaticResource ElementFactory}'
                             Layout='{StaticResource VerticalStackLayout}'
                             HorizontalCacheLength='0'
                             VerticalCacheLength='0' />
                         </primitives:Scroller>
                       </Grid>"));

                var elementFactory = (RecyclingElementFactory)root.Resources["ElementFactory"];
                scroller           = (Scroller)root.FindName("Scroller");
                repeater           = (ItemsRepeater)root.FindName("ItemsRepeater");

                repeater.ElementPrepared += (sender, args) =>
                {
                    Log.Comment($"Realized index: {args.Index} Wating for index {waitingForIndex}");
                    if (args.Index == waitingForIndex)
                    {
                        indexRealized.Set();
                    }
                };

                var items = Enumerable.Range(0, 400).Select(i => string.Format("{0}: {1}", i, lorem.Substring(0, 250)));

                repeater.ItemsSource = items;

                scroller.ViewChanged += (o, e) =>
                {
                    Log.Comment("Scroller.ViewChanged: VerticalOffset=" + scroller.VerticalOffset);
                    viewChangedOffsets.Add(scroller.VerticalOffset);
                    viewChangedEvent.Set();
                };

                scroller.BringingIntoView += (o, e) =>
                {
                    Log.Comment("Scroller.BringingIntoView:");
                    Log.Comment("TargetVerticalOffset=" + e.TargetVerticalOffset);
                    Log.Comment("RequestEventArgs.AnimationDesired=" + e.RequestEventArgs.AnimationDesired);
                    Log.Comment("RequestEventArgs.Handled=" + e.RequestEventArgs.Handled);
                    Log.Comment("RequestEventArgs.VerticalAlignmentRatio=" + e.RequestEventArgs.VerticalAlignmentRatio);
                    Log.Comment("RequestEventArgs.VerticalOffset=" + e.RequestEventArgs.VerticalOffset);
                    Log.Comment("RequestEventArgs.TargetRect=" + e.RequestEventArgs.TargetRect);
                };

                scroller.EffectiveViewportChanged += (o, args) =>
                {
                    Log.Comment("Scroller.EffectiveViewportChanged: VerticalOffset=" + scroller.VerticalOffset);
                };

                root.Loaded += delegate {
                    rootLoadedEvent.Set();
                };

                Content = root;
            });
            Verify.IsTrue(rootLoadedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();

            RunOnUIThread.Execute(() =>
            {
                waitingForIndex = 101;
                indexRealized.Reset();
                repeater.GetOrCreateElement(100).StartBringIntoView(new BringIntoViewOptions {
                    VerticalAlignmentRatio = 0.0
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            Verify.AreEqual(1, viewChangedOffsets.Count);
            viewChangedOffsets.Clear();
            Verify.IsTrue(indexRealized.WaitOne(DefaultWaitTimeInMS));

            ValidateRealizedRange(repeater, 99, 106);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Scroll into view item 105 (already realized) w/ animation.");
                waitingForIndex = 99;
                repeater.TryGetElement(105).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.5,
                    AnimationDesired       = true
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            Verify.IsLessThanOrEqual(1, viewChangedOffsets.Count);
            viewChangedOffsets.Clear();
            ValidateRealizedRange(repeater, 101, 109);

            RunOnUIThread.Execute(() =>
            {
                Log.Comment("Scroll item 0 to the top w/ animation and 0.5 vertical alignment.");
                waitingForIndex = 1;
                indexRealized.Reset();
                repeater.GetOrCreateElement(0).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.5,
                    AnimationDesired       = true
                });
            });

            Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            viewChangedOffsets.Clear();
            Verify.IsTrue(indexRealized.WaitOne(DefaultWaitTimeInMS));

            // Test Reliability fix. If offset is not 0 yet, give
            // some more time for the animation to settle down.
            double verticalOffset = 0;

            RunOnUIThread.Execute(() =>
            {
                verticalOffset = scroller.VerticalOffset;
            });

            if (verticalOffset != 0)
            {
                Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
                IdleSynchronizer.Wait();
                viewChangedOffsets.Clear();
            }

            ValidateRealizedRange(repeater, 0, 6);

            RunOnUIThread.Execute(() =>
            {
                // You can't align the first group in the middle obviously.
                Verify.AreEqual(0, scroller.VerticalOffset);

                Log.Comment("Scroll to item 20.");
                waitingForIndex = 21;
                indexRealized.Reset();
                repeater.GetOrCreateElement(20).StartBringIntoView(new BringIntoViewOptions
                {
                    VerticalAlignmentRatio = 0.0
                });
                repeater.UpdateLayout();
            });

            Verify.IsTrue(viewChangedEvent.WaitOne(DefaultWaitTimeInMS));
            IdleSynchronizer.Wait();
            Verify.IsTrue(indexRealized.WaitOne(DefaultWaitTimeInMS));

            ValidateRealizedRange(repeater, 19, 26);
        }
Ejemplo n.º 12
0
        public Task <bool> LoadDocumentAsync(string svgFilePath)
        {
            if (_isLoadingDrawing || string.IsNullOrWhiteSpace(svgFilePath))
            {
                return(Task.FromResult <bool>(false));
            }
            Uri uriSvgPath = new Uri(svgFilePath);

            if (uriSvgPath.IsFile && !File.Exists(svgFilePath))
            {
                return(Task.FromResult <bool>(false));
            }

            string fileExt = Path.GetExtension(svgFilePath);

            if (!(string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) ||
                  string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase)))
            {
                _svgFilePath = null;
                return(Task.FromResult <bool>(false));
            }

            _isLoadingDrawing = true;

            this.UnloadDocument(true);

            DirectoryInfo workingDir = _workingDir;

            if (_directoryInfo != null)
            {
                workingDir = _directoryInfo;
            }

            _svgFilePath = svgFilePath;
            _saveXaml    = _optionSettings.ShowOutputFile;

            _embeddedImageVisitor.SaveImages    = !_wpfSettings.IncludeRuntime;
            _embeddedImageVisitor.SaveDirectory = _drawingDir;
            _wpfSettings.Visitors.ImageVisitor  = _embeddedImageVisitor;

            if (_fileReader == null)
            {
                _fileReader          = new FileSvgReader(_wpfSettings);
                _fileReader.SaveXaml = _saveXaml;
                _fileReader.SaveZaml = false;
            }

            var drawingStream = new MemoryStream();

            // Get the UI thread's context
            var context = TaskScheduler.FromCurrentSynchronizationContext();

            return(Task <bool> .Factory.StartNew(() =>
            {
//                var saveXaml = _fileReader.SaveXaml;
//                _fileReader.SaveXaml = true; // For threaded, we will save to avoid loading issue later...
                DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir);
//                _fileReader.SaveXaml = saveXaml;
                _drawingDocument = _fileReader.DrawingDocument;
                if (drawing != null)
                {
                    XamlWriter.Save(drawing, drawingStream);
                    drawingStream.Seek(0, SeekOrigin.Begin);

                    return true;
                }
                _svgFilePath = null;
                return false;
            }).ContinueWith((t) => {
                try
                {
                    if (!t.Result)
                    {
                        _isLoadingDrawing = false;
                        _svgFilePath = null;
                        return false;
                    }
                    if (drawingStream.Length != 0)
                    {
                        DrawingGroup drawing = (DrawingGroup)XamlReader.Load(drawingStream);

                        svgViewer.UnloadDiagrams();
                        svgViewer.RenderDiagrams(drawing);

                        Rect bounds = svgViewer.Bounds;

                        if (bounds.IsEmpty)
                        {
                            bounds = new Rect(0, 0, svgViewer.ActualWidth, svgViewer.ActualHeight);
                        }

                        zoomPanControl.AnimatedZoomTo(bounds);
                        CommandManager.InvalidateRequerySuggested();

                        // The drawing changed, update the source...
                        _fileReader.Drawing = drawing;
                    }

                    _isLoadingDrawing = false;

                    return true;
                }
                catch
                {
                    _isLoadingDrawing = false;
                    throw;
                }
            }, context));
        }
Ejemplo n.º 13
0
        public void ValidateNonVirtualLayoutDoesNotGetMeasuredForViewportChanges()
        {
            RunOnUIThread.Execute(() =>
            {
                int measureCount = 0;
                int arrangeCount = 0;
                var repeater     = new ItemsRepeater();

                // with a non virtualizing layout, repeater will just
                // run layout once.
                repeater.Layout = new MockNonVirtualizingLayout()
                {
                    MeasureLayoutFunc = (size, context) =>
                    {
                        measureCount++;
                        return(new Size(100, 800));
                    },
                    ArrangeLayoutFunc = (size, context) =>
                    {
                        arrangeCount++;
                        return(new Size(100, 800));
                    }
                };

                repeater.ItemsSource  = Enumerable.Range(0, 10);
                repeater.ItemTemplate = (DataTemplate)XamlReader.Load(
                    @"<DataTemplate  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
						 <Button Content='{Binding}' Height='100' />
					</DataTemplate>"                    );

                Content = new ScrollViewer()
                {
                    Content = repeater
                };
                Content.UpdateLayout();

                Verify.AreEqual(1, measureCount);
                Verify.AreEqual(1, arrangeCount);

                measureCount = 0;
                arrangeCount = 0;

                // Once we switch to a virtualizing layout we should
                // get at least two passes to update the viewport.
                repeater.Layout = new MockVirtualizingLayout()
                {
                    MeasureLayoutFunc = (size, context) =>
                    {
                        measureCount++;
                        return(new Size(100, 800));
                    },
                    ArrangeLayoutFunc = (size, context) =>
                    {
                        arrangeCount++;
                        return(new Size(100, 800));
                    }
                };

                Content.UpdateLayout();

                Verify.IsGreaterThan(measureCount, 1);
                Verify.IsGreaterThan(arrangeCount, 1);
            });
        }
Ejemplo n.º 14
0
 public XamlImageInfo(Stream stream)
 {
     _image = XamlReader.Load(stream);
 }
Ejemplo n.º 15
0
Archivo: Skin.cs Proyecto: Starwer/Lime
        // --------------------------------------------------------------------------------------------------
        #region ctors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="skinName">Name of the skin</param>
        /// <param name="loadParam">Load the parameters from user-config</param>
        public Skin(string skinName, bool loadParam = true)
        {
            LimeMsg.Debug("Skin: constructor");
            LimeLib.LifeTrace(this);

            // Invalidate this skin
            Name = null;

            // Prepare to populate new set of Skin-parameters
            SkinParam.Clear();

            // Load Skin list
            LoadSkinList();

            // Load resource
            ResourceDictionary resources = null;

            if (!string.IsNullOrEmpty(skinName))
            {
                // Load Xaml here
                string dir = About.SkinsPath;
#if DEBUG
                // Debug Only: bypass local skins to use the one in the project directly
                if (!string.IsNullOrEmpty(Global.DebugProjectDir))
                {
                    dir = Path.Combine(Global.DebugProjectDir, "Skins");
                }
#endif

                dir = Path.Combine(dir, skinName);
                dir = LimeLib.ResolvePath(dir);

                string path = Path.Combine(dir, skinName + ".xaml");
                path = LimeLib.ResolvePath(path);

                // Parse theXaml. This may fail if there is a file/Xaml error
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    // Get the root element, which must be a ResourceDictionary
                    resources = (ResourceDictionary)XamlReader.Load(fs);
                }

                // File change monitoring
                if (Global.User.SkinAutoRefresh && Global.User.DevMode)
                {
                    LimeMsg.Debug("Skin: constructor: Watch changes on {0}", dir);
                    _Watch = new FileSystemWatcher
                    {
                        Path = dir,
                        IncludeSubdirectories = false,
                        Filter = ""
                    };

                    _Watch.Changed += new FileSystemEventHandler(OnXamlFileChanged);

                    _Watch.EnableRaisingEvents = true;
                }
                else
                {
                    _Watch = null;
                }
            }

            // Freeze the Parameters
            SkinParam.Lock();


            // Retrieve/check Required resources
            double version = 0.0;
            try
            {
                MetaAuthor      = (string)resources["MetaAuthor"];
                MetaContact     = (string)resources["MetaContact"];
                MetaWebsite     = (string)resources["MetaWebsite"];
                MetaDescription = (string)resources["MetaDescription"];
                version         = (double)resources["MetaLimeVersion"];
            }
            catch (ResourceReferenceKeyNotFoundException e)
            {
                LimeMsg.Error("ErrSkinParMiss", e.Key);
            }
            catch
            {
                LimeMsg.Error("ErrSkinFormat");
            }

            if (version > 0.5)
            {
                // Successfull
                if (version > About.versionNum)
                {
                    LimeMsg.Error("ErrSkinVersion", skinName, About.name, version);
                }
            }

            // Process the Skin parameters
            var parList = SkinParam.List.ToArray();
            SkinParam.Clear();

            // Assign the key of the resource-dictonary to the SkinParam Ident.
            foreach (var key in resources.Keys)
            {
                if (key is string skey && resources[key] is SkinParam res)
                {
                    res.Ident = skey;

                    // Exclude Empty elements
                    if (res.Content == null && res.Name == null)
                    {
                        res.Visible = false;
                    }
                }
            }

            // Retrieve special parameters
            IconBigSize   = Array.Find(parList, x => x.Ident == "ParamIconBigSize");
            IconSmallSize = Array.Find(parList, x => x.Ident == "ParamIconSmallSize");

            if (IconBigSize == null)
            {
                LimeMsg.Error("ErrSkinParMiss", nameof(IconBigSize));
                return;
            }

            if (IconSmallSize == null)
            {
                LimeMsg.Error("ErrSkinParMiss", nameof(IconSmallSize));
                return;
            }


            // Remove the non-visible parameters from the list of parameters
            parList = parList.Where(x => x.Visible).ToArray();

            // Retrieve (if exists) parameters from the Configuration (settings)
            SkinParam[] configParam = null;
            if (Global.User.SkinParams != null)
            {
                Global.User.SkinParams.TryGetValue(skinName, out configParam);
            }

            // Process every paramters
            foreach (var param in parList)
            {
                // Create, reference and retrieve the property from the config (settings)
                LimeMsg.Debug("Skin: Parameter: {0} ({1})", param.Ident, param.Type);
                if (param.Content != null)
                {
                    // If no explicit name, assign the type to the Name property
                    if (param.Name == null)
                    {
                        string name = param.Type.ToString();
                        if (name != null)
                        {
                            while (name.Contains("."))
                            {
                                name = name.Substring(name.IndexOf(".") + 1);
                            }
                            param.Name = name;
                        }
                    }

                    // Default description
                    if (param.Desc == null)
                    {
                        param.Desc = "Skin Parameter: " + param.Name;
                    }

                    // Load Setting
                    if (configParam != null && loadParam)
                    {
                        SkinParam match = Array.Find(configParam, x => x.Ident == param.Ident);
                        if (match != null)
                        {
                            string val = match.Serialize;
                            LimeMsg.Debug("Skin: Parameter: Load {0} = {1}", param.Ident, val);
                            try
                            {
                                param.Serialize = val;
                            }
                            catch
                            {
                                if (Global.User.DevMode)
                                {
                                    LimeMsg.Error("ErrSkinParValue", param.Ident, val);
                                }
                            }
                        }
                    }

                    // Monitor this property for modification
                    param.PropertyChangedWeak += SkinParamPropertyChanged;
                }
            }

            // Monitor the user-properties Scaled and EnableTypeScaled
            Global.User.PropertyChangedWeak  += IconSizePropertyChanged;
            Global.Local.PropertyChangedWeak += IconSizePropertyChanged;

            // Apply the skin
            Application.Current.Resources = resources;
            Commands.MainWindow.Style     = (Style)Commands.MainWindow.FindResource(typeof(Window));


            // Validate the skin
            Name = skinName;

            // Make the parameters visible (binding)
            Parameters = parList;

            // Parameter are considered as modified when reset to default
            if (!loadParam && configParam != null)
            {
                Global.User.Modified = true;
            }
        }
        /// <summary>
        /// Creates a flow document of the report data
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ArgumentException">XAML data does not represent a FlowDocument</exception>
        /// <exception cref="ArgumentException">Flow document must have a specified page height</exception>
        /// <exception cref="ArgumentException">Flow document must have a specified page width</exception>
        /// <exception cref="ArgumentException">"Flow document must have only one ReportProperties section, but it has {0}"</exception>
        public FlowDocument CreateFlowDocument()
        {
            MemoryStream mem = new MemoryStream();

            byte[] buf = Encoding.UTF8.GetBytes(_xamlData);
            mem.Write(buf, 0, buf.Length);
            mem.Position = 0;
            FlowDocument res = XamlReader.Load(mem) as FlowDocument;

            if (res == null)
            {
                throw new ArgumentException("XAML data does not represent a FlowDocument");
            }

            if (res.PageHeight == double.NaN)
            {
                throw new ArgumentException("Flow document must have a specified page height");
            }
            if (res.PageWidth == double.NaN)
            {
                throw new ArgumentException("Flow document must have a specified page width");
            }

            // remember original values
            _pageHeight = res.PageHeight;
            _pageWidth  = res.PageWidth;

            // search report properties
            DocumentWalker             walker     = new DocumentWalker();
            List <SectionReportHeader> headers    = walker.Walk <SectionReportHeader>(res);
            List <SectionReportFooter> footers    = walker.Walk <SectionReportFooter>(res);
            List <ReportProperties>    properties = walker.Walk <ReportProperties>(res);

            if (properties.Count > 0)
            {
                if (properties.Count > 1)
                {
                    throw new ArgumentException(String.Format("Flow document must have only one ReportProperties section, but it has {0}", properties.Count));
                }
                ReportProperties prop = properties[0];
                if (prop.ReportName != null)
                {
                    ReportName = prop.ReportName;
                }
                if (prop.ReportTitle != null)
                {
                    ReportTitle = prop.ReportTitle;
                }
                if (headers.Count > 0)
                {
                    PageHeaderHeight = headers[0].PageHeaderHeight;
                }
                if (footers.Count > 0)
                {
                    PageFooterHeight = footers[0].PageFooterHeight;
                }

                // remove properties section from FlowDocument
                DependencyObject parent = prop.Parent;
                if (parent is FlowDocument)
                {
                    ((FlowDocument)parent).Blocks.Remove(prop); parent = null;
                }
                if (parent is Section)
                {
                    ((Section)parent).Blocks.Remove(prop);
                }
            }

            // make height smaller to have enough space for page header and page footer
            res.PageHeight = _pageHeight - _pageHeight * (PageHeaderHeight + PageFooterHeight) / 100d;

            // search image objects
            List <Image> images = new List <Image>();

            walker.Tag            = images;
            walker.VisualVisited += WalkerVisualVisited;
            walker.Walk(res);

            // load all images
            foreach (Image image in images)
            {
                if (ImageProcessing != null)
                {
                    ImageProcessing(this, new ImageEventArgs(this, image));
                }
                try
                {
                    if (image.Tag is string)
                    {
                        image.Source = new BitmapImage(new Uri("file:///" + Path.Combine(_xamlImagePath, image.Tag.ToString())));
                    }
                }
                catch (Exception ex)
                {
                    // fire event on exception and check for Handled = true after each invoke
                    if (ImageError != null)
                    {
                        bool handled = false;
                        lock (ImageError)
                        {
                            ImageErrorEventArgs eventArgs = new ImageErrorEventArgs(ex, this, image);
                            foreach (var ed in ImageError.GetInvocationList())
                            {
                                ed.DynamicInvoke(this, eventArgs);
                                if (eventArgs.Handled)
                                {
                                    handled = true; break;
                                }
                            }
                        }
                        if (!handled)
                        {
                            throw;
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
                if (ImageProcessed != null)
                {
                    ImageProcessed(this, new ImageEventArgs(this, image));
                }
                // TODO: find a better way to specify file names
            }

            return(res);
        }
Ejemplo n.º 17
0
        private object Load(Stream stream, Uri parentUri, ParserContext pc, ContentType mimeType, string rootElement)
        {
            object obj = null;

            if (!DocumentMode)
            {                       // Loose XAML, just check against schema, don't check content type
                if (rootElement == null)
                {
                    obj = XamlReader.Load(stream, pc);
                }
            }
            else
            {                       // inside an XPS Document. Perform maximum validation
                XpsSchema schema = XpsSchema.GetSchema(mimeType);
                Uri       uri    = pc.BaseUri;

                // Using PackUriHelper.ValidateAndGetPackUriComponents internal method
                // to get Package and Part Uri in one step
                Uri packageUri;
                Uri partUri;
                PackUriHelper.ValidateAndGetPackUriComponents(uri, out packageUri, out partUri);

                Package package = PreloadedPackages.GetPackage(packageUri);

                Uri parentPackageUri = null;

                if (parentUri != null)
                {
                    parentPackageUri = PackUriHelper.GetPackageUri(parentUri);
                    if (!parentPackageUri.Equals(packageUri))
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUriNotInSamePackage));
                    }
                }

                schema.ValidateRelationships(new SecurityCriticalData <Package>(package), packageUri, partUri, mimeType);

                if (schema.AllowsMultipleReferencesToSameUri(mimeType))
                {
                    _uniqueUriRef = null;
                }
                else
                {
                    _uniqueUriRef = new Hashtable(11);
                }

                Hashtable validResources = (_validResources.Count > 0 ? _validResources.Peek() : null);
                if (schema.HasRequiredResources(mimeType))
                {
                    validResources = new Hashtable(11);

                    PackagePart part = package.GetPart(partUri);
                    PackageRelationshipCollection requiredResources = part.GetRelationshipsByType(_requiredResourceRel);

                    foreach (PackageRelationship relationShip in requiredResources)
                    {
                        Uri targetUri    = PackUriHelper.ResolvePartUri(partUri, relationShip.TargetUri);
                        Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);

                        PackagePart targetPart = package.GetPart(targetUri);

                        if (schema.IsValidRequiredResourceMimeType(targetPart.ValidatedContentType))
                        {
                            if (!validResources.ContainsKey(absTargetUri))
                            {
                                validResources.Add(absTargetUri, true);
                            }
                        }
                        else
                        {
                            if (!validResources.ContainsKey(absTargetUri))
                            {
                                validResources.Add(absTargetUri, false);
                            }
                        }
                    }
                }

                XpsSchemaValidator xpsSchemaValidator = new XpsSchemaValidator(this, schema, mimeType,
                                                                               stream, packageUri, partUri);
                _validResources.Push(validResources);
                if (rootElement != null)
                {
                    xpsSchemaValidator.XmlReader.MoveToContent();

                    if (!rootElement.Equals(xpsSchemaValidator.XmlReader.Name))
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedMimeType));
                    }

                    while (xpsSchemaValidator.XmlReader.Read())
                    {
                        ;
                    }
                }
                else
                {
                    obj = XamlReader.Load(xpsSchemaValidator.XmlReader,
                                          pc,
                                          XamlParseMode.Synchronous);
                }
                _validResources.Pop();
            }

            return(obj);
        }
Ejemplo n.º 18
0
 public DetailsDialog()
 {
     XamlReader.Load(this);
     DataContext = Model = new DetailViewModel();
 }
Ejemplo n.º 19
0
 public void PropertySetter_sl3()
 {
     XamlReader.Load(@"<TextBlock xmlns=""http://schemas.microsoft.com/client/2007"" FontWeight=""Bold"" />");
 }
Ejemplo n.º 20
0
        public dlgPlugins()
        {
            XamlReader.Load(this);

            DefaultButton = btnClose;
            DisplayMode   = DialogDisplayMode.Attached;

            filters              = new ObservableCollection <PluginEntry>();
            floppyImages         = new ObservableCollection <PluginEntry>();
            mediaImages          = new ObservableCollection <PluginEntry>();
            partitions           = new ObservableCollection <PluginEntry>();
            filesystems          = new ObservableCollection <PluginEntry>();
            readOnlyFilesystems  = new ObservableCollection <PluginEntry>();
            writableFloppyImages = new ObservableCollection <PluginEntry>();
            writableImages       = new ObservableCollection <PluginEntry>();

            grdFilters.DataStore = filters;
            grdFilters.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Name)
                },
                HeaderText = "Name",
                Sortable   = true
            });
            grdFilters.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => $"{r.Uuid}")
                },
                HeaderText = "UUID",
                Sortable   = true
            });
            grdFilters.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Version)
                },
                HeaderText = "Version",
                Sortable   = true
            });
            grdFilters.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Author)
                },
                HeaderText = "Author",
                Sortable   = true
            });
            grdFilters.AllowMultipleSelection = false;
            grdFilters.AllowColumnReordering  = true;

            grdReadableMediaImages.DataStore = mediaImages;
            grdReadableMediaImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Name)
                },
                HeaderText = "Name",
                Sortable   = true
            });
            grdReadableMediaImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding
                        .Property <PluginEntry, string>(r => $"{r.Uuid}")
                },
                HeaderText = "UUID",
                Sortable   = true
            });
            grdReadableMediaImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Version)
                },
                HeaderText = "Version",
                Sortable   = true
            });
            grdReadableMediaImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Author)
                },
                HeaderText = "Author",
                Sortable   = true
            });
            grdReadableMediaImages.AllowMultipleSelection = false;
            grdReadableMediaImages.AllowColumnReordering  = true;

            grdPartitions.DataStore = partitions;
            grdPartitions.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Name)
                },
                HeaderText = "Name",
                Sortable   = true
            });
            grdPartitions.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => $"{r.Uuid}")
                },
                HeaderText = "UUID",
                Sortable   = true
            });
            grdPartitions.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Version)
                },
                HeaderText = "Version",
                Sortable   = true
            });
            grdPartitions.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Author)
                },
                HeaderText = "Author",
                Sortable   = true
            });
            grdPartitions.AllowMultipleSelection = false;
            grdPartitions.AllowColumnReordering  = true;

            grdFilesystem.DataStore = filesystems;
            grdFilesystem.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Name)
                },
                HeaderText = "Name",
                Sortable   = true
            });
            grdFilesystem.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => $"{r.Uuid}")
                },
                HeaderText = "UUID",
                Sortable   = true
            });
            grdFilesystem.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Version)
                },
                HeaderText = "Version",
                Sortable   = true
            });
            grdFilesystem.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding = Binding.Property <PluginEntry, string>(r => r.Author)
                },
                HeaderText = "Author",
                Sortable   = true
            });
            grdFilesystem.AllowMultipleSelection = false;
            grdFilesystem.AllowColumnReordering  = true;

            grdReadOnlyFilesystem.DataStore = readOnlyFilesystems;
            grdReadOnlyFilesystem.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Name)
                },
                HeaderText = "Name",
                Sortable   = true
            });
            grdReadOnlyFilesystem.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding
                        .Property <PluginEntry, string>(r => $"{r.Uuid}")
                },
                HeaderText = "UUID",
                Sortable   = true
            });
            grdReadOnlyFilesystem.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Version)
                },
                HeaderText = "Version",
                Sortable   = true
            });
            grdReadOnlyFilesystem.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Author)
                },
                HeaderText = "Author",
                Sortable   = true
            });
            grdReadOnlyFilesystem.AllowMultipleSelection = false;
            grdReadOnlyFilesystem.AllowColumnReordering  = true;

            grdReadableFloppyImages.DataStore = floppyImages;
            grdReadableFloppyImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Name)
                },
                HeaderText = "Name",
                Sortable   = true
            });
            grdReadableFloppyImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding
                        .Property <PluginEntry, string>(r => $"{r.Uuid}")
                },
                HeaderText = "UUID",
                Sortable   = true
            });
            grdReadableFloppyImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding
                        .Property <PluginEntry, string>(r => r.Version)
                },
                HeaderText = "Version",
                Sortable   = true
            });
            grdReadableFloppyImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Author)
                },
                HeaderText = "Author",
                Sortable   = true
            });
            grdReadableFloppyImages.AllowMultipleSelection = false;
            grdReadableFloppyImages.AllowColumnReordering  = true;

            grdWritableFloppyImages.DataStore = writableFloppyImages;
            grdWritableFloppyImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Name)
                },
                HeaderText = "Name",
                Sortable   = true
            });
            grdWritableFloppyImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding
                        .Property <PluginEntry, string>(r => $"{r.Uuid}")
                },
                HeaderText = "UUID",
                Sortable   = true
            });
            grdWritableFloppyImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding
                        .Property <PluginEntry, string>(r => r.Version)
                },
                HeaderText = "Version",
                Sortable   = true
            });
            grdWritableFloppyImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Author)
                },
                HeaderText = "Author",
                Sortable   = true
            });
            grdWritableFloppyImages.AllowMultipleSelection = false;
            grdWritableFloppyImages.AllowColumnReordering  = true;

            grdWritableMediaImages.DataStore = writableImages;
            grdWritableMediaImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Name)
                },
                HeaderText = "Name",
                Sortable   = true
            });
            grdWritableMediaImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding
                        .Property <PluginEntry, string>(r => $"{r.Uuid}")
                },
                HeaderText = "UUID",
                Sortable   = true
            });
            grdWritableMediaImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Version)
                },
                HeaderText = "Version",
                Sortable   = true
            });
            grdWritableMediaImages.Columns.Add(new GridColumn
            {
                DataCell = new TextBoxCell
                {
                    Binding =
                        Binding.Property <PluginEntry, string>(r => r.Author)
                },
                HeaderText = "Author",
                Sortable   = true
            });
            grdWritableMediaImages.AllowMultipleSelection = false;
            grdWritableMediaImages.AllowColumnReordering  = true;
        }
Ejemplo n.º 21
0
        public async Task ValidatePhaseInvokeAndOrdering()
        {
            if (!PlatformConfiguration.IsOsVersionGreaterThan(OSVersion.Redstone2))
            {
                Log.Warning("Skipping: GetAvailableSize API is only available in RS3 and above.");
                return;
            }

            ItemsRepeater repeater           = null;
            int           numPhases          = 6; // 0 to 5
            bool          buildTreeCompleted = false;

            RunOnUIThread.Execute(() =>
            {
                var itemTemplate = (DataTemplate)XamlReader.Load(
                    @"<DataTemplate  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                            <Button Width='100' Height='100'/>
                        </DataTemplate>");
                repeater = new ItemsRepeater()
                {
                    ItemsSource  = Enumerable.Range(0, 10),
                    ItemTemplate = new CustomElementFactory(numPhases),
                    Layout       = new StackLayout(),
                };

                repeater.ElementPrepared += (sender, args) =>
                {
                    if (args.Index == expectedLastRealizedIndex)
                    {
                        Log.Comment("Item 8 Created!");
                        RepeaterTestHooks.BuildTreeCompleted += (sender1, args1) =>
                        {
                            buildTreeCompleted = true;
                        };
                    }
                };

                Content = new ItemsRepeaterScrollHost()
                {
                    Width        = 400,
                    Height       = 400,
                    ScrollViewer = new ScrollViewer
                    {
                        Content = repeater
                    }
                };

                // CompositionTarget.Rendering += (sender, args) => { Log.Comment("Rendering"); }; // debugging aid
            });

            await TestServices.WindowHelper.WaitFor(() => buildTreeCompleted, 2000);

            if (buildTreeCompleted)
            {
                RunOnUIThread.Execute(() =>
                {
                    var calls = ElementPhasingManager.ProcessedCalls;

                    Verify.AreEqual(9, calls.Count);
                    calls[0].RemoveAt(0);                     // Remove the create we did for first measure.
                    foreach (var index in calls.Keys)
                    {
                        var phases = calls[index];
                        Verify.AreEqual(6, phases.Count);
                        for (int i = 0; i < phases.Count; i++)
                        {
                            Verify.AreEqual(i, phases[i]);
                        }
                    }

                    ElementPhasingManager.ProcessedCalls.Clear();
                });
            }
            else
            {
                Verify.Fail("Failed on waiting on build tree.");
            }
        }
Ejemplo n.º 22
0
 private static void RichTextPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
 {
     ((RichTextBox)dependencyObject).Blocks.Add(
         XamlReader.Load((string)dependencyPropertyChangedEventArgs.NewValue) as Paragraph);
 }
Ejemplo n.º 23
0
        public void ValidateRecycling()
        {
            RunOnUIThread.Execute(() =>
            {
                var elementFactory = new RecyclingElementFactory()
                {
                    RecyclePool = new RecyclePool(),
                };
                elementFactory.Templates["even"] = (DataTemplate)XamlReader.Load(
                    @"<DataTemplate  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                        <TextBlock Text='even' />
                    </DataTemplate>");
                elementFactory.Templates["odd"] = (DataTemplate)XamlReader.Load(
                    @"<DataTemplate  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                        <TextBlock Text='odd' />
                    </DataTemplate>");

                elementFactory.SelectTemplateKey +=
                    delegate(RecyclingElementFactory sender, SelectTemplateEventArgs args)
                {
                    args.TemplateKey = ((int)args.DataContext % 2 == 0) ? "even" : "odd";
                };

                const int numItems     = 10;
                ItemsRepeater repeater = new ItemsRepeater()
                {
                    ItemsSource = Enumerable.Range(0, numItems),
#if BUILD_WINDOWS
                    ItemTemplate = (Windows.UI.Xaml.IElementFactory)elementFactory,
#else
                    ItemTemplate = elementFactory,
#endif
                };


                var context         = (ElementFactoryGetArgs)RepeaterTestHooks.CreateRepeaterElementFactoryGetArgs();
                context.Parent      = repeater;
                var clearContext    = (ElementFactoryRecycleArgs)RepeaterTestHooks.CreateRepeaterElementFactoryRecycleArgs();
                clearContext.Parent = repeater;

                // Element0 is of type even, a new one should be created
                context.Data = 0;
                var element0 = elementFactory.GetElement(context);
                Verify.IsNotNull(element0);
                Verify.AreEqual("even", (element0 as TextBlock).Text);
                clearContext.Element = element0;
                elementFactory.RecycleElement(clearContext);

                // Element1 is of type odd, a new one should be created
                context.Data = 1;
                var element1 = elementFactory.GetElement(context);
                Verify.IsNotNull(element1);
                Verify.AreNotSame(element0, element1);
                Verify.AreEqual("odd", (element1 as TextBlock).Text);
                clearContext.Element = element1;
                elementFactory.RecycleElement(clearContext);

                // Element0 should be recycled for element2
                context.Data = 2;
                var element2 = elementFactory.GetElement(context);
                Verify.AreEqual("even", (element2 as TextBlock).Text);
                Verify.AreSame(element0, element2);

                // Element1 should be recycled for element3
                context.Data = 3;
                var element3 = elementFactory.GetElement(context);
                Verify.AreEqual("odd", (element3 as TextBlock).Text);
                Verify.AreSame(element1, element3);
            });
        }
Ejemplo n.º 24
0
        private bool LoadFile(Stream stream, SvgTestInfo testInfo)
        {
            testDetailsDoc.Blocks.Clear();

            Regex rgx = new Regex("\\s+");

            testTitle.Text      = testInfo.Title;
            testDescrition.Text = rgx.Replace(testInfo.Description, " ").Trim();
            testFilePath.Text   = _svgFilePath;

            btnFilePath.IsEnabled = true;

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreWhitespace             = false;
            settings.IgnoreComments               = true;
            settings.IgnoreProcessingInstructions = true;
            settings.DtdProcessing = DtdProcessing.Parse;

            SvgTestSuite selectedTestSuite = null;

            if (_optionSettings != null)
            {
                selectedTestSuite = _optionSettings.SelectedTestSuite;
            }
            if (selectedTestSuite == null)
            {
                selectedTestSuite = SvgTestSuite.GetDefault(SvgTestSuite.Create());
            }

            int majorVersion = selectedTestSuite.MajorVersion;
            int minorVersion = selectedTestSuite.MinorVersion;

            using (XmlReader reader = XmlReader.Create(stream, settings))
            {
                if (majorVersion == 1 && minorVersion == 1)
                {
                    if (reader.ReadToFollowing("d:SVGTestCase"))
                    {
                        _testCase = new SvgTestCase();

                        while (reader.Read())
                        {
                            string      nodeName = reader.Name;
                            XmlNodeType nodeType = reader.NodeType;
                            if (nodeType == XmlNodeType.Element)
                            {
                                if (string.Equals(nodeName, "d:operatorScript", StringComparison.OrdinalIgnoreCase))
                                {
                                    string inputText = reader.ReadInnerXml();
                                    string xamlText  = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false);

                                    Paragraph titlePara = new Paragraph();
                                    titlePara.FontWeight = FontWeights.Bold;
                                    titlePara.FontSize   = 16;
                                    titlePara.Inlines.Add(new Run("Operator Script"));

                                    if (_useConverter)
                                    {
                                        StringReader stringReader = new StringReader(xamlText);
                                        XmlReader    xmlReader    = XmlReader.Create(stringReader);

                                        Section nextSection = (Section)XamlReader.Load(xmlReader);
                                        if (nextSection != null)
                                        {
                                            testDetailsDoc.Blocks.Add(titlePara);
                                            testDetailsDoc.Blocks.Add(nextSection);
                                        }
                                    }
                                    else
                                    {
                                        Section   pageSession = new Section();
                                        Paragraph nextPara    = new Paragraph();
                                        //nextPara.Padding = new Thickness(3, 5, 3, 5);
                                        string paraText = rgx.Replace(inputText, " ").Trim();
                                        nextPara.Inlines.Add(new Run(paraText));
                                        pageSession.Blocks.Add(titlePara);
                                        pageSession.Blocks.Add(nextPara);

                                        testDetailsDoc.Blocks.Add(pageSession);
                                    }
                                }
                                else if (string.Equals(nodeName, "d:passCriteria", StringComparison.OrdinalIgnoreCase))
                                {
                                    string inputText = reader.ReadInnerXml();
                                    string xamlText  = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false);

                                    Paragraph titlePara = new Paragraph();
                                    titlePara.FontWeight = FontWeights.Bold;
                                    titlePara.FontSize   = 16;
                                    titlePara.Inlines.Add(new Run("Pass Criteria"));

                                    if (_useConverter)
                                    {
                                        StringReader stringReader = new StringReader(xamlText);
                                        XmlReader    xmlReader    = XmlReader.Create(stringReader);

                                        Section nextSection = (Section)XamlReader.Load(xmlReader);
                                        if (nextSection != null)
                                        {
                                            testDetailsDoc.Blocks.Add(titlePara);
                                            testDetailsDoc.Blocks.Add(nextSection);
                                        }
                                    }
                                    else
                                    {
                                        Section   pageSession = new Section();
                                        Paragraph nextPara    = new Paragraph();
                                        //nextPara.Padding = new Thickness(3, 5, 3, 5);
                                        string paraText = rgx.Replace(inputText, " ").Trim();
                                        nextPara.Inlines.Add(new Run(paraText));
                                        pageSession.Blocks.Add(titlePara);
                                        pageSession.Blocks.Add(nextPara);

                                        testDetailsDoc.Blocks.Add(pageSession);
                                    }
                                }
                                else if (string.Equals(nodeName, "d:testDescription", StringComparison.OrdinalIgnoreCase))
                                {
                                    string inputText = reader.ReadInnerXml();
                                    string xamlText  = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false);

                                    Paragraph titlePara = new Paragraph();
                                    titlePara.FontWeight = FontWeights.Bold;
                                    titlePara.FontSize   = 16;
                                    titlePara.Inlines.Add(new Run("Test Description"));

                                    if (_useConverter)
                                    {
                                        StringReader stringReader = new StringReader(xamlText);
                                        XmlReader    xmlReader    = XmlReader.Create(stringReader);

                                        Section nextSection = (Section)XamlReader.Load(xmlReader);
                                        if (nextSection != null)
                                        {
                                            testDetailsDoc.Blocks.Add(titlePara);
                                            testDetailsDoc.Blocks.Add(nextSection);
                                        }
                                    }
                                    else
                                    {
                                        Section   pageSession = new Section();
                                        Paragraph nextPara    = new Paragraph();
                                        //nextPara.Padding = new Thickness(3, 5, 3, 5);
                                        string paraText = rgx.Replace(inputText, " ").Trim();
                                        nextPara.Inlines.Add(new Run(paraText));
                                        pageSession.Blocks.Add(titlePara);
                                        pageSession.Blocks.Add(nextPara);

                                        testDetailsDoc.Blocks.Add(pageSession);
                                    }

                                    _testCase.Paragraphs.Add(inputText);
                                }
                            }
                            else if (nodeType == XmlNodeType.EndElement &&
                                     string.Equals(nodeName, "SVGTestCase", StringComparison.OrdinalIgnoreCase))
                            {
                                break;
                            }
                        }
                    }
                }
                else if (majorVersion == 1 && minorVersion == 2)
                {
                    if (reader.ReadToFollowing("SVGTestCase"))
                    {
                        _testCase = new SvgTestCase();

                        while (reader.Read())
                        {
                            string      nodeName = reader.Name;
                            XmlNodeType nodeType = reader.NodeType;
                            if (nodeType == XmlNodeType.Element)
                            {
                                if (string.Equals(nodeName, "d:OperatorScript", StringComparison.OrdinalIgnoreCase))
                                {
                                    string inputText = reader.ReadInnerXml();
                                    string xamlText  = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false);

                                    if (_useConverter)
                                    {
                                        StringReader stringReader = new StringReader(xamlText);
                                        XmlReader    xmlReader    = XmlReader.Create(stringReader);

                                        Section nextSection = (Section)XamlReader.Load(xmlReader);
                                        if (nextSection != null)
                                        {
                                            testDetailsDoc.Blocks.Add(nextSection);
                                        }
                                    }
                                    else
                                    {
                                        Section   pageSession = new Section();
                                        Paragraph nextPara    = new Paragraph();
                                        //nextPara.Padding = new Thickness(3, 5, 3, 5);
                                        string paraText = rgx.Replace(inputText, " ").Trim();
                                        nextPara.Inlines.Add(new Run(paraText));
                                        pageSession.Blocks.Add(nextPara);

                                        testDetailsDoc.Blocks.Add(pageSession);
                                    }
                                }
                                else if (string.Equals(nodeName, "d:PassCriteria", StringComparison.OrdinalIgnoreCase))
                                {
                                    string inputText = reader.ReadInnerXml();
                                    string xamlText  = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false);

                                    if (_useConverter)
                                    {
                                        StringReader stringReader = new StringReader(xamlText);
                                        XmlReader    xmlReader    = XmlReader.Create(stringReader);

                                        Section nextSection = (Section)XamlReader.Load(xmlReader);
                                        if (nextSection != null)
                                        {
                                            testDetailsDoc.Blocks.Add(nextSection);
                                        }
                                    }
                                    else
                                    {
                                        Section   pageSession = new Section();
                                        Paragraph nextPara    = new Paragraph();
                                        //nextPara.Padding = new Thickness(3, 5, 3, 5);
                                        string paraText = rgx.Replace(inputText, " ").Trim();
                                        nextPara.Inlines.Add(new Run(paraText));
                                        pageSession.Blocks.Add(nextPara);

                                        testDetailsDoc.Blocks.Add(pageSession);
                                    }
                                }
                                else if (string.Equals(nodeName, "d:TestDescription", StringComparison.OrdinalIgnoreCase))
                                {
                                    string inputText = reader.ReadInnerXml();
                                    string xamlText  = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false);

                                    if (_useConverter)
                                    {
                                        StringReader stringReader = new StringReader(xamlText);
                                        XmlReader    xmlReader    = XmlReader.Create(stringReader);

                                        Section nextSection = (Section)XamlReader.Load(xmlReader);
                                        if (nextSection != null)
                                        {
                                            testDetailsDoc.Blocks.Add(nextSection);
                                        }
                                    }
                                    else
                                    {
                                        Section   pageSession = new Section();
                                        Paragraph nextPara    = new Paragraph();
                                        //nextPara.Padding = new Thickness(3, 5, 3, 5);
                                        string paraText = rgx.Replace(inputText, " ").Trim();
                                        nextPara.Inlines.Add(new Run(paraText));
                                        pageSession.Blocks.Add(nextPara);

                                        testDetailsDoc.Blocks.Add(pageSession);
                                    }

                                    _testCase.Paragraphs.Add(inputText);
                                }
                            }
                            else if (nodeType == XmlNodeType.EndElement &&
                                     string.Equals(nodeName, "SVGTestCase", StringComparison.OrdinalIgnoreCase))
                            {
                                break;
                            }
                        }
                    }
                }
                else
                {
                    if (reader.ReadToFollowing("SVGTestCase"))
                    {
                        _testCase = new SvgTestCase();

                        while (reader.Read())
                        {
                            string      nodeName = reader.Name;
                            XmlNodeType nodeType = reader.NodeType;
                            if (nodeType == XmlNodeType.Element)
                            {
                                if (string.Equals(nodeName, "OperatorScript", StringComparison.OrdinalIgnoreCase))
                                {
                                    string revisionText = reader.GetAttribute("version");
                                    if (!string.IsNullOrWhiteSpace(revisionText))
                                    {
                                        revisionText       = revisionText.Replace("$", "");
                                        _testCase.Revision = revisionText.Trim();
                                    }
                                    string nameText = reader.GetAttribute("testname");
                                    if (!string.IsNullOrWhiteSpace(nameText))
                                    {
                                        _testCase.Name = nameText.Trim();
                                    }
                                }
                                else if (string.Equals(nodeName, "Paragraph", StringComparison.OrdinalIgnoreCase))
                                {
                                    string inputText = reader.ReadInnerXml();
                                    string xamlText  = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false);

                                    if (_useConverter)
                                    {
                                        StringReader stringReader = new StringReader(xamlText);
                                        XmlReader    xmlReader    = XmlReader.Create(stringReader);

                                        Section nextSection = (Section)XamlReader.Load(xmlReader);

                                        testDetailsDoc.Blocks.Add(nextSection);
                                    }
                                    else
                                    {
                                        Section   pageSession = new Section();
                                        Paragraph nextPara    = new Paragraph();
                                        //nextPara.Padding = new Thickness(3, 5, 3, 5);
                                        string paraText = rgx.Replace(inputText, " ").Trim();
                                        nextPara.Inlines.Add(new Run(paraText));
                                        pageSession.Blocks.Add(nextPara);

                                        testDetailsDoc.Blocks.Add(pageSession);
                                    }

                                    _testCase.Paragraphs.Add(inputText);
                                }
                            }
                            else if (nodeType == XmlNodeType.EndElement &&
                                     string.Equals(nodeName, "SVGTestCase", StringComparison.OrdinalIgnoreCase))
                            {
                                break;
                            }
                        }
                    }
                }
            }

            SubscribeToAllHyperlinks();

            return(true);
        }
Ejemplo n.º 25
0
        public void VerifyCurrentAnchor()
        {
            ItemsRepeater           rootRepeater = null;
            ScrollViewer            scrollViewer = null;
            ItemsRepeaterScrollHost scrollhost   = null;
            ManualResetEvent        viewChanged  = new ManualResetEvent(false);

            RunOnUIThread.Execute(() =>
            {
                scrollhost = (ItemsRepeaterScrollHost)XamlReader.Load(
                    @"<controls:ItemsRepeaterScrollHost Width='400' Height='600'
                     xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                     xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                     xmlns:controls='using:Microsoft.UI.Xaml.Controls'>
                    <controls:ItemsRepeaterScrollHost.Resources>
                        <DataTemplate x:Key='ItemTemplate' >
                            <TextBlock Text='{Binding}' Height='50'/>
                        </DataTemplate>
                    </controls:ItemsRepeaterScrollHost.Resources>
                    <ScrollViewer x:Name='scrollviewer'>
                        <controls:ItemsRepeater x:Name='rootRepeater' ItemTemplate='{StaticResource ItemTemplate}' VerticalCacheLength='0' />
                    </ScrollViewer>
                </controls:ItemsRepeaterScrollHost>");

                rootRepeater              = (ItemsRepeater)scrollhost.FindName("rootRepeater");
                scrollViewer              = (ScrollViewer)scrollhost.FindName("scrollviewer");
                scrollViewer.ViewChanged += (sender, args) =>
                {
                    if (!args.IsIntermediate)
                    {
                        viewChanged.Set();
                    }
                };

                rootRepeater.ItemsSource = Enumerable.Range(0, 500);
                Content = scrollhost;
            });

            // scroll down several times and validate current anchor
            for (int i = 1; i < 10; i++)
            {
                IdleSynchronizer.Wait();
                RunOnUIThread.Execute(() =>
                {
                    scrollViewer.ChangeView(null, i * 200, null);
                });

                Verify.IsTrue(viewChanged.WaitOne(DefaultWaitTimeInMS));
                viewChanged.Reset();

                RunOnUIThread.Execute(() =>
                {
                    Verify.AreEqual(i * 200, scrollViewer.VerticalOffset);
                    var anchor = PlatformConfiguration.IsOSVersionLessThan(OSVersion.Redstone5) ?
                                 scrollhost.CurrentAnchor :
                                 scrollViewer.CurrentAnchor;
                    var anchorIndex = rootRepeater.GetElementIndex(anchor);
                    Log.Comment("CurrentAnchor: " + anchorIndex);
                    Verify.AreEqual(i * 4, anchorIndex);
                });
            }
        }
Ejemplo n.º 26
0
        private object Load(Stream stream, Uri parentUri, ParserContext pc, ContentType mimeType, string rootElement)
        {
            object      result    = null;
            List <Type> safeTypes = new List <Type>
            {
                typeof(ResourceDictionary)
            };

            if (!XpsValidatingLoader.DocumentMode)
            {
                if (rootElement == null)
                {
                    XmlReader reader = XmlReader.Create(stream, null, pc);
                    result = XamlReader.Load(reader, pc, XamlParseMode.Synchronous, FrameworkCompatibilityPreferences.DisableLegacyDangerousXamlDeserializationMode, safeTypes);
                    stream.Close();
                }
            }
            else
            {
                XpsSchema schema  = XpsSchema.GetSchema(mimeType);
                Uri       baseUri = pc.BaseUri;
                Uri       uri;
                Uri       uri2;
                PackUriHelper.ValidateAndGetPackUriComponents(baseUri, out uri, out uri2);
                Package package = PreloadedPackages.GetPackage(uri);
                if (parentUri != null)
                {
                    Uri packageUri = PackUriHelper.GetPackageUri(parentUri);
                    if (!packageUri.Equals(uri))
                    {
                        throw new FileFormatException(SR.Get("XpsValidatingLoaderUriNotInSamePackage"));
                    }
                }
                schema.ValidateRelationships(new SecurityCriticalData <Package>(package), uri, uri2, mimeType);
                if (schema.AllowsMultipleReferencesToSameUri(mimeType))
                {
                    this._uniqueUriRef = null;
                }
                else
                {
                    this._uniqueUriRef = new Hashtable(11);
                }
                Hashtable hashtable = (XpsValidatingLoader._validResources.Count > 0) ? XpsValidatingLoader._validResources.Peek() : null;
                if (schema.HasRequiredResources(mimeType))
                {
                    hashtable = new Hashtable(11);
                    PackagePart part = package.GetPart(uri2);
                    PackageRelationshipCollection relationshipsByType = part.GetRelationshipsByType(XpsValidatingLoader._requiredResourceRel);
                    foreach (PackageRelationship packageRelationship in relationshipsByType)
                    {
                        Uri         partUri = PackUriHelper.ResolvePartUri(uri2, packageRelationship.TargetUri);
                        Uri         key     = PackUriHelper.Create(uri, partUri);
                        PackagePart part2   = package.GetPart(partUri);
                        if (schema.IsValidRequiredResourceMimeType(part2.ValidatedContentType))
                        {
                            if (!hashtable.ContainsKey(key))
                            {
                                hashtable.Add(key, true);
                            }
                        }
                        else if (!hashtable.ContainsKey(key))
                        {
                            hashtable.Add(key, false);
                        }
                    }
                }
                XpsSchemaValidator xpsSchemaValidator = new XpsSchemaValidator(this, schema, mimeType, stream, uri, uri2);
                XpsValidatingLoader._validResources.Push(hashtable);
                if (rootElement != null)
                {
                    xpsSchemaValidator.XmlReader.MoveToContent();
                    if (!rootElement.Equals(xpsSchemaValidator.XmlReader.Name))
                    {
                        throw new FileFormatException(SR.Get("XpsValidatingLoaderUnsupportedMimeType"));
                    }
                    while (xpsSchemaValidator.XmlReader.Read())
                    {
                    }
                }
                else
                {
                    result = XamlReader.Load(xpsSchemaValidator.XmlReader, pc, XamlParseMode.Synchronous, FrameworkCompatibilityPreferences.DisableLegacyDangerousXamlDeserializationMode, safeTypes);
                }
                XpsValidatingLoader._validResources.Pop();
            }
            return(result);
        }
Ejemplo n.º 27
0
        public void VerifyCorrectionsInNonScrollableDirection()
        {
            ItemsRepeater           rootRepeater = null;
            ScrollViewer            scrollViewer = null;
            ItemsRepeaterScrollHost scrollhost   = null;
            ManualResetEvent        viewChanged  = new ManualResetEvent(false);

            RunOnUIThread.Execute(() =>
            {
                scrollhost = (ItemsRepeaterScrollHost)XamlReader.Load(
                    @"<controls:ItemsRepeaterScrollHost Width='400' Height='600'
                     xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                     xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                     xmlns:controls='using:Microsoft.UI.Xaml.Controls'>
                    <ScrollViewer Width='400' Height='400' x:Name='scrollviewer'>
                        <controls:ItemsRepeater x:Name='repeater'>
                            <DataTemplate>
                                <StackPanel>
                                    <controls:ItemsRepeater ItemsSource='{Binding}'>
                                        <controls:ItemsRepeater.Layout>
                                            <controls:StackLayout Orientation='Horizontal' />
                                        </controls:ItemsRepeater.Layout>
                                    </controls:ItemsRepeater>
                                </StackPanel>
                            </DataTemplate>
                        </controls:ItemsRepeater>
                    </ScrollViewer>
                </controls:ItemsRepeaterScrollHost>");

                rootRepeater              = (ItemsRepeater)scrollhost.FindName("repeater");
                scrollViewer              = (ScrollViewer)scrollhost.FindName("scrollviewer");
                scrollViewer.ViewChanged += (sender, args) =>
                {
                    if (!args.IsIntermediate)
                    {
                        viewChanged.Set();
                    }
                };

                List <List <int> > items = new List <List <int> >();
                for (int i = 0; i < 100; i++)
                {
                    items.Add(Enumerable.Range(0, 4).ToList());
                }
                rootRepeater.ItemsSource = items;
                Content = scrollhost;
            });

            // scroll down several times and validate no crash
            for (int i = 1; i < 5; i++)
            {
                IdleSynchronizer.Wait();
                RunOnUIThread.Execute(() =>
                {
                    scrollViewer.ChangeView(null, i * 200, null);
                });

                Verify.IsTrue(viewChanged.WaitOne(DefaultWaitTimeInMS));
                viewChanged.Reset();
            }
        }
Ejemplo n.º 28
0
        static TreeViewBackend()
        {
            Uri uri = new Uri("pack://application:,,,/Xwt.WPF;component/XWT.WPFBackend/TreeView.xaml");

            TreeResourceDictionary = (ResourceDictionary)XamlReader.Load(System.Windows.Application.GetResourceStream(uri).Stream);
        }
        public void VerifyDropdownItemTemplateWithNoControl()
        {
            BreadcrumbBar breadcrumb = null;

            RunOnUIThread.Execute(() =>
            {
                breadcrumb             = new BreadcrumbBar();
                breadcrumb.ItemsSource = new List <string>()
                {
                    "Node 1", "Node 2"
                };

                // Set a custom ItemTemplate to be wrapped in a BreadcrumbBarItem.
                var itemTemplate = (DataTemplate)XamlReader.Load(
                    @"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
                            <TextBlock Text='{Binding}'/>
                        </DataTemplate>");

                breadcrumb.ItemTemplate = itemTemplate;

                var stackPanel   = new StackPanel();
                stackPanel.Width = 60;
                stackPanel.Children.Add(breadcrumb);

                Content = stackPanel;
                Content.UpdateLayout();
            });

            IdleSynchronizer.Wait();

            Button ellipsisButton = null;

            RunOnUIThread.Execute(() =>
            {
                ItemsRepeater breadcrumbItemsRepeater = (ItemsRepeater)breadcrumb.FindVisualChildByName("PART_ItemsRepeater");
                Verify.IsNotNull(breadcrumbItemsRepeater, "The underlying items repeater (1) could not be retrieved");

                var breadcrumbNode1 = breadcrumbItemsRepeater.TryGetElement(0) as BreadcrumbBarItem;
                Verify.IsNotNull(breadcrumbNode1, "Our custom ItemTemplate (1) should have been wrapped in a BreadcrumbBarItem.");

                ellipsisButton = (Button)breadcrumbNode1.FindVisualChildByName("PART_ItemButton");
                Verify.IsNotNull(ellipsisButton, "The ellipsis item (1) could not be retrieved");

                var automationPeer    = new ButtonAutomationPeer(ellipsisButton);
                var invokationPattern = automationPeer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
                invokationPattern?.Invoke();
            });

            // GetOpenPopups returns empty list in RS3. The scenario works, this just seems to be a
            // test/infra issue in RS3, so filtering it out for now.
            if (PlatformConfiguration.IsOsVersionGreaterThan(OSVersion.Redstone3))
            {
                IdleSynchronizer.Wait();

                RunOnUIThread.Execute(() =>
                {
                    var flyout = VisualTreeHelper.GetOpenPopups(Window.Current).Last();
                    Verify.IsNotNull(flyout, "Flyout could not be retrieved");
                    var ellipsisItemsRepeater = TestUtilities.FindDescendents <ItemsRepeater>(flyout).Single();
                    Verify.IsNotNull(ellipsisItemsRepeater, "The underlying flyout items repeater (1) could not be retrieved");

                    ellipsisItemsRepeater.Loaded += (object sender, RoutedEventArgs e) =>
                    {
                        TextBlock ellipsisNode1 = ellipsisItemsRepeater.TryGetElement(0) as TextBlock;
                        Verify.IsNotNull(ellipsisNode1, "Our flyout ItemTemplate (1) should have been wrapped in a TextBlock.");

                        // change this conditions
                        bool testCondition = !(ellipsisNode1.Foreground is SolidColorBrush brush && brush.Color == Colors.Blue);
                        Verify.IsTrue(testCondition, "Default foreground color of the BreadcrumbBarItem should not have been [blue].");
                    };
                });
            }
        }
Ejemplo n.º 30
0
 public ContinuumBackwardOutAnimator()
     : base()
 {
     Storyboard = XamlReader.Load(Storyboards.ContinuumBackwardOutStoryboard) as Storyboard;
 }