Пример #1
0
        private Grid FormatContainer(FixedContainer context)
        {
            var grid = new Grid();

            grid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = GridLength.Auto
            });
            grid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = GridLength.Auto
            });

            var fields = context.GetPrimitiveFields(Data)
                         .Where(f => f.IsEnabled(context, Data));

            foreach (var primitive in fields)
            {
                var label = new Label
                {
                    Padding = new Thickness(0),
                    Margin  = new Thickness(2, 1, 0, 0),
                    Content = primitive.Description,
                    VerticalContentAlignment = VerticalAlignment.Center
                };
                FrameworkElement value;
                if (editMode)
                {
                    value        = CreateReadWriteFieldElement(context, primitive);
                    value.Margin = App.ValueMargin;
                }
                else
                {
                    value = new Label
                    {
                        Padding = new Thickness(0),
                        Margin  = App.ValueMargin,
                        Content = primitive.GetText(context, Data)
                    };
                }

                Grid.SetRow(label, grid.RowDefinitions.Count);
                Grid.SetRow(value, grid.RowDefinitions.Count);
                Grid.SetColumn(label, 0);
                Grid.SetColumn(value, 1);
                grid.RowDefinitions.Add(new RowDefinition());
                grid.Children.Add(label);
                grid.Children.Add(value);
            }

            // Assumption: at most one dynamic overlay per container
            var overlay = context.Container.Fields.OfType <DynamicOverlay>().FirstOrDefault();

            if (overlay != null)
            {
                var currentContainer = overlay.GetOverlaidContainer(context, Data);
                grid.Tag = (overlay, currentContainer);
            }

            return(grid);
        }
Пример #2
0
 internal VisualTreeNode(
     VisualTreeNode?parent,
     FixedContainer context,
     Func <VisualTreeNode?, IReadOnlyList <VisualTreeNode> > childrenProvider,
     IReadOnlyList <VisualTreeDetail> details,
     FormattableDescription description,
     FormattableDescription?kitOnlyDescription,
     FieldChain <MidiNoteField>?midiNoteField,
     int?kitNumber,
     int?instrumentNumber) =>
 (Parent, Context, Children, Details, Description, KitOnlyDescription, MidiNoteField, KitNumber, InstrumentNumber) =
 private VisualTreeConversionContext(
     ModuleJson moduleJson,
     FixedContainer containerContext,
     IReadOnlyDictionary <string, string> lookupsByPath,
     List <KeyValuePair <string, string> > indexes)
 {
     this.moduleJson       = moduleJson;
     this.ContainerContext = containerContext;
     this.lookupsByPath    = lookupsByPath;
     this.indexes          = indexes;
 }
        private async Task LoadContainerAsync(ModuleData data, FixedContainer context)
        {
            if (data.GetSegmentOrNull(context.Address) != null)
            {
                return;
            }
            var timerToken     = new CancellationTokenSource(TimeSpan.FromSeconds(1)).Token;
            var effectiveToken = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, timerToken).Token;
            var segment        = await midiClient.RequestDataAsync(context.Address.Value, context.Container.Size, effectiveToken);

            data.Populate(context.Address, segment);
        }
Пример #5
0
        public bool Validate(FixedContainer context, ModuleData data, out string?error)
        {
            var segment = data.GetSegment(GetAddress(context));

            // TODO: Check the length against size?
            if (segment == null)
            {
                error = "No segment containing field present in the module data.";
                return(false);
            }
            return(ValidateData(context, data, out error));
        }
Пример #6
0
        internal async void LoadDeviceData(FixedContainer root)
        {
            var data = new ModuleData();

            // TODO: Possibly reinstate this in RolandMidiClient.
            // client.UnconsumedMessageHandler += LogUnconsumedMessage;
            try
            {
                Stopwatch sw         = Stopwatch.StartNew();
                var       containers = root.AnnotateDescendantsAndSelf().Where(c => c.Container.Loadable).ToList();
                logger.Log($"Loading {containers.Count} containers from device {schema.Identifier.Name}");
                progress.Maximum = containers.Count;
                int loaded = 0;
                foreach (var container in containers)
                {
                    // TODO: Make RequestDataAsync return a segment.
                    label.Content = $"Loading {container.Path}";
                    await PopulateSegment(data, container, cancellationTokenSource.Token);

                    loaded++;
                    progress.Value = loaded;
                }
                Data         = data;
                DialogResult = true;
                logger.Log($"Finished loading in {(int) sw.Elapsed.TotalSeconds} seconds");
            }
            catch (OperationCanceledException)
            {
                logger.Log("Data loading from device was cancelled");
                DialogResult = false;
            }
            catch (Exception ex)
            {
                logger.Log("Error loading data from device", ex);
            }
            finally
            {
                //client.UnconsumedMessageHandler -= LogUnconsumedMessage;
            }

            /*
             * void LogUnconsumedMessage(object sender, DataResponseMessage message) =>
             *  logger.Log($"Unexpected data response. Address: {message.Address:x8}; Length: {message.Length:x8}");
             */
        }
Пример #7
0
        // Note: this used to be in ModuleJson.ToModuleSchema(), but it turns out it's really useful for
        // a field to have access to the schema it's part of... which is tricky when everything is immutable
        // and the schema also has to have references to the fields. So this code is ugly - and makes field testing
        // trickier - but at least it's pleasant to use elsewhere.
        internal ModuleSchema(ModuleJson json)
        {
            // Note: we populate everything other than the fields first, so that field
            // construction can rely on it.
            json.Validate();
            Identifier        = new ModuleIdentifier(json.Name !, json.ModelId !.Value, json.FamilyCode !.Value, json.FamilyNumberCode !.Value);
            InstrumentGroups  = json.BuildInstrumentGroups();
            PresetInstruments = InstrumentGroups.SelectMany(ig => ig.Instruments)
                                .OrderBy(i => i.Id)
                                .ToList()
                                .AsReadOnly();
            // Just validate that our list is consistent.
            for (int i = 0; i < PresetInstruments.Count; i++)
            {
                if (PresetInstruments[i].Id != i)
                {
                    throw new InvalidOperationException($"Instrument {PresetInstruments[i]} is in index {i}");
                }
            }

            UserSampleInstruments = Enumerable.Range(0, json.UserSamples !.Value)
                                    .Select(id => Instrument.FromUserSample(id))
                                    .ToList()
                                    .AsReadOnly();

            // Now do everything with the fields.
            Root         = new FixedContainer(json.BuildRootContainer(this), new ModuleAddress(0));
            LogicalRoot  = json.BuildLogicalRoot(Root);
            PhysicalRoot = VisualTreeNode.FromFixedContainer(null, Root);
            KitRoots     = LogicalRoot.DescendantNodesAndSelf()
                           .Where(node => node.KitNumber != null)
                           .ToDictionary(node => node.KitNumber !.Value)
                           .AsReadOnly();
            LoadableContainersByAddress = Root
                                          .DescendantsAndSelf()
                                          .Where(context => context.Container.Loadable)
                                          .ToDictionary(context => context.Address, context => context.Container)
                                          .AsReadOnly();
        }
Пример #8
0
 private static JToken ConvertToJson(VisualTreeDetail detail, FixedContainer context, ModuleData data)
 {
     if (detail.DetailDescriptions is object)
     {
         var ret = new JArray();
         foreach (var description in detail.DetailDescriptions)
         {
             ret.Add(description.Format(context, data));
         }
         return(ret);
     }
     else
     {
         var ret       = new JObject();
         var container = detail.Container;
         var fields    = container.GetPrimitiveFields(data)
                         .Where(f => f.IsEnabled(context, data));
         foreach (var field in fields)
         {
             ret.Add(field.Description, field.GetText(container, data));
         }
         return(ret);
     }
 }
Пример #9
0
 public Difference(Instrument instrument, FixedContainer container, IField field, int realValue, int predictedValue) =>
 (Instrument, Container, Field, RealValue, PredictedValue) =
Пример #10
0
 public AnnotatedContainer(string path, FixedContainer context) =>
 (Path, Context) = (path, context);
Пример #11
0
 public abstract void Reset(FixedContainer context, ModuleData data);
Пример #12
0
 public abstract string GetText(FixedContainer context, ModuleData data);
Пример #13
0
 /// <summary>
 /// Validates the data against the field. This is called by <see cref="Validate"/>
 /// after performing the common check that the field has a segment in the module data.
 /// Implementations may therefore assume that the data exists.
 /// </summary>
 protected abstract bool ValidateData(FixedContainer context, ModuleData data, out string?error);
Пример #14
0
 public abstract bool TrySetText(FixedContainer context, ModuleData data, string text);
Пример #15
0
 public VisualTreeDetail(string description, FixedContainer container) =>
 (Description, Container, DetailDescriptions) = (description, container, null);
 internal static VisualTreeConversionContext Create(
     ModuleJson moduleJson,
     FixedContainer containerContext,
     IReadOnlyDictionary <string, string> lookupsByPath) =>
 new VisualTreeConversionContext(moduleJson, containerContext, lookupsByPath, new List <KeyValuePair <string, string> >());
Пример #17
0
        public RdlRender.FixedContainer Render()
        {
            FixedContainer topBox = new FixedContainer(null, this, new BoxStyle(Style.DefaultStyle));

            topBox.Name = "Report";
            if (_width.points > 0)
            {
                topBox.Width = _width.points;
                topBox.CanGrowHorizonally = false;
            }

            // Set up the compiler
            CompilerParameters cp = new CompilerParameters();

            cp.GenerateExecutable    = false;
            cp.GenerateInMemory      = true;
            cp.TreatWarningsAsErrors = false;
            if (File.Exists(System.AppDomain.CurrentDomain.RelativeSearchPath + @"\rdlEngine.dll"))
            {
                cp.ReferencedAssemblies.Add(System.AppDomain.CurrentDomain.RelativeSearchPath + @"\rdlEngine.dll");
            }
            else if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + @"\rdlEngine.dll"))
            {
                cp.ReferencedAssemblies.Add(System.AppDomain.CurrentDomain.BaseDirectory + @"\rdlEngine.dll");
            }
            else
            {
                throw new Exception("Unable to file rdlEngine.dll");
            }

            // Replace the aggregate function calls with deletage calls.
            int ct = _functions.Count;

            for (int i = 0; i < ct; i++)
            {
                _functions[i] = ReplaceAggregatesWithDelegates(_functions[i]);
            }

            // Build the source code for the named functions.
            string addFns    = string.Empty;
            string functions = string.Empty;

            for (int i = 0; i < _functions.Count; i++)
            {
                addFns    += "     AddFunction( AddressOf fn_" + i.ToString() + " )\n";
                functions += _functions[i] + "\n";
            }

            string source = RdlEngine.RdlResource.RuntimeCode;

            source = source.Replace(@"' Add Functions", addFns);
            source = source.Replace(@"' Functions", functions);

            // Compile the runtime source
            CodeDomProvider provider = new VBCodeProvider();
            CompilerResults cr       = provider.CompileAssemblyFromSource(cp, new string[] { source });

            if (cr.Errors.Count > 0)
            {
                throw new Exception("Compile errors");
            }

            // Get a reference to a RunTimeBase object.
            Assembly CodeAssembly = cr.CompiledAssembly;
            Type     ty           = CodeAssembly.GetType("RdlRuntime.RunTimeClass");

            Rtb = (RdlRuntime.RuntimeBase)Activator.CreateInstance(ty,
                                                                   new object[] { this });

            // Initialize the data sets.
            _dataSets.Initialize();

            // Set the default DataSet for the report
            if (_dataSchema != null)
            {
                _reportDataSet = _dataSets[_dataSchema];
            }
            else
            {
                _reportDataSet = _dataSets.FirstDataSet;
            }

            // Set up the default data context.
            _context = new RdlRuntime.Context(
                null, _reportDataSet, null, null, null);
            topBox.ContextBase = true;

            // Render the report.
            _body.Render(topBox);

            topBox.LinkToggles();

            return(topBox);
        }
Пример #18
0
 private FrameworkElement CreateReadWriteFieldElement(FixedContainer context, IPrimitiveField field) =>
 field switch
 {
Пример #19
0
 public static bool IsEnabled(this IField field, FixedContainer context, ModuleData data) =>
 field.Condition?.IsEnabled(field, context, data) ?? true;