void Initialize()
        {
            container.CreateAndAddLabelRow("Reaction ID");

            container.CreateAndAddStringEditorRow2("Name", "", rx.Name, (sender, e) => { rx.Name = sender.Text; });

            container.CreateAndAddLabelRow("Compounds and Stoichiometry (Include / Name / Heat of Formation (kJ/kg) / Stoich. Coeff.)");

            var compcontainer = new DynamicLayout();
            //compcontainer.BackgroundColor = Colors.White;

            Double val;

            foreach (ICompoundConstantProperties comp in flowsheet.SelectedCompounds.Values)
            {
                var chk = new CheckBox()
                {
                    Text = comp.Name, Checked = (rx.Components.ContainsKey(comp.Name) ? true : false)
                };
                chk.CheckedChanged += (sender, e) =>
                {
                    if (!rx.Components.ContainsKey(comp.Name))
                    {
                        rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, 0, false, 0, 0));
                    }
                    else
                    {
                        rx.Components.Remove(comp.Name);
                    }
                    UpdateEquation();
                };

                var sc = new TextBox()
                {
                    Width = (int)(sf * 50), Text = (rx.Components.ContainsKey(comp.Name) ? rx.Components[comp.Name].StoichCoeff.ToString() : 0.0f.ToString())
                };

                sc.TextChanged += (sender, e) =>
                {
                    if (Double.TryParse(sc.Text.ToString(), out val))
                    {
                        sc.TextColor = SystemColors.ControlText;
                        if (!rx.Components.ContainsKey(comp.Name))
                        {
                            rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, Double.Parse(sc.Text), false, 0, 0));
                        }
                        else
                        {
                            rx.Components[comp.Name].StoichCoeff = double.Parse(sc.Text);
                        }
                        UpdateEquation();
                    }
                    else
                    {
                        sc.TextColor = Colors.Red;
                    }
                };

                var hf = new TextBox()
                {
                    Enabled = false, Width = (int)(sf * 100), Text = comp.IG_Enthalpy_of_Formation_25C.ToString("N2")
                };

                compcontainer.Add(new TableRow(chk, null, hf, sc));
            }

            container.CreateAndAddControlRow(compcontainer);
            container.CreateAndAddEmptySpace();

            var comps = flowsheet.SelectedCompounds.Values.Select((x) => x.Name).ToList();

            comps.Insert(0, "");

            container.CreateAndAddLabelRow("Base Compound");

            var basecompselector = container.CreateAndAddDropDownRow("Base Compound", comps, 0, null);

            var basecomp = rx.Components.Values.Where((x) => x.IsBaseReactant).FirstOrDefault();

            if (basecomp != null)
            {
                basecompselector.SelectedIndex = comps.IndexOf(basecomp.CompName);
            }
            else
            {
                basecompselector.SelectedIndex = 0;
            }

            basecompselector.SelectedIndexChanged += (sender, e) =>
            {
                if (rx.Components.ContainsKey(comps[basecompselector.SelectedIndex]))
                {
                    foreach (var rxc in rx.Components.Values)
                    {
                        rxc.IsBaseReactant = false;
                    }
                    rx.Components[comps[basecompselector.SelectedIndex]].IsBaseReactant = true;
                    rx.BaseReactant = comps[basecompselector.SelectedIndex];
                }
            };

            container.CreateAndAddLabelRow("Reaction Balance");

            txtEquation = container.CreateAndAddLabelRow2("");

            container.CreateAndAddLabelRow("Temperature Limits");

            var nf = flowsheet.FlowsheetOptions.NumberFormat;
            var su = flowsheet.FlowsheetOptions.SelectedUnitSystem;

            container.CreateAndAddTextBoxRow(nf, "Minimum Temperature (" + su.temperature + ")", rx.Tmin.ConvertFromSI(su.temperature), (sender, e) => { if (sender.Text.IsValidDouble())
                                                                                                                                                         {
                                                                                                                                                             rx.Tmin = sender.Text.ToDoubleFromCurrent().ConvertToSI(su.temperature);
                                                                                                                                                         }
                                             });
            container.CreateAndAddTextBoxRow(nf, "Maximum Temperature (" + su.temperature + ")", rx.Tmax.ConvertFromSI(su.temperature), (sender, e) => { if (sender.Text.IsValidDouble())
                                                                                                                                                         {
                                                                                                                                                             rx.Tmax = sender.Text.ToDoubleFromCurrent().ConvertToSI(su.temperature);
                                                                                                                                                         }
                                             });

            container.CreateAndAddLabelRow("Reaction Phase");

            var rxphaseselector = container.CreateAndAddDropDownRow("Reaction Phase", Shared.StringArrays.reactionphase().ToList(), 0, null);

            switch (rx.ReactionPhase)
            {
            case Interfaces.Enums.PhaseName.Mixture:
                rxphaseselector.SelectedIndex = (0);
                break;

            case Interfaces.Enums.PhaseName.Vapor:
                rxphaseselector.SelectedIndex = (1);
                break;

            case Interfaces.Enums.PhaseName.Liquid:
                rxphaseselector.SelectedIndex = (2);
                break;
            }

            rxphaseselector.SelectedIndexChanged += (sender, e) =>
            {
                switch (rxphaseselector.SelectedIndex)
                {
                case 0:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Mixture;
                    break;

                case 1:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Vapor;
                    break;

                case 2:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Liquid;
                    break;
                }
            };

            UpdateEquation();
        }
Exemple #2
0
        void Initialize()
        {
            container.CreateAndAddLabelRow("Reaction ID");

            container.CreateAndAddStringEditorRow2("Name", "", rx.Name, (sender, e) => { rx.Name = sender.Text; });

            container.CreateAndAddLabelRow("Compounds and Stoichiometry (Include / Name / Heat of Formation (kJ/kg) / Stoich. Coeff.)");

            var compcontainer = new DynamicLayout();
            //compcontainer.BackgroundColor = Colors.White;

            Double val;

            foreach (ICompoundConstantProperties comp in flowsheet.SelectedCompounds.Values)
            {
                var chk = new CheckBox()
                {
                    Text = comp.Name, Checked = (rx.Components.ContainsKey(comp.Name) ? true : false)
                };
                chk.CheckedChanged += (sender, e) =>
                {
                    if (!rx.Components.ContainsKey(comp.Name))
                    {
                        rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, 0, false, 0, 0));
                    }
                    else
                    {
                        rx.Components.Remove(comp.Name);
                    }
                    UpdateEquation();
                };

                var sc = new TextBox()
                {
                    Width = (int)(sf * 50), Text = (rx.Components.ContainsKey(comp.Name) ? rx.Components[comp.Name].StoichCoeff.ToString() : 0.0f.ToString())
                };

                sc.TextChanged += (sender, e) =>
                {
                    if (Double.TryParse(sc.Text.ToString(), out val))
                    {
                        sc.TextColor = SystemColors.ControlText;
                        if (!rx.Components.ContainsKey(comp.Name))
                        {
                            rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, Double.Parse(sc.Text), false, 0, 0));
                        }
                        else
                        {
                            rx.Components[comp.Name].StoichCoeff = double.Parse(sc.Text);
                        }
                        UpdateEquation();
                    }
                    else
                    {
                        sc.TextColor = Colors.Red;
                    }
                };


                var hf = new TextBox()
                {
                    Enabled = false, Width = (int)(sf * 100), Text = comp.IG_Enthalpy_of_Formation_25C.ToString("N2")
                };

                compcontainer.Add(new TableRow(chk, null, hf, sc));
            }

            container.CreateAndAddControlRow(compcontainer);
            container.CreateAndAddEmptySpace();

            var comps = flowsheet.SelectedCompounds.Values.Select((x) => x.Name).ToList();

            comps.Insert(0, "");

            container.CreateAndAddLabelRow("Base Compound");

            var basecompselector = container.CreateAndAddDropDownRow("Base Compound", comps, 0, null);

            var basecomp = rx.Components.Values.Where((x) => x.IsBaseReactant).FirstOrDefault();

            if (basecomp != null)
            {
                basecompselector.SelectedIndex = comps.IndexOf(basecomp.CompName);
            }
            else
            {
                basecompselector.SelectedIndex = 0;
            }

            basecompselector.SelectedIndexChanged += (sender, e) =>
            {
                if (rx.Components.ContainsKey(comps[basecompselector.SelectedIndex]))
                {
                    foreach (var rxc in rx.Components.Values)
                    {
                        rxc.IsBaseReactant = false;
                    }
                    rx.Components[comps[basecompselector.SelectedIndex]].IsBaseReactant = true;
                    rx.BaseReactant = comps[basecompselector.SelectedIndex];
                }
            };

            container.CreateAndAddLabelRow("Reaction Balance");

            txtEquation = container.CreateAndAddLabelRow2("");

            container.CreateAndAddLabelRow("Reaction Phase");

            var rxphaseselector = container.CreateAndAddDropDownRow("Reaction Phase", Shared.StringArrays.reactionphase().ToList(), 0, null);

            switch (rx.ReactionPhase)
            {
            case Interfaces.Enums.PhaseName.Mixture:
                rxphaseselector.SelectedIndex = 0;
                break;

            case Interfaces.Enums.PhaseName.Vapor:
                rxphaseselector.SelectedIndex = 1;
                break;

            case Interfaces.Enums.PhaseName.Liquid:
                rxphaseselector.SelectedIndex = 2;
                break;
            }

            rxphaseselector.SelectedIndexChanged += (sender, e) =>
            {
                switch (rxphaseselector.SelectedIndex)
                {
                case 0:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Mixture;
                    break;

                case 1:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Vapor;
                    break;

                case 2:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Liquid;
                    break;
                }
            };

            container.CreateAndAddLabelRow("Reaction Basis");

            var rxbasisselector = container.CreateAndAddDropDownRow("Reaction Basis", Shared.StringArrays.reactionbasis().ToList(), 0, null);

            switch (rx.ReactionBasis)
            {
            case Interfaces.Enums.ReactionBasis.Activity:
                rxbasisselector.SelectedIndex = (0);
                break;

            case Interfaces.Enums.ReactionBasis.Fugacity:
                rxbasisselector.SelectedIndex = (1);
                break;

            case Interfaces.Enums.ReactionBasis.MassConc:
                rxbasisselector.SelectedIndex = (2);
                break;

            case Interfaces.Enums.ReactionBasis.MassFrac:
                rxbasisselector.SelectedIndex = (3);
                break;

            case Interfaces.Enums.ReactionBasis.MolarConc:
                rxbasisselector.SelectedIndex = (4);
                break;

            case Interfaces.Enums.ReactionBasis.MolarFrac:
                rxbasisselector.SelectedIndex = (5);
                break;

            case Interfaces.Enums.ReactionBasis.PartialPress:
                rxbasisselector.SelectedIndex = (6);
                break;
            }

            rxbasisselector.SelectedIndexChanged += (sender, e) =>
            {
                switch (rxbasisselector.SelectedIndex)
                {
                case 0:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.Activity;
                    break;

                case 1:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.Fugacity;
                    break;

                case 2:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MassConc;
                    break;

                case 3:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MassFrac;
                    break;

                case 4:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MolarConc;
                    break;

                case 5:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MolarFrac;
                    break;

                case 6:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.PartialPress;
                    break;
                }
            };

            container.CreateAndAddLabelRow("Rate Expressions");

            container.CreateAndAddLabelRow2("Reaction Rate Numerator Expression:");

            container.CreateAndAddMultilineTextBoxRow(rx.RateEquationNumerator, false, false, (sender, e) => rx.RateEquationNumerator = sender.Text);

            container.CreateAndAddLabelRow2("Reaction Rate Denominator Expression:");

            container.CreateAndAddMultilineTextBoxRow(rx.RateEquationDenominator, false, false, (sender, e) => rx.RateEquationDenominator = sender.Text);

            container.CreateAndAddDescriptionRow("Reaction Rate (r) = f(T, Ri, Pi) = Numerator / Denominator");

            container.CreateAndAddDescriptionRow("Expression Variables: Temperature (T) in K, reactant amounts (R1, R2, ..., Rn) and product amounts (P1, P2, ..., Pn in the selected amount units, Reaction Rate (r) in the selected velocity units.");

            container.CreateAndAddLabelRow("Units");

            var us    = new DWSIM.SharedClasses.SystemsOfUnits.Units();
            var units = us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.molar_conc);

            units.AddRange(us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.mass_conc));
            units.AddRange(us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.pressure));
            units.Insert(0, "");

            container.CreateAndAddDropDownRow("Amount Units", units, units.IndexOf(rx.ConcUnit), (sender, e) => rx.ConcUnit = sender.SelectedValue.ToString());

            var units2 = us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.reac_rate_heterog);

            units2.Insert(0, "");

            container.CreateAndAddDropDownRow("Velocity Units", units2, units2.IndexOf(rx.VelUnit), (sender, e) => rx.VelUnit = sender.SelectedValue.ToString());

            UpdateEquation();
        }
        void Initialize()
        {
            var su  = column.GetFlowsheet().FlowsheetOptions.SelectedUnitSystem;
            var nf  = column.GetFlowsheet().FlowsheetOptions.NumberFormat;
            var nff = column.GetFlowsheet().FlowsheetOptions.FractionNumberFormat;

            s.CreateAndAddLabelRow(container, "Distillation Column Editor");

            s.CreateAndAddDescriptionRow(container, "Property values are updated/stored as they are changed/edited. There's no need to press ENTER to commit the changes.");

            if ((Inspector.Host.Items.Where(x => x.Name.Contains(column.GraphicObject.Tag)).Count() > 0))
            {
                var ctn = new DynamicLayout();
                ctn.BackgroundColor = Colors.LightGrey;
                s.CreateAndAddLabelRow(ctn, "Inspector Reports");
                s.CreateAndAddLabelAndButtonRow(ctn, "An Inspector Report is ready for viewing.", "View Report", null, (btn, e) => {
                    var f = s.GetDefaultEditorForm("Inspector Report for '" + column.GraphicObject.Tag + "'", 1024, 768, Inspector.Window2_Eto.GetInspectorWindow(column), false);
                    f.Show();
                });
                container.Add(ctn);
            }

            s.CreateAndAddLabelRow(container, "Column Details");

            s.CreateAndAddTwoLabelsRow(container, "Type", column.GetDisplayName());

            s.CreateAndAddTwoLabelsRow(container, "Status", column.GraphicObject.Active ? "Active" : "Inactive");

            s.CreateAndAddStringEditorRow(container, "Name", column.GraphicObject.Tag, (TextBox arg3, EventArgs ev) =>
            {
                column.GraphicObject.Tag = arg3.Text;
                column.GetFlowsheet().UpdateInterface();
            }, () => {
                column.GetFlowsheet().UpdateOpenEditForms();
            });

            s.CreateAndAddLabelRow(container, "Property Package");

            var proppacks = column.GetFlowsheet().PropertyPackages.Values.Select((x) => x.Tag).ToList();

            if (proppacks.Count == 0)
            {
                column.GetFlowsheet().ShowMessage("Error: please add at least one Property Package before continuing.", IFlowsheet.MessageType.GeneralError);
            }
            else
            {
                var    pp         = column.PropertyPackage;
                string selectedpp = "";
                if (pp != null)
                {
                    selectedpp = pp.Tag;
                }
                s.CreateAndAddDropDownRow(container, "Property Package", proppacks, proppacks.IndexOf(selectedpp), (DropDown arg1, EventArgs ev) =>
                {
                    if (proppacks.Count > 0)
                    {
                        column.PropertyPackage = (IPropertyPackage)column.GetFlowsheet().PropertyPackages.Values.Where((x) => x.Tag == proppacks[arg1.SelectedIndex]).FirstOrDefault();
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
            }

            s.CreateAndAddLabelRow(container, "Object Properties");

            s.CreateAndAddButtonRow(container, "Define Number of Stages", null, (arg1, e) =>
            {
                var np                  = new Eto.Forms.NumericStepper();
                np.MinValue             = 3;
                np.MaxValue             = 100;
                np.MaximumDecimalPlaces = 0;
                np.Value                = column.NumberOfStages;
                np.ValueChanged        += (sender, e2) =>
                {
                    var refval            = (int)np.Value;
                    column.NumberOfStages = refval;
                    int ne, nep, dif, i;
                    ne  = refval;
                    nep = column.Stages.Count;
                    dif = ne - nep;
                    if (dif != 0)
                    {
                        if (dif < 0)
                        {
                            column.Stages.RemoveRange(ne - 1, -dif);
                        }
                        else if (dif > 0)
                        {
                            for (i = 0; i <= dif; i++)
                            {
                                column.Stages.Insert(column.Stages.Count - 1, new Stage(Guid.NewGuid().ToString())
                                {
                                    P = 101325, Efficiency = 1.0f
                                });
                                column.Stages[column.Stages.Count - 2].Name = "Stage " + (column.Stages.Count - 2).ToString();
                            }
                        }
                    }
                };

                s.CreateDialog(np, "Set Number of Stages").ShowModal(container);
            });

            s.CreateAndAddButtonRow(container, "Edit Stages", null, (arg1, e) =>
            {
                var sview = DWSIM.UI.Shared.Common.GetDefaultContainer();

                s.CreateAndAddLabelRow(sview, "Edit Stages");
                s.CreateAndAddLabelRow(sview, "Number / Name / Pressure");
                var tlist = new List <TextBox>();
                foreach (var stage in column.Stages)
                {
                    tlist.Add(s.CreateAndAddDoubleTextBoxRow(sview, nf, (column.Stages.IndexOf(stage) + 1).ToString(), stage.Name, cv.ConvertFromSI(su.pressure, stage.P),
                                                             (arg10, arg20) =>
                    {
                        stage.Name = arg10.Text;
                    }, (arg11, arg22) =>
                    {
                        if (s.IsValidDouble(arg11.Text))
                        {
                            stage.P = cv.ConvertToSI(su.pressure, Double.Parse(arg11.Text));
                            if (column.Stages.IndexOf(stage) == 0)
                            {
                                column.CondenserPressure = stage.P;
                            }
                            else if (column.Stages.IndexOf(stage) == column.Stages.Count - 1)
                            {
                                column.ReboilerPressure = stage.P;
                            }
                        }
                    }));
                }
                s.CreateAndAddLabelAndButtonRow(sview, "Interpolate Pressures", "Interpolate", null, (sender2, e2) => {
                    var first = tlist[0].Text.ToDoubleFromCurrent();
                    var last  = tlist[tlist.Count - 1].Text.ToDoubleFromCurrent();
                    var n     = tlist.Count;
                    int i     = 1;
                    for (i = 1; i < n - 1; i++)
                    {
                        tlist[i].Text = (first + (last - first) * i / (n - 1)).ToString(nf);
                    }
                });
                s.CreateAndAddDescriptionRow(sview, "Calculate inner pressures using end stage defined values.");

                var scroll     = new Eto.Forms.Scrollable();
                scroll.Content = sview;

                s.CreateDialog(scroll, "Edit Stages", 600, 600).ShowModal(container);
            });

            var istrs   = column.GraphicObject.InputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Feed")).Select((x2) => x2.AttachedConnector.AttachedFrom.Name).ToList();
            var ostrs   = column.GraphicObject.OutputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Side")).Select((x2) => x2.AttachedConnector.AttachedTo.Name).ToList();
            var dist    = column.GraphicObject.OutputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Distillate")).Select((x2) => x2.AttachedConnector.AttachedTo.Name).ToList();
            var ov      = column.GraphicObject.OutputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Overhead")).Select((x2) => x2.AttachedConnector.AttachedTo.Name).ToList();
            var bottoms = column.GraphicObject.OutputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Bottoms")).Select((x2) => x2.AttachedConnector.AttachedTo.Name).ToList();
            var rduty   = column.GraphicObject.InputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Reboiler")).Select((x2) => x2.AttachedConnector.AttachedFrom.Name).ToList();
            var cduty   = column.GraphicObject.OutputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Condenser")).Select((x2) => x2.AttachedConnector.AttachedTo.Name).ToList();

            foreach (var id in istrs)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.Feed
                    });
                }
            }
            foreach (var id in ostrs)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.Sidedraw
                    });
                }
            }
            foreach (var id in dist)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.Distillate
                    });
                }
            }
            foreach (var id in ov)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.OverheadVapor
                    });
                }
            }
            foreach (var id in bottoms)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.BottomsLiquid
                    });
                }
            }
            List <string> remove = new List <string>();

            foreach (var si in column.MaterialStreams.Values)
            {
                if (!istrs.Contains(si.StreamID) && !ostrs.Contains(si.StreamID) && !ov.Contains(si.StreamID) && !dist.Contains(si.StreamID) && !bottoms.Contains(si.StreamID))
                {
                    remove.Add(si.ID);
                }
                if (!column.GetFlowsheet().SimulationObjects.ContainsKey(si.StreamID))
                {
                    remove.Add(si.ID);
                }
            }
            foreach (var id in remove)
            {
                if (column.MaterialStreams.ContainsKey(id))
                {
                    column.MaterialStreams.Remove(id);
                }
            }

            foreach (var id in cduty)
            {
                if (column.EnergyStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.EnergyStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Energy,
                        StreamBehavior = StreamInformation.Behavior.Distillate
                    });
                }
            }
            foreach (var id in rduty)
            {
                if (column.EnergyStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.EnergyStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Energy,
                        StreamBehavior = StreamInformation.Behavior.BottomsLiquid
                    });
                }
            }
            List <string> remove2 = new List <string>();

            foreach (var si in column.EnergyStreams.Values)
            {
                if (!rduty.Contains(si.StreamID) && !cduty.Contains(si.StreamID))
                {
                    remove2.Add(si.ID);
                }
                if (!column.GetFlowsheet().SimulationObjects.ContainsKey(si.StreamID))
                {
                    remove2.Add(si.ID);
                }
            }
            foreach (var id in remove2)
            {
                if (column.EnergyStreams.ContainsKey(id))
                {
                    column.EnergyStreams.Remove(id);
                }
            }

            var stageNames = column.Stages.Select((x) => x.Name).ToList();

            stageNames.Insert(0, "");
            var stageIDs = column.Stages.Select((x) => x.ID).ToList();

            stageIDs.Insert(0, "");

            s.CreateAndAddLabelRow(container, "Streams");

            foreach (var si in column.MaterialStreams.Values)
            {
                if (si.StreamBehavior == StreamInformation.Behavior.Feed)
                {
                    s.CreateAndAddDropDownRow(container, "[FEED] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
                else if (si.StreamBehavior == StreamInformation.Behavior.Sidedraw)
                {
                    s.CreateAndAddDropDownRow(container, "[SIDEDRAW] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
                else if (si.StreamBehavior == StreamInformation.Behavior.OverheadVapor)
                {
                    s.CreateAndAddDropDownRow(container, "[OVH_VAPOR] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
                else if (si.StreamBehavior == StreamInformation.Behavior.Distillate)
                {
                    s.CreateAndAddDropDownRow(container, "[DISTILLATE] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
                else if (si.StreamBehavior == StreamInformation.Behavior.BottomsLiquid)
                {
                    s.CreateAndAddDropDownRow(container, "[BOTTOMS] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
            }
            foreach (var si in column.EnergyStreams.Values)
            {
                if (si.StreamBehavior == StreamInformation.Behavior.Distillate)
                {
                    s.CreateAndAddDropDownRow(container, "[COND. DUTY] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
                else if (si.StreamBehavior == StreamInformation.Behavior.BottomsLiquid)
                {
                    s.CreateAndAddDropDownRow(container, "[REB. DUTY] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
            }

            s.CreateAndAddLabelRow(container, "Side Draw Specs");
            var sdphases = new List <string>()
            {
                "L", "V"
            };

            foreach (var si in column.MaterialStreams.Values)
            {
                string sp = "L";
                switch (si.StreamPhase)
                {
                case StreamInformation.Phase.L:
                    sp = "L";
                    break;

                case StreamInformation.Phase.V:
                    sp = "V";
                    break;

                case StreamInformation.Phase.B:
                case StreamInformation.Phase.None:
                    sp = "L";
                    break;
                }
                if (si.StreamBehavior == StreamInformation.Behavior.Sidedraw)
                {
                    s.CreateAndAddDropDownRow(container, column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag + " / Draw Phase",
                                              sdphases, sdphases.IndexOf(sp), (arg1, arg2) =>
                    {
                        switch (arg1.SelectedIndex)
                        {
                        case 0:
                            si.StreamPhase = StreamInformation.Phase.L;
                            break;

                        case 1:
                            si.StreamPhase = StreamInformation.Phase.V;
                            break;
                        }
                    });
                    s.CreateAndAddTextBoxRow(container, nf, column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag + " / Molar Flow (" + su.molarflow + ")",
                                             cv.ConvertFromSI(su.molarflow, si.FlowRate.Value), (arg1, arg2) =>
                    {
                        if (s.IsValidDouble(arg1.Text))
                        {
                            si.FlowRate.Value = cv.ConvertToSI(su.molarflow, Double.Parse(arg1.Text));
                        }
                    });
                }
            }

            var compounds = column.GetFlowsheet().SelectedCompounds.Keys.ToList();

            compounds.Insert(0, "");
            var specs = StringResources.columnspec();
            var units = su.GetUnitSet(Interfaces.Enums.UnitOfMeasure.molarflow);

            units.AddRange(su.GetUnitSet(Interfaces.Enums.UnitOfMeasure.massflow));
            units.AddRange(su.GetUnitSet(Interfaces.Enums.UnitOfMeasure.heatflow));
            units.AddRange(su.GetUnitSet(Interfaces.Enums.UnitOfMeasure.temperature));
            units.AddRange(new[] { "% M/M", "% W/W", "M", "We" });
            units.Insert(0, "");
            int cspec = 0, rspec = 0;

            switch (column.Specs["C"].SType)
            {
            case ColumnSpec.SpecType.Product_Molar_Flow_Rate:
                cspec = 0;
                break;

            case ColumnSpec.SpecType.Product_Mass_Flow_Rate:
                cspec = 1;
                break;

            case ColumnSpec.SpecType.Stream_Ratio:
                cspec = 2;
                break;

            case ColumnSpec.SpecType.Heat_Duty:
                cspec = 3;
                break;

            case ColumnSpec.SpecType.Component_Mass_Flow_Rate:
                cspec = 4;
                break;

            case ColumnSpec.SpecType.Component_Molar_Flow_Rate:
                cspec = 5;
                break;

            case ColumnSpec.SpecType.Component_Recovery:
                cspec = 6;
                break;

            case ColumnSpec.SpecType.Component_Fraction:
                cspec = 7;
                break;

            case ColumnSpec.SpecType.Temperature:
                cspec = 8;
                break;
            }

            switch (column.Specs["R"].SType)
            {
            case ColumnSpec.SpecType.Product_Molar_Flow_Rate:
                rspec = 0;
                break;

            case ColumnSpec.SpecType.Product_Mass_Flow_Rate:
                rspec = 1;
                break;

            case ColumnSpec.SpecType.Stream_Ratio:
                rspec = 2;
                break;

            case ColumnSpec.SpecType.Heat_Duty:
                rspec = 3;
                break;

            case ColumnSpec.SpecType.Component_Mass_Flow_Rate:
                rspec = 4;
                break;

            case ColumnSpec.SpecType.Component_Molar_Flow_Rate:
                rspec = 5;
                break;

            case ColumnSpec.SpecType.Component_Recovery:
                rspec = 6;
                break;

            case ColumnSpec.SpecType.Component_Fraction:
                rspec = 7;
                break;

            case ColumnSpec.SpecType.Temperature:
                rspec = 8;
                break;
            }

            s.CreateAndAddLabelRow(container, "Condenser Specification");
            s.CreateAndAddDropDownRow(container, "Specification", specs.ToList(), cspec, (arg1, arg2) =>
            {
                switch (arg1.SelectedIndex)
                {
                case 0:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Product_Molar_Flow_Rate;
                    break;

                case 1:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Product_Mass_Flow_Rate;
                    break;

                case 2:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Stream_Ratio;
                    break;

                case 3:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Heat_Duty;
                    break;

                case 4:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Component_Mass_Flow_Rate;
                    break;

                case 5:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Component_Molar_Flow_Rate;
                    break;

                case 6:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Component_Recovery;
                    break;

                case 7:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Component_Fraction;
                    break;

                case 8:
                    column.Specs["C"].SType = ColumnSpec.SpecType.Temperature;
                    break;
                }
            });
            var cid = 0;

            if (compounds.Contains(column.Specs["C"].ComponentID))
            {
                cid = compounds.IndexOf(column.Specs["C"].ComponentID);
            }
            s.CreateAndAddDropDownRow(container, "Compound", compounds, cid, (arg3, e) =>
            {
                column.Specs["C"].ComponentID = compounds[arg3.SelectedIndex];
            });
            s.CreateAndAddTextBoxRow(container, nf, "Value", column.Specs["C"].SpecValue, (arg1, arg2) =>
            {
                if (s.IsValidDouble(arg1.Text))
                {
                    column.Specs["C"].SpecValue = Double.Parse(arg1.Text);
                }
            }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                       {
                           ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                       }
                });
            s.CreateAndAddDropDownRow(container, "Units", units, units.IndexOf(column.Specs["C"].SpecUnit),
                                      (arg1, arg2) =>
            {
                column.Specs["C"].SpecUnit = units[arg1.SelectedIndex];
            });

            s.CreateAndAddLabelRow(container, "Reboiler Specification");
            s.CreateAndAddDropDownRow(container, "Specification", specs.ToList(), rspec, (arg1, arg2) =>
            {
                switch (arg1.SelectedIndex)
                {
                case 0:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Product_Molar_Flow_Rate;
                    break;

                case 1:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Product_Mass_Flow_Rate;
                    break;

                case 2:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Stream_Ratio;
                    break;

                case 3:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Heat_Duty;
                    break;

                case 4:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Component_Mass_Flow_Rate;
                    break;

                case 5:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Component_Molar_Flow_Rate;
                    break;

                case 6:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Component_Recovery;
                    break;

                case 7:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Component_Fraction;
                    break;

                case 8:
                    column.Specs["R"].SType = ColumnSpec.SpecType.Temperature;
                    break;
                }
            });
            var cid2 = 0;

            if (compounds.Contains(column.Specs["R"].ComponentID))
            {
                cid2 = compounds.IndexOf(column.Specs["R"].ComponentID);
            }
            s.CreateAndAddDropDownRow(container, "Compound", compounds, cid2, (arg3, e) =>
            {
                column.Specs["R"].ComponentID = compounds[arg3.SelectedIndex];
            });
            s.CreateAndAddTextBoxRow(container, nf, "Value", column.Specs["R"].SpecValue, (arg1, arg2) =>
            {
                if (s.IsValidDouble(arg1.Text))
                {
                    column.Specs["R"].SpecValue = Double.Parse(arg1.Text);
                }
            }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                       {
                           ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                       }
                });
            s.CreateAndAddDropDownRow(container, "Units", units, units.IndexOf(column.Specs["R"].SpecUnit),
                                      (arg1, arg2) =>
            {
                column.Specs["R"].SpecUnit = units[arg1.SelectedIndex];
            });

            s.CreateAndAddTextBoxRow(container, "N0", "Maximum Iterations", column.MaxIterations,
                                     (sender, e) =>
            {
                if (sender.Text.IsValidDouble())
                {
                    column.MaxIterations = (int)sender.Text.ToDoubleFromCurrent();
                }
            }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                       {
                           ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                       }
                });

            s.CreateAndAddTextBoxRow(container, nf, "Convergence Tolerance (External Loop)", column.ExternalLoopTolerance,
                                     (sender, e) =>
            {
                if (sender.Text.IsValidDouble())
                {
                    column.ExternalLoopTolerance = sender.Text.ToDoubleFromCurrent();
                }
            }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                       {
                           ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                       }
                });

            s.CreateAndAddTextBoxRow(container, nf, "Convergence Tolerance (Internal Loop)", column.InternalLoopTolerance,
                                     (sender, e) =>
            {
                if (sender.Text.IsValidDouble())
                {
                    column.InternalLoopTolerance = sender.Text.ToDoubleFromCurrent();
                }
            }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                       {
                           ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                       }
                });

            s.CreateAndAddEmptySpace(container);
            s.CreateAndAddEmptySpace(container);
            s.CreateAndAddEmptySpace(container);
        }
Exemple #4
0
        private TabControl ConstructMainTabControl()
        {
            // Main log list
            var logList = new LogList(ApiData, LogDataProcessor, UploadProcessor, ImageProvider, LogNameProvider);

            LogCollectionsRecreated += (sender, args) => logList.DataStore = logsFiltered;

            LogDataProcessor.Processed += (sender, args) =>
            {
                bool last = args.CurrentScheduledItems == 0;

                if (last || gridRefreshCooldown.TryUse(DateTime.Now))
                {
                    Application.Instance.AsyncInvoke(() => { logList.ReloadData(); });
                }
            };
            // Player list
            var playerList = new PlayerList(ApiData, LogDataProcessor, UploadProcessor, ImageProvider, LogNameProvider);

            FilteredLogsUpdated += (sender, args) => playerList.UpdateDataFromLogs(logsFiltered);

            // Guild list
            var guildList = new GuildList(ApiData, LogDataProcessor, UploadProcessor, ImageProvider, LogNameProvider);

            FilteredLogsUpdated += (sender, args) => guildList.UpdateDataFromLogs(logsFiltered);

            // Statistics
            var statistics = new StatisticsSection(ImageProvider, LogNameProvider);

            FilteredLogsUpdated += (sender, args) => statistics.UpdateDataFromLogs(logsFiltered.ToList());

            // Game data collecting
            var gameDataCollecting = new GameDataCollecting(logList);
            var gameDataPage       = new TabPage
            {
                Text = "Game data", Content = gameDataCollecting, Visible = Settings.ShowDebugData
            };

            Settings.ShowDebugDataChanged += (sender, args) => gameDataPage.Visible = Settings.ShowDebugData;

            // Service status
            var serviceStatus = new DynamicLayout {
                Spacing = new Size(10, 10), Padding = new Padding(5)
            };

            serviceStatus.BeginHorizontal();
            {
                serviceStatus.Add(new GroupBox
                {
                    Text    = "Uploads",
                    Content = new BackgroundProcessorDetail {
                        BackgroundProcessor = UploadProcessor
                    }
                }, xscale: true);
                serviceStatus.Add(new GroupBox
                {
                    Text    = "Guild Wars 2 API",
                    Content = new BackgroundProcessorDetail {
                        BackgroundProcessor = ApiProcessor
                    }
                }, xscale: true);
                serviceStatus.Add(new GroupBox
                {
                    Text    = "Log parsing",
                    Content = new BackgroundProcessorDetail {
                        BackgroundProcessor = LogDataProcessor
                    }
                }, xscale: true);
            }
            serviceStatus.AddRow(null);
            var servicePage = new TabPage
            {
                Text = "Services", Content = serviceStatus, Visible = Settings.ShowDebugData
            };

            Settings.ShowDebugDataChanged += (sender, args) => servicePage.Visible = Settings.ShowDebugData;

            var tabs = new TabControl();

            tabs.Pages.Add(new TabPage {
                Text = "Logs", Content = logList
            });
            tabs.Pages.Add(new TabPage {
                Text = "Players", Content = playerList
            });
            tabs.Pages.Add(new TabPage {
                Text = "Guilds", Content = guildList
            });
            tabs.Pages.Add(new TabPage {
                Text = "Statistics", Content = statistics
            });
            tabs.Pages.Add(gameDataPage);
            tabs.Pages.Add(servicePage);

            // This is needed to avoid a Gtk platform issue where the tab is changed to the last one.
            Shown += (sender, args) => tabs.SelectedIndex = 1;

            return(tabs);
        }
        Control LeftPane()
        {
            var layout = new DynamicLayout {
                DefaultSpacing = new Size(5, 5)
            };

            layout.BeginVertical();
            layout.BeginHorizontal();
            layout.Add(new Label {
                Text = "Label", VerticalAlignment = VerticalAlignment.Center
            });
            layout.AddCentered(new Button {
                Text = "Button"
            });
            layout.AddCentered(new LinkButton {
                Text = "LinkButton"
            });
            layout.Add(new Label {
                Text = "ImageView", VerticalAlignment = VerticalAlignment.Center
            });
            layout.Add(new ImageView {
                Image = icon1, Size = new Size(64, 64)
            });
            layout.Add(null);
            layout.EndHorizontal();

            layout.EndBeginVertical();

            layout.AddSeparateRow(new CheckBox {
                Text = "CheckBox", ThreeState = true
            }, RadioButtons(), null);
            layout.AddSeparateRow(new TextBox {
                Text = "TextBox", Size = new Size(150, -1)
            }, "PasswordBox", new PasswordBox {
                Text = "PasswordBox", Size = new Size(150, -1)
            }, null);
            layout.AddSeparateRow(DropDown(), ComboBox(), null);
            layout.AddSeparateRow("Stepper", new Stepper(), "NumericStepper", new NumericStepper {
                Value = 50, DecimalPlaces = 1
            }, new TextStepper {
                Text = "TextStepper"
            }, null);

            layout.BeginVertical();
            layout.BeginHorizontal();
            layout.BeginVertical();
            layout.AddSeparateRow("DateTimePicker", new DateTimePicker {
                Value = DateTime.Now
            }, null);
            layout.AddSeparateRow(new TextArea {
                Text = "TextArea", Size = new Size(150, 50)
            }, CreateRichTextArea(), null);
            layout.AddSeparateRow(ListBox(), new GroupBox {
                Text = "GroupBox", Content = new Label {
                    Text = "I'm in a group box"
                }
            }, null);
            layout.EndVertical();
            layout.AddSeparateColumn("Calendar", new Calendar(), null);
            layout.EndHorizontal();
            layout.EndVertical();

            layout.AddSeparateRow("Slider", new Slider {
                Value = 50, TickFrequency = 10
            });
            layout.AddSeparateRow("ProgressBar", new ProgressBar {
                Value = 25, Width = 100
            }, "Spinner", new Spinner {
                Enabled = true
            }, null);
            layout.EndVertical();

            layout.EndVertical();
            layout.Add(null);

            return(layout);
        }
Exemple #6
0
		public MessageBoxSection()
		{
			MessageBoxText = "Some message";
			MessageBoxCaption = "Some caption";
			AttachToParent = true;

			var layout = new DynamicLayout();

			layout.AddSeparateRow(null, new Label { Text = "Caption" }, CaptionBox(), null);
			layout.AddSeparateRow(null, new Label { Text = "Text" }, TitleBox(), null);

			layout.BeginVertical(Padding.Empty);

			layout.BeginHorizontal();
			layout.Add(null);
			layout.Add(new Label { Text = "Type", VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Right });
			layout.Add(MessageBoxTypeCombo());
			layout.Add(AttachToParentCheckBox());
			layout.Add(null);
			layout.EndHorizontal();

			layout.EndBeginVertical();
			layout.BeginHorizontal();
			layout.Add(null);
			layout.Add(new Label { Text = "Buttons", VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Right });
			layout.Add(MessageBoxButtonsCombo());
			layout.Add(new Label { Text = "Default Button", VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Right });
			layout.Add(MessageBoxDefaultButtonCombo());
			layout.Add(null);
			layout.EndHorizontal();

			layout.EndVertical();

			layout.AddSeparateRow(null, ShowDialogButton(), null);
			layout.Add(null);

			Content = layout;
		}
Exemple #7
0
        void Initialize()
        {
            var su  = column.GetFlowsheet().FlowsheetOptions.SelectedUnitSystem;
            var nf  = column.GetFlowsheet().FlowsheetOptions.NumberFormat;
            var nff = column.GetFlowsheet().FlowsheetOptions.FractionNumberFormat;

            s.CreateAndAddLabelRow(container, "Absorption Column Editor");

            s.CreateAndAddDescriptionRow(container, "Property values are updated/stored as they are changed/edited. There's no need to press ENTER to commit the changes.");

            if ((Inspector.Host.Items.Where(x => x.Name.Contains(column.GraphicObject.Tag)).Count() > 0))
            {
                var ctn = new DynamicLayout();
                ctn.BackgroundColor = Colors.LightGrey;
                s.CreateAndAddLabelRow(ctn, "Inspector Reports");
                s.CreateAndAddLabelAndButtonRow(ctn, "An Inspector Report is ready for viewing.", "View Report", null, (btn, e) => {
                    var f = s.GetDefaultEditorForm("Inspector Report for '" + column.GraphicObject.Tag + "'", 1024, 768, Inspector.Window2_Eto.GetInspectorWindow(column), false);
                    f.Show();
                });
                container.Add(ctn);
            }

            s.CreateAndAddLabelRow(container, "Column Details");

            s.CreateAndAddTwoLabelsRow(container, "Type", column.GetDisplayName());

            s.CreateAndAddTwoLabelsRow(container, "Status", column.GraphicObject.Active ? "Active" : "Inactive");

            s.CreateAndAddStringEditorRow(container, "Name", column.GraphicObject.Tag, (TextBox arg3, EventArgs ev) =>
            {
                column.GraphicObject.Tag = arg3.Text;
                column.GetFlowsheet().UpdateInterface();
            }, () => {
                column.GetFlowsheet().UpdateOpenEditForms();
            });

            s.CreateAndAddLabelRow(container, "Property Package");

            var proppacks = column.GetFlowsheet().PropertyPackages.Values.Select((x) => x.Tag).ToList();

            if (proppacks.Count == 0)
            {
                column.GetFlowsheet().ShowMessage("Error: please add at least one Property Package before continuing.", IFlowsheet.MessageType.GeneralError);
            }
            else
            {
                var    pp         = column.PropertyPackage;
                string selectedpp = "";
                if (pp != null)
                {
                    selectedpp = pp.Tag;
                }
                s.CreateAndAddDropDownRow(container, "Property Package", proppacks, proppacks.IndexOf(selectedpp), (DropDown arg1, EventArgs ev) =>
                {
                    if (proppacks.Count > 0)
                    {
                        column.PropertyPackage = (IPropertyPackage)column.GetFlowsheet().PropertyPackages.Values.Where((x) => x.Tag == proppacks[arg1.SelectedIndex]).FirstOrDefault();
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
            }

            s.CreateAndAddLabelRow(container, "Object Properties");

            s.CreateAndAddDropDownRow(container, "Operating Mode", new List <string> {
                "Gas-Liquid Absorption", "Liquid-Liquid Extraction"
            }, (int)column.OperationMode, (arg1, e) => {
                switch (arg1.SelectedIndex)
                {
                case 0:
                    column.OperationMode = AbsorptionColumn.OpMode.Absorber;
                    break;

                case 1:
                    column.OperationMode = AbsorptionColumn.OpMode.Extractor;
                    break;
                }
            });

            s.CreateAndAddButtonRow(container, "Define Number of Stages", null, (arg1, e) =>
            {
                var np                  = new Eto.Forms.NumericStepper();
                np.MinValue             = 3;
                np.MaxValue             = 100;
                np.MaximumDecimalPlaces = 0;
                np.Value                = column.NumberOfStages;
                np.ValueChanged        += (sender, e2) =>
                {
                    var refval            = (int)np.Value;
                    column.NumberOfStages = refval;
                    int ne, nep, dif, i;
                    ne  = refval;
                    nep = column.Stages.Count;
                    dif = ne - nep;
                    if (dif != 0)
                    {
                        if (dif < 0)
                        {
                            column.Stages.RemoveRange(ne - 1, -dif);
                        }
                        else if (dif > 0)
                        {
                            for (i = 0; i <= dif; i++)
                            {
                                column.Stages.Insert(column.Stages.Count - 1, new Stage(Guid.NewGuid().ToString())
                                {
                                    P = 101325, Efficiency = 1.0f
                                });
                                column.Stages[column.Stages.Count - 2].Name = "Stage " + (column.Stages.Count - 2).ToString();
                            }
                        }
                    }
                };

                s.CreateDialog(np, "Set Number of Stages").ShowModal(container);
            });

            s.CreateAndAddButtonRow(container, "Edit Stages", null, (arg1, e) =>
            {
                var sview = DWSIM.UI.Shared.Common.GetDefaultContainer();

                s.CreateAndAddLabelRow(sview, "Edit Stages");
                s.CreateAndAddLabelRow(sview, "Number / Name / Pressure");
                var tlist = new List <TextBox>();
                foreach (var stage in column.Stages)
                {
                    tlist.Add(s.CreateAndAddDoubleTextBoxRow(sview, nf, (column.Stages.IndexOf(stage) + 1).ToString(), stage.Name, cv.ConvertFromSI(su.pressure, stage.P),
                                                             (arg10, arg20) =>
                    {
                        stage.Name = arg10.Text;
                    }, (arg11, arg22) =>
                    {
                        if (s.IsValidDouble(arg11.Text))
                        {
                            stage.P = cv.ConvertToSI(su.pressure, Double.Parse(arg11.Text));
                            if (column.Stages.IndexOf(stage) == 0)
                            {
                                column.CondenserPressure = stage.P;
                            }
                            else if (column.Stages.IndexOf(stage) == column.Stages.Count - 1)
                            {
                                column.ReboilerPressure = stage.P;
                            }
                        }
                    }));
                }
                s.CreateAndAddLabelAndButtonRow(sview, "Interpolate Pressures", "Interpolate", null, (sender2, e2) =>
                {
                    var first = tlist[0].Text.ToDoubleFromCurrent();
                    var last  = tlist[tlist.Count - 1].Text.ToDoubleFromCurrent();
                    var n     = tlist.Count;
                    int i     = 1;
                    for (i = 1; i < n - 1; i++)
                    {
                        tlist[i].Text = (first + (last - first) * i / (n - 1)).ToString(nf);
                    }
                });
                s.CreateAndAddDescriptionRow(sview, "Calculate inner pressures using end stage defined values.");

                var scroll     = new Eto.Forms.Scrollable();
                scroll.Content = sview;

                s.CreateDialog(scroll, "Edit Stages", 600, 600).ShowModal(container);
            });

            var istrs   = column.GraphicObject.InputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Feed")).Select((x2) => x2.AttachedConnector.AttachedFrom.Name).ToList();
            var ostrs   = column.GraphicObject.OutputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Side")).Select((x2) => x2.AttachedConnector.AttachedTo.Name).ToList();
            var dist    = column.GraphicObject.OutputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Top Product")).Select((x2) => x2.AttachedConnector.AttachedTo.Name).ToList();
            var bottoms = column.GraphicObject.OutputConnectors.Where((x) => x.IsAttached && x.ConnectorName.Contains("Bottoms Product")).Select((x2) => x2.AttachedConnector.AttachedTo.Name).ToList();

            foreach (var id in istrs)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.Feed
                    });
                }
            }
            foreach (var id in ostrs)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.Sidedraw
                    });
                }
            }
            foreach (var id in dist)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.OverheadVapor
                    });
                }
            }
            foreach (var id in bottoms)
            {
                if (column.MaterialStreams.Values.Where(x => x.StreamID == id).Count() == 0)
                {
                    column.MaterialStreams.Add(id, new StreamInformation()
                    {
                        StreamID       = id,
                        ID             = id,
                        StreamType     = StreamInformation.Type.Material,
                        StreamBehavior = StreamInformation.Behavior.BottomsLiquid
                    });
                }
            }
            List <string> remove = new List <string>();

            foreach (var si in column.MaterialStreams.Values)
            {
                if (!istrs.Contains(si.StreamID) && !ostrs.Contains(si.StreamID) && !dist.Contains(si.StreamID) && !bottoms.Contains(si.StreamID))
                {
                    remove.Add(si.ID);
                }
                if (!column.GetFlowsheet().SimulationObjects.ContainsKey(si.StreamID))
                {
                    remove.Add(si.ID);
                }
            }
            foreach (var id in remove)
            {
                if (column.MaterialStreams.ContainsKey(id))
                {
                    column.MaterialStreams.Remove(id);
                }
            }

            var stageNames = column.Stages.Select((x) => x.Name).ToList();

            stageNames.Insert(0, "");
            var stageIDs = column.Stages.Select((x) => x.ID).ToList();

            stageIDs.Insert(0, "");

            s.CreateAndAddLabelRow(container, "Streams");

            foreach (var si in column.MaterialStreams.Values)
            {
                if (si.StreamBehavior == StreamInformation.Behavior.Feed)
                {
                    s.CreateAndAddDropDownRow(container, "[FEED] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
                else if (si.StreamBehavior == StreamInformation.Behavior.Sidedraw)
                {
                    s.CreateAndAddDropDownRow(container, "[SIDEDRAW] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
                else if (si.StreamBehavior == StreamInformation.Behavior.Distillate || si.StreamBehavior == StreamInformation.Behavior.OverheadVapor)
                {
                    s.CreateAndAddDropDownRow(container, "[TOP PRODUCT] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
                else if (si.StreamBehavior == StreamInformation.Behavior.BottomsLiquid)
                {
                    s.CreateAndAddDropDownRow(container, "[BOTTOMS PRODUCT] " + column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag,
                                              stageNames, stageIDs.IndexOf(si.AssociatedStage), (arg1, arg2) =>
                    {
                        si.AssociatedStage = stageIDs[arg1.SelectedIndex];
                    });
                }
            }

            s.CreateAndAddLabelRow(container, "Side Draw Specs");
            var sdphases = new List <string>()
            {
                "L", "V"
            };

            foreach (var si in column.MaterialStreams.Values)
            {
                string sp = "L";
                switch (si.StreamPhase)
                {
                case StreamInformation.Phase.L:
                    sp = "L";
                    break;

                case StreamInformation.Phase.V:
                    sp = "V";
                    break;
                }
                if (si.StreamBehavior == StreamInformation.Behavior.Sidedraw)
                {
                    s.CreateAndAddDropDownRow(container, column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag + " / Draw Phase",
                                              sdphases, sdphases.IndexOf(sp), (arg1, arg2) =>
                    {
                        switch (arg1.SelectedIndex)
                        {
                        case 0:
                            si.StreamPhase = StreamInformation.Phase.L;
                            break;

                        case 1:
                            si.StreamPhase = StreamInformation.Phase.V;
                            break;
                        }
                    });
                    s.CreateAndAddTextBoxRow(container, nf, column.GetFlowsheet().SimulationObjects[si.StreamID].GraphicObject.Tag + " / Molar Flow (" + su.molarflow + ")",
                                             cv.ConvertFromSI(su.molarflow, si.FlowRate.Value), (arg1, arg2) =>
                    {
                        if (s.IsValidDouble(arg1.Text))
                        {
                            si.FlowRate.Value = cv.ConvertToSI(su.molarflow, Double.Parse(arg1.Text));
                        }
                    });
                }
            }

            s.CreateAndAddLabelRow(container, "Solver Settings");

            var methods = new string[] { "Burningham-Otto (Sum Rates)", "Napthali-Sandholm (Simultaneous Correction)" };

            if (column.SolvingMethodName.Contains("Wang"))
            {
                column.SolvingMethodName = "Burningham-Otto (Sum Rates)";
            }

            s.CreateAndAddDropDownRow(container, "Solving Method", methods.ToList(), methods.ToList().IndexOf(column.SolvingMethodName), (sender, e) =>
            {
                column.SolvingMethodName = sender.SelectedValue.ToString();
            });

            s.CreateAndAddTextBoxRow(container, "N0", "Maximum Iterations", column.MaxIterations,
                                     (sender, e) =>
            {
                if (sender.Text.IsValidDouble())
                {
                    column.MaxIterations = (int)sender.Text.ToDoubleFromCurrent();
                }
            }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                       {
                           ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                       }
                });

            s.CreateAndAddTextBoxRow(container, nf, "Convergence Tolerance", column.ExternalLoopTolerance,
                                     (sender, e) =>
            {
                if (sender.Text.IsValidDouble())
                {
                    column.ExternalLoopTolerance = sender.Text.ToDoubleFromCurrent();
                    column.InternalLoopTolerance = sender.Text.ToDoubleFromCurrent();
                }
            }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                       {
                           ((Shared.Flowsheet)column.GetFlowsheet()).HighLevelSolve.Invoke();
                       }
                });

            s.CreateAndAddEmptySpace(container);
            s.CreateAndAddEmptySpace(container);
            s.CreateAndAddEmptySpace(container);
        }
Exemple #8
0
        void Initialize()
        {
            container.CreateAndAddLabelRow("Reaction ID");

            container.CreateAndAddStringEditorRow2("Name", "", rx.Name, (sender, e) => { rx.Name = sender.Text; });

            container.CreateAndAddLabelRow("Compounds and Stoichiometry (Include / Name / Stoich. Coeff. / Direct Order Exponent / Reverse Order Exponent)");

            var compcontainer = new DynamicLayout();

            compcontainer.BackgroundColor = Colors.White;

            Double val;

            foreach (ICompoundConstantProperties comp in flowsheet.SelectedCompounds.Values)
            {
                var chk = new CheckBox()
                {
                    Text = comp.Name, Checked = (rx.Components.ContainsKey(comp.Name) ? true : false)
                };
                chk.CheckedChanged += (sender, e) =>
                {
                    if (!rx.Components.ContainsKey(comp.Name))
                    {
                        rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, 0, false, 0, 0));
                    }
                    else
                    {
                        rx.Components.Remove(comp.Name);
                    }
                    UpdateEquation();
                };

                var sc = new TextBox()
                {
                    Width = 30, Text = (rx.Components.ContainsKey(comp.Name) ? rx.Components[comp.Name].StoichCoeff.ToString() : 0.0f.ToString())
                };

                sc.TextChanged += (sender, e) =>
                {
                    if (Double.TryParse(sc.Text.ToString(), out val))
                    {
                        sc.TextColor = SystemColors.ControlText;
                        if (!rx.Components.ContainsKey(comp.Name))
                        {
                            rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, Double.Parse(sc.Text), false, 0, 0));
                        }
                        else
                        {
                            rx.Components[comp.Name].StoichCoeff = double.Parse(sc.Text);
                        }
                        UpdateEquation();
                    }
                    else
                    {
                        sc.TextColor = Colors.Red;
                    }
                };

                var txtdo = new TextBox()
                {
                    Width = 30, Text = (rx.Components.ContainsKey(comp.Name) ? rx.Components[comp.Name].DirectOrder.ToString() : 0.0f.ToString())
                };

                txtdo.TextChanged += (sender, e) =>
                {
                    if (Double.TryParse(txtdo.Text.ToString(), out val))
                    {
                        txtdo.TextColor = SystemColors.ControlText;
                        if (!rx.Components.ContainsKey(comp.Name))
                        {
                            rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, 0, false, Double.Parse(txtdo.Text), 0));
                        }
                        else
                        {
                            rx.Components[comp.Name].DirectOrder = double.Parse(txtdo.Text);
                        }
                        UpdateEquation();
                    }
                    else
                    {
                        txtdo.TextColor = Colors.Red;
                    }
                };

                var txtro = new TextBox()
                {
                    Width = 30, Text = (rx.Components.ContainsKey(comp.Name) ? rx.Components[comp.Name].ReverseOrder.ToString() : 0.0f.ToString())
                };

                txtro.TextChanged += (sender, e) =>
                {
                    if (Double.TryParse(txtro.Text.ToString(), out val))
                    {
                        txtro.TextColor = SystemColors.ControlText;
                        if (!rx.Components.ContainsKey(comp.Name))
                        {
                            rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, 0, false, 0, Double.Parse(txtro.Text)));
                        }
                        else
                        {
                            rx.Components[comp.Name].ReverseOrder = double.Parse(txtro.Text);
                        }
                        UpdateEquation();
                    }
                    else
                    {
                        txtro.TextColor = Colors.Red;
                    }
                };

                compcontainer.Add(new TableRow(chk, null, sc, txtdo, txtro));
            }

            container.CreateAndAddControlRow(compcontainer);
            container.CreateAndAddEmptySpace();

            var comps = flowsheet.SelectedCompounds.Values.Select((x) => x.Name).ToList();

            comps.Insert(0, "");

            container.CreateAndAddLabelRow("Base Compound");

            var basecompselector = container.CreateAndAddDropDownRow("Base Compound", comps, 0, null);

            var basecomp = rx.Components.Values.Where((x) => x.IsBaseReactant).FirstOrDefault();

            if (basecomp != null)
            {
                basecompselector.SelectedIndex = comps.IndexOf(basecomp.CompName);
            }
            else
            {
                basecompselector.SelectedIndex = 0;
            }

            basecompselector.SelectedIndexChanged += (sender, e) =>
            {
                if (rx.Components.ContainsKey(comps[basecompselector.SelectedIndex]))
                {
                    foreach (var rxc in rx.Components.Values)
                    {
                        rxc.IsBaseReactant = false;
                    }
                    rx.Components[comps[basecompselector.SelectedIndex]].IsBaseReactant = true;
                    rx.BaseReactant = comps[basecompselector.SelectedIndex];
                }
            };

            container.CreateAndAddLabelRow("Reaction Balance");

            txtEquation = container.CreateAndAddLabelRow2("");

            container.CreateAndAddLabelRow("Reaction Phase");

            var rxphaseselector = container.CreateAndAddDropDownRow("Reaction Phase", Shared.StringArrays.reactionphase().ToList(), 0, null);

            switch (rx.ReactionPhase)
            {
            case Interfaces.Enums.PhaseName.Vapor:
                rxphaseselector.SelectedIndex = (0);
                break;

            case Interfaces.Enums.PhaseName.Liquid:
                rxphaseselector.SelectedIndex = (1);
                break;

            case Interfaces.Enums.PhaseName.Mixture:
                rxphaseselector.SelectedIndex = (2);
                break;
            }

            rxphaseselector.SelectedIndexChanged += (sender, e) =>
            {
                switch (rxphaseselector.SelectedIndex)
                {
                case 0:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Vapor;
                    break;

                case 1:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Liquid;
                    break;

                case 2:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Mixture;
                    break;
                }
            };

            container.CreateAndAddLabelRow("Reaction Basis");

            var rxbasisselector = container.CreateAndAddDropDownRow("Reaction Basis", Shared.StringArrays.reactionbasis().ToList(), 0, null);

            switch (rx.ReactionBasis)
            {
            case Interfaces.Enums.ReactionBasis.Activity:
                rxphaseselector.SelectedIndex = (0);
                break;

            case Interfaces.Enums.ReactionBasis.Fugacity:
                rxphaseselector.SelectedIndex = (1);
                break;

            case Interfaces.Enums.ReactionBasis.MassConc:
                rxphaseselector.SelectedIndex = (2);
                break;

            case Interfaces.Enums.ReactionBasis.MassFrac:
                rxphaseselector.SelectedIndex = (3);
                break;

            case Interfaces.Enums.ReactionBasis.MolarConc:
                rxphaseselector.SelectedIndex = (4);
                break;

            case Interfaces.Enums.ReactionBasis.MolarFrac:
                rxphaseselector.SelectedIndex = (5);
                break;

            case Interfaces.Enums.ReactionBasis.PartialPress:
                rxphaseselector.SelectedIndex = (6);
                break;
            }

            rxbasisselector.SelectedIndexChanged += (sender, e) =>
            {
                switch (rxbasisselector.SelectedIndex)
                {
                case 0:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.Activity;
                    break;

                case 1:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.Fugacity;
                    break;

                case 2:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MassConc;
                    break;

                case 3:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MassFrac;
                    break;

                case 4:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MolarConc;
                    break;

                case 5:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MolarFrac;
                    break;

                case 6:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.PartialPress;
                    break;
                }
            };

            container.CreateAndAddLabelRow("Kinetic Parameters");

            container.CreateAndAddLabelRow2("Direct and Reverse Reactions Velocity Constants (k = A*exp(-E/RT), E in J/mol and T in K)");

            container.CreateAndAddStringEditorRow2("Direct Reaction A", "", rx.A_Forward.ToString(), (sender, e) => {
                if (Double.TryParse(sender.Text.ToString(), out val))
                {
                    sender.TextColor = SystemColors.ControlText;
                    rx.A_Forward     = double.Parse(sender.Text);
                }
                else
                {
                    sender.TextColor = Colors.Red;
                }
            });

            container.CreateAndAddStringEditorRow2("Direct Reaction E", "", rx.E_Forward.ToString(), (sender, e) =>
            {
                if (Double.TryParse(sender.Text.ToString(), out val))
                {
                    sender.TextColor = SystemColors.ControlText;
                    rx.E_Forward     = double.Parse(sender.Text);
                }
                else
                {
                    sender.TextColor = Colors.Red;
                }
            });

            container.CreateAndAddStringEditorRow2("Reverse Reaction A", "", rx.A_Reverse.ToString(), (sender, e) =>
            {
                if (Double.TryParse(sender.Text.ToString(), out val))
                {
                    sender.TextColor = SystemColors.ControlText;
                    rx.A_Reverse     = double.Parse(sender.Text);
                }
                else
                {
                    sender.TextColor = Colors.Red;
                }
            });

            container.CreateAndAddStringEditorRow2("Reverse Reaction E", "", rx.E_Reverse.ToString(), (sender, e) =>
            {
                if (Double.TryParse(sender.Text.ToString(), out val))
                {
                    sender.TextColor = SystemColors.ControlText;
                    rx.E_Reverse     = double.Parse(sender.Text);
                }
                else
                {
                    sender.TextColor = Colors.Red;
                }
            });

            container.CreateAndAddLabelRow("Units");

            var us    = new DWSIM.SharedClasses.SystemsOfUnits.Units();
            var units = us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.molar_conc);

            units.AddRange(us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.mass_conc));
            units.AddRange(us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.pressure));
            units.Insert(0, "");

            container.CreateAndAddDropDownRow("Basis Units (Base Compound)", units, units.IndexOf(rx.ConcUnit), (sender, e) => rx.ConcUnit = sender.SelectedValue.ToString());

            var units2 = us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.reac_rate);

            units2.Insert(0, "");

            container.CreateAndAddDropDownRow("Velocity Units", units2, units2.IndexOf(rx.VelUnit), (sender, e) => rx.VelUnit = sender.SelectedValue.ToString());

            UpdateEquation();
        }
Exemple #9
0
        void Initialize()
        {
            container.CreateAndAddLabelRow("Reaction ID");

            container.CreateAndAddStringEditorRow2("Name", "", rx.Name, (sender, e) => { rx.Name = sender.Text; });

            DynamicLayout p1, p2;

            StackLayout t1;

            p1 = UI.Shared.Common.GetDefaultContainer();
            p2 = UI.Shared.Common.GetDefaultContainer();

            p1.Width = 390;
            p2.Width = 440;

            t1             = new StackLayout(p1, p2);
            t1.Orientation = Orientation.Horizontal;

            container.SizeChanged += (sender, e) =>
            {
                if (p1.ParentWindow != null)
                {
                    p1.Width  = (int)(p1.ParentWindow.Width / 2 - 15);
                    p2.Width  = (int)(p2.ParentWindow.Width / 2 - 15);
                    p1.Height = p1.ParentWindow.Height - 170;
                    p2.Height = p1.ParentWindow.Height - 170;
                }
            };

            container.Add(t1);

            p1.CreateAndAddLabelRow("Compounds and Stoichiometry (Include / Name / Heat of Formation (kJ/kg) / Stoich. Coeff. / Direct Order Exponent / Reverse Order Exponent)");

            var compcontainer = new DynamicLayout();

            Double val;

            foreach (ICompoundConstantProperties comp in flowsheet.SelectedCompounds.Values)
            {
                var chk = new CheckBox()
                {
                    Text = comp.Name, Checked = (rx.Components.ContainsKey(comp.Name) ? true : false)
                };
                chk.CheckedChanged += (sender, e) =>
                {
                    if (!rx.Components.ContainsKey(comp.Name))
                    {
                        rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, 0, false, 0, 0));
                    }
                    else
                    {
                        rx.Components.Remove(comp.Name);
                    }
                    UpdateEquation();
                };

                var sc = new TextBox()
                {
                    Width = (int)(sf * 30), Text = (rx.Components.ContainsKey(comp.Name) ? rx.Components[comp.Name].StoichCoeff.ToString() : 0.0f.ToString())
                };

                sc.TextChanged += (sender, e) =>
                {
                    if (Double.TryParse(sc.Text.ToString(), out val))
                    {
                        sc.TextColor = SystemColors.ControlText;
                        if (!rx.Components.ContainsKey(comp.Name))
                        {
                            rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, Double.Parse(sc.Text), false, 0, 0));
                        }
                        else
                        {
                            rx.Components[comp.Name].StoichCoeff = double.Parse(sc.Text);
                        }
                        UpdateEquation();
                    }
                    else
                    {
                        sc.TextColor = Colors.Red;
                    }
                };

                var txtdo = new TextBox()
                {
                    Width = (int)(sf * 30), Text = (rx.Components.ContainsKey(comp.Name) ? rx.Components[comp.Name].DirectOrder.ToString() : 0.0f.ToString())
                };

                txtdo.TextChanged += (sender, e) =>
                {
                    if (Double.TryParse(txtdo.Text.ToString(), out val))
                    {
                        txtdo.TextColor = SystemColors.ControlText;
                        if (!rx.Components.ContainsKey(comp.Name))
                        {
                            rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, 0, false, Double.Parse(txtdo.Text), 0));
                        }
                        else
                        {
                            rx.Components[comp.Name].DirectOrder = double.Parse(txtdo.Text);
                        }
                        UpdateEquation();
                    }
                    else
                    {
                        txtdo.TextColor = Colors.Red;
                    }
                };

                var txtro = new TextBox()
                {
                    Width = (int)(sf * 30), Text = (rx.Components.ContainsKey(comp.Name) ? rx.Components[comp.Name].ReverseOrder.ToString() : 0.0f.ToString())
                };

                txtro.TextChanged += (sender, e) =>
                {
                    if (Double.TryParse(txtro.Text.ToString(), out val))
                    {
                        txtro.TextColor = SystemColors.ControlText;
                        if (!rx.Components.ContainsKey(comp.Name))
                        {
                            rx.Components.Add(comp.Name, new DWSIM.Thermodynamics.BaseClasses.ReactionStoichBase(comp.Name, 0, false, 0, Double.Parse(txtro.Text)));
                        }
                        else
                        {
                            rx.Components[comp.Name].ReverseOrder = double.Parse(txtro.Text);
                        }
                        UpdateEquation();
                    }
                    else
                    {
                        txtro.TextColor = Colors.Red;
                    }
                };

                var hf = new TextBox()
                {
                    Enabled = false, Width = (int)(sf * 100), Text = comp.IG_Enthalpy_of_Formation_25C.ToString("N2")
                };

                compcontainer.Add(new TableRow(chk, null, hf, sc, txtdo, txtro));
            }

            p1.CreateAndAddControlRow(compcontainer);
            p1.CreateAndAddEmptySpace();

            var comps = flowsheet.SelectedCompounds.Values.Select((x) => x.Name).ToList();

            comps.Insert(0, "");

            p1.CreateAndAddLabelRow("Base Compound");

            var basecompselector = p1.CreateAndAddDropDownRow("Base Compound", comps, 0, null);

            var basecomp = rx.Components.Values.Where((x) => x.IsBaseReactant).FirstOrDefault();

            if (basecomp != null)
            {
                basecompselector.SelectedIndex = comps.IndexOf(basecomp.CompName);
            }
            else
            {
                basecompselector.SelectedIndex = 0;
            }

            basecompselector.SelectedIndexChanged += (sender, e) =>
            {
                if (rx.Components.ContainsKey(comps[basecompselector.SelectedIndex]))
                {
                    foreach (var rxc in rx.Components.Values)
                    {
                        rxc.IsBaseReactant = false;
                    }
                    rx.Components[comps[basecompselector.SelectedIndex]].IsBaseReactant = true;
                    rx.BaseReactant = comps[basecompselector.SelectedIndex];
                }
            };

            p1.CreateAndAddLabelRow("Reaction Balance");

            txtEquation = p1.CreateAndAddLabelRow2("");

            p1.CreateAndAddLabelRow("Reaction Phase");

            var rxphaseselector = p1.CreateAndAddDropDownRow("Reaction Phase", Shared.StringArrays.reactionphase().ToList(), 0, null);

            switch (rx.ReactionPhase)
            {
            case Interfaces.Enums.PhaseName.Mixture:
                rxphaseselector.SelectedIndex = (0);
                break;

            case Interfaces.Enums.PhaseName.Vapor:
                rxphaseselector.SelectedIndex = (1);
                break;

            case Interfaces.Enums.PhaseName.Liquid:
                rxphaseselector.SelectedIndex = (2);
                break;
            }

            rxphaseselector.SelectedIndexChanged += (sender, e) =>
            {
                switch (rxphaseselector.SelectedIndex)
                {
                case 0:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Mixture;
                    break;

                case 1:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Vapor;
                    break;

                case 2:
                    rx.ReactionPhase = Interfaces.Enums.PhaseName.Liquid;
                    break;
                }
            };

            p1.CreateAndAddLabelRow("Reaction Basis");

            var rxbasisselector = p1.CreateAndAddDropDownRow("Reaction Basis", Shared.StringArrays.reactionbasis().ToList(), 0, null);

            switch (rx.ReactionBasis)
            {
            case Interfaces.Enums.ReactionBasis.Activity:
                rxbasisselector.SelectedIndex = (0);
                break;

            case Interfaces.Enums.ReactionBasis.Fugacity:
                rxbasisselector.SelectedIndex = (1);
                break;

            case Interfaces.Enums.ReactionBasis.MassConc:
                rxbasisselector.SelectedIndex = (2);
                break;

            case Interfaces.Enums.ReactionBasis.MassFrac:
                rxbasisselector.SelectedIndex = (3);
                break;

            case Interfaces.Enums.ReactionBasis.MolarConc:
                rxbasisselector.SelectedIndex = (4);
                break;

            case Interfaces.Enums.ReactionBasis.MolarFrac:
                rxbasisselector.SelectedIndex = (5);
                break;

            case Interfaces.Enums.ReactionBasis.PartialPress:
                rxbasisselector.SelectedIndex = (6);
                break;
            }

            rxbasisselector.SelectedIndexChanged += (sender, e) =>
            {
                switch (rxbasisselector.SelectedIndex)
                {
                case 0:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.Activity;
                    break;

                case 1:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.Fugacity;
                    break;

                case 2:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MassConc;
                    break;

                case 3:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MassFrac;
                    break;

                case 4:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MolarConc;
                    break;

                case 5:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.MolarFrac;
                    break;

                case 6:
                    rx.ReactionBasis = Interfaces.Enums.ReactionBasis.PartialPress;
                    break;
                }
            };

            p2.CreateAndAddLabelRow("Kinetic Parameters");

            var nf = flowsheet.FlowsheetOptions.NumberFormat;
            var su = flowsheet.FlowsheetOptions.SelectedUnitSystem;

            p2.CreateAndAddTextBoxRow(nf, "Minimum Temperature (" + su.temperature + ")", rx.Tmin.ConvertFromSI(su.temperature), (sender, e) => { if (sender.Text.IsValidDouble())
                                                                                                                                                  {
                                                                                                                                                      rx.Tmin = sender.Text.ToDoubleFromCurrent().ConvertToSI(su.temperature);
                                                                                                                                                  }
                                      });
            p2.CreateAndAddTextBoxRow(nf, "Maximum Temperature (" + su.temperature + ")", rx.Tmax.ConvertFromSI(su.temperature), (sender, e) => { if (sender.Text.IsValidDouble())
                                                                                                                                                  {
                                                                                                                                                      rx.Tmax = sender.Text.ToDoubleFromCurrent().ConvertToSI(su.temperature);
                                                                                                                                                  }
                                      });

            p2.CreateAndAddLabelRow("Velocity Constant for Forward Reactions");

            p2.CreateAndAddDropDownRow("Equation Type for Forward Reactions", new List <string>()
            {
                "Arrhenius (k = A*exp(-E/RT))", "User-Defined Expression"
            }, (int)rx.ReactionKinFwdType, (sender, e) =>
            {
                switch (sender.SelectedIndex)
                {
                case 0:
                    rx.ReactionKinFwdType = Interfaces.Enums.ReactionKineticType.Arrhenius;
                    break;

                case 1:
                    rx.ReactionKinFwdType = Interfaces.Enums.ReactionKineticType.UserDefined;
                    break;
                }
            });

            p2.CreateAndAddStringEditorRow2("A", "", rx.A_Forward.ToString(), (sender, e) =>
            {
                if (Double.TryParse(sender.Text.ToString(), out val))
                {
                    sender.TextColor = SystemColors.ControlText;
                    rx.A_Forward     = double.Parse(sender.Text);
                }
                else
                {
                    sender.TextColor = Colors.Red;
                }
            });

            p2.CreateAndAddStringEditorRow2("E (J/mol)", "", rx.E_Forward.ToString(), (sender, e) =>
            {
                if (Double.TryParse(sender.Text.ToString(), out val))
                {
                    sender.TextColor = SystemColors.ControlText;
                    rx.E_Forward     = double.Parse(sender.Text);
                }
                else
                {
                    sender.TextColor = Colors.Red;
                }
            });

            p2.CreateAndAddStringEditorRow2("User Expression - f(T)", "", rx.ReactionKinFwdExpression, (sender, e) =>
            {
                rx.ReactionKinFwdExpression = sender.Text;
            });

            p2.CreateAndAddLabelRow("Velocity Constant for Reverse Reactions");

            p2.CreateAndAddDropDownRow("Equation Type for Reverse Reactions", new List <string>()
            {
                "Arrhenius (k = A*exp(-E/RT))", "User-Defined Expression"
            }, (int)rx.ReactionKinRevType, (sender, e) =>
            {
                switch (sender.SelectedIndex)
                {
                case 0:
                    rx.ReactionKinRevType = Interfaces.Enums.ReactionKineticType.Arrhenius;
                    break;

                case 1:
                    rx.ReactionKinRevType = Interfaces.Enums.ReactionKineticType.UserDefined;
                    break;
                }
            });

            p2.CreateAndAddStringEditorRow2("A", "", rx.A_Reverse.ToString(), (sender, e) =>
            {
                if (Double.TryParse(sender.Text.ToString(), out val))
                {
                    sender.TextColor = SystemColors.ControlText;
                    rx.A_Reverse     = double.Parse(sender.Text);
                }
                else
                {
                    sender.TextColor = Colors.Red;
                }
            });

            p2.CreateAndAddStringEditorRow2("E (J/mol)", "", rx.E_Reverse.ToString(), (sender, e) =>
            {
                if (Double.TryParse(sender.Text.ToString(), out val))
                {
                    sender.TextColor = SystemColors.ControlText;
                    rx.E_Reverse     = double.Parse(sender.Text);
                }
                else
                {
                    sender.TextColor = Colors.Red;
                }
            });

            p2.CreateAndAddStringEditorRow2("User Expression - f(T)", "", rx.ReactionKinRevExpression, (sender, e) =>
            {
                rx.ReactionKinRevExpression = sender.Text;
            });

            p2.CreateAndAddLabelRow("Units");

            var us    = new DWSIM.SharedClasses.SystemsOfUnits.Units();
            var units = us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.molar_conc);

            units.AddRange(us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.mass_conc));
            units.AddRange(us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.pressure));
            units.Insert(0, "");

            p2.CreateAndAddDropDownRow("Basis Units (Base Compound)", units, units.IndexOf(rx.ConcUnit), (sender, e) => rx.ConcUnit = sender.SelectedValue.ToString());

            var units2 = us.GetUnitSet(Interfaces.Enums.UnitOfMeasure.reac_rate);

            units2.Insert(0, "");

            p2.CreateAndAddDropDownRow("Velocity Units", units2, units2.IndexOf(rx.VelUnit), (sender, e) => rx.VelUnit = sender.SelectedValue.ToString());

            UpdateEquation();
        }
        public ProjectWizardPageView(ProjectWizardPageModel model)
        {
            var radioSpacing = Platform.IsGtk ? Size.Empty : new Size(2, 2);

            var content = new DynamicLayout
            {
                Spacing = new Size(10, 10)
            };

            if (model.SupportsAppName)
            {
                var nameBox = new TextBox();
                nameBox.TextBinding.BindDataContext((ProjectWizardPageModel m) => m.AppName);
                Application.Instance.AsyncInvoke(nameBox.Focus);

                var nameValid = new Label {
                    TextColor = Global.Theme.ErrorForeground
                };
                nameValid.BindDataContext(c => c.Visible, (ProjectWizardPageModel m) => m.AppNameInvalid);
                nameValid.BindDataContext(c => c.Text, (ProjectWizardPageModel m) => m.AppNameValidationText);


                content.BeginHorizontal();
                content.Add(HeadingLabel((model.IsLibrary ? "Library" : "App") + " Name:"));
                content.AddColumn(nameBox, nameValid);
                content.EndHorizontal();
            }
            else if (!string.IsNullOrEmpty(model.AppName))
            {
                var label = new Label {
                    Text = model.AppName, VerticalAlignment = VerticalAlignment.Center
                };
                content.AddRow(HeadingLabel((model.IsLibrary ? "Library" : "App") + " Name:"), label);
            }

            if (model.SupportsFramework)
            {
                var frameworkDropDown = new DropDown();
                frameworkDropDown.BindDataContext(c => c.DataStore, (ProjectWizardPageModel m) => m.SupportedFrameworks);
                frameworkDropDown.ItemTextBinding = Binding.Property((ProjectWizardPageModel.FrameworkInfo i) => i.Text);
                frameworkDropDown.ItemKeyBinding  = Binding.Property((ProjectWizardPageModel.FrameworkInfo i) => i.Value);
                frameworkDropDown.SelectedValueBinding.BindDataContext((ProjectWizardPageModel m) => m.SelectedFramework);

                /*
                 * var frameworkCheckBoxes = new CheckBoxList();
                 * frameworkCheckBoxes.BindDataContext(c => c.DataStore, (ProjectWizardPageModel m) => m.SupportedFrameworks);
                 * frameworkCheckBoxes.ItemTextBinding = Binding.Property((ProjectWizardPageModel.FrameworkInfo i) => i.Text);
                 * frameworkCheckBoxes.ItemKeyBinding = Binding.Property((ProjectWizardPageModel.FrameworkInfo i) => i.Value);
                 * frameworkCheckBoxes.SelectedValuesBinding.BindDataContext((ProjectWizardPageModel m) => m.SelectedFrameworks);
                 */

                content.AddRow(HeadingLabel("Framework:"), frameworkDropDown);
            }

            if (model.SupportsCombined)
            {
                var platformTypeList = new RadioButtonList
                {
                    Orientation = Orientation.Vertical,
                    Spacing     = radioSpacing,
                    Items       =
                    {
                        new ListItem {
                            Text = "Separate projects for each platform", Key = "separate"
                        },
                        new ListItem {
                            Text = "Single Windows, Linux, and Mac desktop project", Key = "combined"
                        }
                    }
                };
                platformTypeList.BindDataContext(c => c.Visible, (ProjectWizardPageModel m) => m.AllowCombined);
                platformTypeList.SelectedKeyBinding
                .Convert(v => v == "combined", v => v ? "combined" : "separate")
                .BindDataContext((ProjectWizardPageModel m) => m.Combined);
                var heading = HeadingLabel("Launcher:");
                heading.BindDataContext(c => c.Visible, (ProjectWizardPageModel m) => m.AllowCombined);
                content.AddRow(heading, platformTypeList);
            }

            if (model.SupportsXamMac)
            {
                var cb = new CheckBox
                {
                    Text    = "Include Xamarin.Mac project",
                    ToolTip = "This enables you to bundle mono with your app so your users don't have to install it separately.  You can only compile this on a Mac"
                };
                cb.CheckedBinding.BindDataContext((ProjectWizardPageModel m) => m.IncludeXamMac);
                content.AddRow(HeadingLabel(string.Empty), cb);
            }

            /*
             * eventually select platforms to include?
             *
             * var platformCheckBoxes = new DynamicLayout();
             * platformCheckBoxes.BeginHorizontal();
             * platformCheckBoxes.Add(new CheckBox { Text = "Gtk2" });
             * platformCheckBoxes.Add(new CheckBox { Text = "Gtk3" });
             * platformCheckBoxes.EndBeginHorizontal();
             * platformCheckBoxes.Add(new CheckBox { Text = "WinForms" });
             * platformCheckBoxes.Add(new CheckBox { Text = "Wpf" });
             * platformCheckBoxes.Add(new CheckBox { Text = "Direct2D" });
             * platformCheckBoxes.EndBeginHorizontal();
             * platformCheckBoxes.Add(new CheckBox { Text = "Mac" });
             * platformCheckBoxes.Add(new CheckBox { Text = "XamMac" });
             * platformCheckBoxes.Add(new CheckBox { Text = "XamMac2" });
             * platformCheckBoxes.EndHorizontal();
             *
             * content.Rows.Add(new TableRow(new Label { Text = "Platforms:", TextAlignment = TextAlignment.Right }, platformCheckBoxes));
             * /**/

            if (model.SupportsProjectType)
            {
                var sharedCodeList = new RadioButtonList
                {
                    Orientation = Orientation.Vertical,
                    Spacing     = radioSpacing,
                };
                if (model.SupportsPCL)
                {
                    sharedCodeList.Items.Add(new ListItem {
                        Text = "Portable Class Library", Key = "pcl"
                    });
                    sharedCodeList.SelectedKeyBinding.Convert(v => v == "pcl", v => v ? "pcl" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UsePCL);
                }
                if (model.SupportsNetStandard)
                {
                    sharedCodeList.Items.Add(new ListItem {
                        Text = ".NET Standard", Key = "netstandard"
                    });
                    sharedCodeList.SelectedKeyBinding.Convert(v => v == "netstandard", v => v ? "netstandard" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseNetStandard);
                }
                if (model.SupportsSAL)
                {
                    sharedCodeList.Items.Add(new ListItem {
                        Text = "Shared Project", Key = "sal"
                    });
                    sharedCodeList.SelectedKeyBinding.Convert(v => v == "sal", v => v ? "sal" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseSAL);
                }

                sharedCodeList.Items.Add(new ListItem {
                    Text = "Full .NET", Key = "net"
                });
                sharedCodeList.SelectedKeyBinding.Convert(v => v == "net", v => v ? "net" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseNET);

                content.AddRow(new Label {
                    Text = model.IsLibrary ? "Type:" : "Shared Code:", TextAlignment = TextAlignment.Right
                }, sharedCodeList);
            }

            if (model.SupportsPanelType)
            {
                var panelTypeList = new RadioButtonList
                {
                    Orientation = Orientation.Horizontal,
                    Spacing     = radioSpacing,
                };

                panelTypeList.Items.Add(new ListItem {
                    Text = "Code", Key = "code"
                });
                panelTypeList.SelectedKeyBinding.BindDataContext((ProjectWizardPageModel m) => m.Mode);

                if (model.SupportsXeto)
                {
                    panelTypeList.Items.Add(new ListItem {
                        Text = "Xaml", Key = "xaml"
                    });
                }
                if (model.SupportsJeto)
                {
                    panelTypeList.Items.Add(new ListItem {
                        Text = "Json", Key = "json"
                    });
                }
                if (model.SupportsCodePreview)
                {
                    panelTypeList.Items.Add(new ListItem {
                        Text = "Code Preview", Key = "preview"
                    });
                }

                content.AddRow(HeadingLabel("Form:"), panelTypeList);
            }

            if (model.SupportsBase)
            {
                var baseTypeList = new RadioButtonList
                {
                    Orientation = Orientation.Horizontal,
                    Spacing     = radioSpacing,
                };

                baseTypeList.Items.Add(new ListItem {
                    Text = "Panel", Key = "Panel"
                });
                baseTypeList.Items.Add(new ListItem {
                    Text = "Dialog", Key = "Dialog"
                });
                baseTypeList.Items.Add(new ListItem {
                    Text = "Form", Key = "Form"
                });
                baseTypeList.SelectedKeyBinding.BindDataContext((ProjectWizardPageModel m) => m.Base);

                content.AddRow(HeadingLabel("Base:"), baseTypeList);
            }

#if DEBUG
            //var showColorsButton = new Button { Text = "Show all themed colors" };
            //showColorsButton.Click += (sender, e) => new ThemedColorsDialog().ShowModal(this);
            //content.AddRow(new Panel(), showColorsButton);
#endif

            var informationLabel = new Label();
            informationLabel.TextBinding.BindDataContext((ProjectWizardPageModel m) => m.Information);
            Information = informationLabel;

            Content     = content;
            DataContext = model;
        }
Exemple #11
0
        } = null;                                                // TODO: Add support

        public MakerForm()
        {
            Title      = "Scratch HTML log maker";
            ClientSize = new Size(800, 600);
            var formLayout = new DynamicLayout();

            Content = formLayout;

            var openFileDialog = new OpenFileDialog {
                MultiSelect = true
            };

            openFileDialog.Filters.Add(new FileFilter("EVTC logs", ".evtc", ".evtc.zip", ".zevtc"));

            var openFilesButton = new Button {
                Text = "Select EVTC logs"
            };
            var processButton = new Button {
                Text = "Create HTML logs"
            };

            var notDoneListBox = new ListBox();
            var doneListBox    = new ListBox();

            doneListBox.DataStore = finishedFileNames.ToArray();

            var splitter = new Splitter {
                Panel1 = notDoneListBox, Panel2 = doneListBox, Position = 400
            };

            formLayout.BeginVertical(spacing: new Size(10, 10));
            formLayout.AddRow(openFilesButton, processButton);
            formLayout.EndVertical();
            formLayout.BeginVertical();
            formLayout.Add(splitter);
            formLayout.EndVertical();

            openFilesButton.Click += (sender, args) =>
            {
                if (openFileDialog.ShowDialog((Control)sender) == DialogResult.Ok)
                {
                    foreach (var file in openFileDialog.Filenames)
                    {
                        notFinishedFileNames.Enqueue(file);
                    }

                    notDoneListBox.DataStore = notFinishedFileNames.Select(Path.GetFileName).ToArray();
                }
            };

            processButton.Click += (sender, args) =>
            {
                Task.Run(() =>
                {
                    var times = new List <(string taskName, double milliseconds)>();
                    var totalTimeStopwatch = Stopwatch.StartNew();

                    var parser    = new EVTCParser();
                    var processor = new LogProcessor();
                    var generator = new HtmlGenerator(ApiData);

                    int finishedTaskCount = 0;
                    while (notFinishedFileNames.Count > 0)
                    {
                        var taskStopwatch = Stopwatch.StartNew();
                        string filename   = "";
                        filename          = notFinishedFileNames.Dequeue();

                        var fileDirectory = Path.GetDirectoryName(filename);
                        var newName       = Path.GetFileNameWithoutExtension(filename);
                        if (newName.EndsWith(".evtc"))
                        {
                            newName = newName.Substring(0, newName.Length - 5);
                        }
                        var resultFilename = Path.Combine(fileDirectory, ResultFilePrefix + newName + ".html");

                        try
                        {
                            var lastElapsed = taskStopwatch.Elapsed;

                            var parsedLog = parser.ParseLog(filename);
                            times.Add(("parsing", (taskStopwatch.Elapsed - lastElapsed).TotalMilliseconds));
                            lastElapsed = taskStopwatch.Elapsed;

                            var processedLog = processor.ProcessLog(parsedLog);
                            times.Add(("processing", (taskStopwatch.Elapsed - lastElapsed).TotalMilliseconds));
                            lastElapsed = taskStopwatch.Elapsed;

                            var analysis = new LogAnalyzer(processedLog, ApiData);
                            var stats    = analysis.GetStatistics();

                            times.Add(("stats", (taskStopwatch.Elapsed - lastElapsed).TotalMilliseconds));
                            lastElapsed = taskStopwatch.Elapsed;

                            using (var htmlStringWriter = new StreamWriter(resultFilename))
                            {
                                generator.WriteHtml(htmlStringWriter, stats);
                            }

                            times.Add(("html", (taskStopwatch.Elapsed - lastElapsed).TotalMilliseconds));
                            lastElapsed = taskStopwatch.Elapsed;

                            finishedFileNames.Add(resultFilename);
                            Application.Instance.Invoke(() =>
                            {
                                notDoneListBox.DataStore = notFinishedFileNames.Select(Path.GetFileName).ToArray();
                                doneListBox.DataStore    = finishedFileNames.Select(Path.GetFileName).ToArray();
                            });
                        }
                        catch (Exception e)
                        {
                            finishedFileNames.Add($"FAILED: {resultFilename} ({e.Message})");
                            Application.Instance.Invoke(() =>
                            {
                                notDoneListBox.DataStore = notFinishedFileNames.Select(Path.GetFileName).ToArray();
                                doneListBox.DataStore    = finishedFileNames.Select(Path.GetFileName).ToArray();
                            });
                        }
                        Console.WriteLine($"{newName} done, time {taskStopwatch.Elapsed}");
                        finishedTaskCount++;
                    }

                    Console.WriteLine($"All done, total time {totalTimeStopwatch.Elapsed}");

                    foreach ((string taskName, double totalMs) in times.GroupBy(x => x.taskName).Select(x => (x.Key, x.Sum(y => y.milliseconds))).OrderByDescending(x => x.Item2))
                    {
                        Console.WriteLine($"{taskName}, total {totalMs}ms, average {totalMs/Math.Max(finishedTaskCount, 1)}ms");
                    }
                });
            };
        }
Exemple #12
0
        void InitializeComponent()
        {
            //exception handling

            var sf = s.UIScalingFactor;

            Application.Instance.UnhandledException += (sender, e) =>
            {
                new DWSIM.UI.Desktop.Editors.UnhandledExceptionView((Exception)e.ExceptionObject).ShowModalAsync();
            };

            string imgprefix = "DWSIM.UI.Forms.Resources.Icons.";

            Title = "DWSIMLauncher".Localize();

            switch (GlobalSettings.Settings.RunningPlatform())
            {
            case GlobalSettings.Settings.Platform.Windows:
                ClientSize = new Size((int)(690 * sf), (int)(420 * sf));
                break;

            case GlobalSettings.Settings.Platform.Linux:
                ClientSize = new Size((int)(690 * sf), (int)(370 * sf));
                break;

            case GlobalSettings.Settings.Platform.Mac:
                ClientSize = new Size((int)(690 * sf), (int)(350 * sf));
                break;
            }

            Icon = Eto.Drawing.Icon.FromResource(imgprefix + "DWSIM_ico.ico");

            var bgcolor = new Color(0.051f, 0.447f, 0.651f);

            if (s.DarkMode)
            {
                bgcolor = SystemColors.ControlBackground;
            }

            Eto.Style.Add <Button>("main", button =>
            {
                button.BackgroundColor = bgcolor;
                button.Font            = new Font(FontFamilies.Sans, 12f, FontStyle.None);
                button.TextColor       = Colors.White;
                button.ImagePosition   = ButtonImagePosition.Left;
                button.Width           = (int)(sf * 250);
            });

            Eto.Style.Add <Button>("donate", button =>
            {
                button.BackgroundColor = !s.DarkMode ? Colors.LightYellow : SystemColors.ControlBackground;
                button.Font            = new Font(FontFamilies.Sans, 12f, FontStyle.None);
                button.TextColor       = !s.DarkMode ? bgcolor : Colors.White;
                button.ImagePosition   = ButtonImagePosition.Left;
                button.Width           = (int)(sf * 250);
            });

            var btn1 = new Button()
            {
                Style = "main", Text = "OpenSavedFile".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "OpenFolder_100px.png"), (int)(sf * 40), (int)(sf * 40), ImageInterpolation.Default)
            };
            var btn2 = new Button()
            {
                Style = "main", Text = "NewSimulation".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "Workflow_100px.png"), (int)(sf * 40), (int)(sf * 40), ImageInterpolation.Default)
            };
            var btn3 = new Button()
            {
                Style = "main", Text = "NewCompound".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "Peptide_100px.png"), (int)(sf * 40), (int)(sf * 40), ImageInterpolation.Default)
            };
            var btn4 = new Button()
            {
                Style = "main", Text = "NewDataRegression".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "AreaChart_100px.png"), (int)(sf * 40), (int)(sf * 40), ImageInterpolation.Default)
            };
            var btn6 = new Button()
            {
                Style = "main", Text = "Help".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "Help_100px.png"), (int)(sf * 40), (int)(sf * 40), ImageInterpolation.Default)
            };
            var btn7 = new Button()
            {
                Style = "main", Text = "About".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "Info_100px.png"), (int)(sf * 40), (int)(sf * 40), ImageInterpolation.Default)
            };
            var btn8 = new Button()
            {
                Style = "donate", Text = "Become a Patron", Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "icons8-patreon.png"), (int)(sf * 40), (int)(sf * 40), ImageInterpolation.Default)
            };
            var btn9 = new Button()
            {
                Style = "main", Text = "Preferences".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "VerticalSettingsMixer_100px.png"), (int)(sf * 40), (int)(sf * 40), ImageInterpolation.Default)
            };

            btn9.Click += (sender, e) =>
            {
                new Forms.Forms.GeneralSettings().GetForm().Show();
            };

            btn6.Click += (sender, e) =>
            {
                Process.Start("http://dwsim.inforside.com.br/docs/crossplatform/help/");
            };

            btn1.Click += (sender, e) =>
            {
                var dialog = new OpenFileDialog();
                dialog.Title = "Open File".Localize();
                dialog.Filters.Add(new FileFilter("XML Simulation File".Localize(), new[] { ".dwxml", ".dwxmz" }));
                dialog.Filters.Add(new FileFilter("Mobile XML Simulation File (Android/iOS)", new[] { ".xml" }));
                dialog.MultiSelect        = false;
                dialog.CurrentFilterIndex = 0;
                if (dialog.ShowDialog(this) == DialogResult.Ok)
                {
                    LoadSimulation(dialog.FileName);
                }
            };

            btn2.Click += (sender, e) =>
            {
                var form = new Forms.Flowsheet();
                AddUserCompounds(form.FlowsheetObject);
                OpenForms   += 1;
                form.Closed += (sender2, e2) =>
                {
                    OpenForms -= 1;
                };
                form.newsim = true;
                form.Show();
            };

            btn7.Click += (sender, e) => new AboutBox().Show();
            btn8.Click += (sender, e) => Process.Start("https://patreon.com/dwsim");

            var stack = new StackLayout {
                Orientation = Orientation.Vertical, Spacing = 5
            };

            stack.Items.Add(btn1);
            stack.Items.Add(btn2);
            stack.Items.Add(btn9);
            stack.Items.Add(btn6);
            stack.Items.Add(btn7);
            stack.Items.Add(btn8);

            var tableright = new TableLayout();

            tableright.Padding = new Padding(5, 5, 5, 5);
            tableright.Spacing = new Size(10, 10);

            MostRecentList = new ListBox {
                BackgroundColor = bgcolor, Height = (int)(sf * 330)
            };
            SampleList = new ListBox {
                BackgroundColor = bgcolor, Height = (int)(sf * 330)
            };
            FoldersList = new ListBox {
                BackgroundColor = bgcolor, Height = (int)(sf * 330)
            };
            FOSSEEList = new ListBox {
                BackgroundColor = bgcolor, Height = (int)(sf * 330)
            };

            if (Application.Instance.Platform.IsGtk &&
                GlobalSettings.Settings.RunningPlatform() == GlobalSettings.Settings.Platform.Mac)
            {
                MostRecentList.TextColor = bgcolor;
                SampleList.TextColor     = bgcolor;
                FoldersList.TextColor    = bgcolor;
                FOSSEEList.TextColor     = bgcolor;
            }
            else if (GlobalSettings.Settings.RunningPlatform() == GlobalSettings.Settings.Platform.Mac)
            {
                MostRecentList.BackgroundColor = SystemColors.ControlBackground;
                SampleList.BackgroundColor     = SystemColors.ControlBackground;
                FoldersList.BackgroundColor    = SystemColors.ControlBackground;
                FOSSEEList.BackgroundColor     = SystemColors.ControlBackground;
                MostRecentList.TextColor       = SystemColors.ControlText;
                SampleList.TextColor           = SystemColors.ControlText;
                FoldersList.TextColor          = SystemColors.ControlText;
                FOSSEEList.TextColor           = SystemColors.ControlText;
            }
            else
            {
                MostRecentList.TextColor = Colors.White;
                SampleList.TextColor     = Colors.White;
                FoldersList.TextColor    = Colors.White;
                FOSSEEList.TextColor     = Colors.White;
            }

            var invertedlist = new List <string>(GlobalSettings.Settings.MostRecentFiles);

            invertedlist.Reverse();

            foreach (var item in invertedlist)
            {
                if (File.Exists(item))
                {
                    MostRecentList.Items.Add(new ListItem {
                        Text = Path.GetFileName(item), Key = item
                    });
                }
            }

            var samplist = Directory.EnumerateFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "samples"), "*.dwxm*");

            foreach (var item in samplist)
            {
                if (File.Exists(item))
                {
                    SampleList.Items.Add(new ListItem {
                        Text = Path.GetFileName(item), Key = item
                    });
                }
            }

            foreach (String f in invertedlist)
            {
                if (Path.GetExtension(f).ToLower() != ".dwbcs")
                {
                    if (FoldersList.Items.Where((x) => x.Text == Path.GetDirectoryName(f)).Count() == 0)
                    {
                        if (Directory.Exists(Path.GetDirectoryName(f)))
                        {
                            FoldersList.Items.Add(new ListItem {
                                Text = Path.GetDirectoryName(f), Key = Path.GetDirectoryName(f)
                            });
                        }
                    }
                }
            }

            FOSSEEList.Items.Add(new ListItem {
                Text = "Downloading flowsheet list, please wait...", Key = ""
            });

            Dictionary <string, SharedClasses.FOSSEEFlowsheet> fslist = new Dictionary <string, SharedClasses.FOSSEEFlowsheet>();

            Task.Factory.StartNew(() =>
            {
                return(SharedClasses.FOSSEEFlowsheets.GetFOSSEEFlowsheets());
            }).ContinueWith((t) =>
            {
                Application.Instance.Invoke(() =>
                {
                    FOSSEEList.Items.Clear();
                    if (t.Exception != null)
                    {
                        FOSSEEList.Items.Add(new ListItem {
                            Text = "Error loading flowsheet list. Check your internet connection.", Key = ""
                        });
                    }
                    else
                    {
                        foreach (var item in t.Result)
                        {
                            fslist.Add(item.DownloadLink, item);
                            FOSSEEList.Items.Add(new ListItem {
                                Text = item.DisplayName, Key = item.DownloadLink
                            });
                        }
                    }
                });
            });

            FoldersList.SelectedIndexChanged += (sender, e) =>
            {
                if (FoldersList.SelectedIndex >= 0)
                {
                    var dialog = new OpenFileDialog();
                    dialog.Title     = "Open File".Localize();
                    dialog.Directory = new Uri(FoldersList.SelectedKey);
                    dialog.Filters.Add(new FileFilter("XML Simulation File".Localize(), new[] { ".dwxml", ".dwxmz" }));
                    dialog.MultiSelect        = false;
                    dialog.CurrentFilterIndex = 0;
                    if (dialog.ShowDialog(this) == DialogResult.Ok)
                    {
                        LoadSimulation(dialog.FileName);
                    }
                }
            };

            MostRecentList.SelectedIndexChanged += (sender, e) =>
            {
                if (MostRecentList.SelectedIndex >= 0)
                {
                    LoadSimulation(MostRecentList.SelectedKey);
                    MostRecentList.SelectedIndex = -1;
                }
                ;
            };

            SampleList.SelectedIndexChanged += (sender, e) =>
            {
                if (SampleList.SelectedIndex >= 0)
                {
                    LoadSimulation(SampleList.SelectedKey);
                    MostRecentList.SelectedIndex = -1;
                }
                ;
            };

            FOSSEEList.SelectedIndexChanged += (sender, e) =>
            {
                if (FOSSEEList.SelectedIndex >= 0 && FOSSEEList.SelectedKey != "")
                {
                    var item = fslist[FOSSEEList.SelectedKey];
                    var sb   = new StringBuilder();
                    sb.AppendLine("Title: " + item.Title);
                    sb.AppendLine("Author: " + item.ProposerName);
                    sb.AppendLine("Institution: " + item.Institution);
                    sb.AppendLine();
                    sb.AppendLine("Click 'Yes' to download and open this flowsheet.");

                    if (MessageBox.Show(sb.ToString(), "Open FOSSEE Flowsheet", MessageBoxButtons.YesNo, MessageBoxType.Information, MessageBoxDefaultButton.Yes) == DialogResult.Yes)
                    {
                        var loadingdialog = new LoadingData();
                        loadingdialog.loadingtext.Text = "Please wait, downloading file...\n(" + FOSSEEList.SelectedKey + ")";
                        loadingdialog.Show();
                        var address = FOSSEEList.SelectedKey;
                        Task.Factory.StartNew(() =>
                        {
                            return(SharedClasses.FOSSEEFlowsheets.DownloadFlowsheet(address, (p) => {
                                Application.Instance.Invoke(() => loadingdialog.loadingtext.Text = "Please wait, downloading file... (" + p + "%)\n(" + address + ")");
                            }));
                        }).ContinueWith((t) =>
                        {
                            Application.Instance.Invoke(() => loadingdialog.Close());
                            if (t.Exception != null)
                            {
                                MessageBox.Show(t.Exception.Message, "Error downloading file", MessageBoxButtons.OK, MessageBoxType.Error, MessageBoxDefaultButton.OK);
                            }
                            else
                            {
                                Application.Instance.Invoke(() => LoadSimulation(SharedClasses.FOSSEEFlowsheets.LoadFlowsheet(t.Result)));
                            }
                        });
                        FOSSEEList.SelectedIndex = -1;
                    }
                }
                ;
            };

            var fosseecontainer = c.GetDefaultContainer();
            var l1  = c.CreateAndAddLabelRow3(fosseecontainer, "About the Project");
            var l2  = c.CreateAndAddDescriptionRow(fosseecontainer, "FOSSEE, IIT Bombay, invites chemical engineering students, faculty and practitioners to the flowsheeting project using DWSIM. We want you to convert existing flowsheets into DWSIM and get honoraria and certificates.");
            var bu1 = c.CreateAndAddButtonRow(fosseecontainer, "Submit a Flowsheet", null, (b1, e1) => Process.Start("https://dwsim.fossee.in/flowsheeting-project"));
            var bu2 = c.CreateAndAddButtonRow(fosseecontainer, "About FOSSEE", null, (b2, e2) => Process.Start("https://fossee.in/"));
            var l3  = c.CreateAndAddLabelRow3(fosseecontainer, "Completed Flowsheets");

            if (GlobalSettings.Settings.RunningPlatform() == GlobalSettings.Settings.Platform.Mac)
            {
                fosseecontainer.BackgroundColor = SystemColors.ControlBackground;
            }
            else
            {
                fosseecontainer.BackgroundColor = bgcolor;
                l1.TextColor        = Colors.White;
                l2.TextColor        = Colors.White;
                l3.TextColor        = Colors.White;
                bu1.TextColor       = Colors.White;
                bu2.TextColor       = Colors.White;
                bu1.BackgroundColor = bgcolor;
                bu2.BackgroundColor = bgcolor;
            }
            fosseecontainer.Add(FOSSEEList);
            fosseecontainer.EndVertical();

            var tabview = new TabControl();
            var tab1    = new TabPage(MostRecentList)
            {
                Text = "Recent Files"
            };;
            var tab2 = new TabPage(SampleList)
            {
                Text = "Samples"
            };;
            var tab2a = new TabPage(fosseecontainer)
            {
                Text = "FOSSEE Flowsheets"
            };;
            var tab3 = new TabPage(FoldersList)
            {
                Text = "Recent Folders"
            };;

            tabview.Pages.Add(tab1);
            tabview.Pages.Add(tab2);
            tabview.Pages.Add(tab2a);
            tabview.Pages.Add(tab3);

            tableright.Rows.Add(new TableRow(tabview));

            var tl = new DynamicLayout();

            tl.Add(new TableRow(stack, tableright));

            TableContainer = new TableLayout
            {
                Padding = 10,
                Spacing = new Size(5, 5),
                Rows    = { new TableRow(tl) }
            };

            if (GlobalSettings.Settings.RunningPlatform() == GlobalSettings.Settings.Platform.Mac)
            {
                TableContainer.BackgroundColor = SystemColors.ControlBackground;
            }
            else
            {
                TableContainer.BackgroundColor = bgcolor;
            }


            Content = TableContainer;

            var quitCommand = new Command {
                MenuText = "Quit".Localize(), Shortcut = Application.Instance.CommonModifier | Keys.Q
            };

            quitCommand.Executed += (sender, e) =>
            {
                DWSIM.GlobalSettings.Settings.SaveSettings("dwsim_newui.ini");
                {
                    if (MessageBox.Show(this, "ConfirmAppExit".Localize(), "AppExit".Localize(), MessageBoxButtons.YesNo, MessageBoxType.Information, MessageBoxDefaultButton.No) == DialogResult.Yes)
                    {
                        Application.Instance.Quit();
                    }
                }
            };

            var aboutCommand = new Command {
                MenuText = "About".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "information.png"))
            };

            aboutCommand.Executed += (sender, e) => new AboutBox().Show();

            var aitem1 = new ButtonMenuItem {
                Text = "Preferences".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "icons8-sorting_options.png"))
            };

            aitem1.Click += (sender, e) =>
            {
                new Forms.Forms.GeneralSettings().GetForm().Show();
            };

            var hitem1 = new ButtonMenuItem {
                Text = "Help".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "help_browser.png"))
            };

            hitem1.Click += (sender, e) =>
            {
                Process.Start("http://dwsim.inforside.com.br/docs/crossplatform/help/");
            };

            var hitem2 = new ButtonMenuItem {
                Text = "Support".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "help_browser.png"))
            };

            hitem2.Click += (sender, e) =>
            {
                Process.Start("http://dwsim.inforside.com.br/wiki/index.php?title=Support");
            };

            var hitem3 = new ButtonMenuItem {
                Text = "Report a Bug".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "help_browser.png"))
            };

            hitem3.Click += (sender, e) =>
            {
                Process.Start("https://sourceforge.net/p/dwsim/tickets/");
            };

            var hitem4 = new ButtonMenuItem {
                Text = "Go to DWSIM's Website".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "help_browser.png"))
            };

            hitem4.Click += (sender, e) =>
            {
                Process.Start("http://dwsim.inforside.com.br");
            };

            // create menu
            Menu = new MenuBar
            {
                ApplicationItems = { aitem1 },
                QuitItem         = quitCommand,
                HelpItems        = { hitem1, hitem4, hitem2, hitem3 },
                AboutItem        = aboutCommand
            };

            Shown += MainForm_Shown;

            Closing += MainForm_Closing;

            //Plugins

            LoadPlugins();
        }
Exemple #13
0
        private void InicializeComponents()
        {
            ClientSize = new Size(350, 150);

            List <Projekcija> sveProjekcijePodaci = Projekcija.Sve();

            this.sveProjekcijeLabela = new Label {
                Text = "Izaberite projekciju: "
            };
            this.sveProjekcijeComboBox = new ComboBox( );

            this.obrisi = new Button {
                Text    = "Obrisi",
                ToolTip = "Obrisi projekciju"
            };
            this.obrisi.Visible = false;

            foreach (Projekcija p in sveProjekcijePodaci)
            {
                sveProjekcijeComboBox.Items.Add(p.Film.Naziv + ", " + p.Sala.Naziv, p.ProjekcijaId.ToString());
            }


            this.obrisi.Click += (sender, e) => obrisiProjekciju();

            this.sveProjekcijeComboBox.SelectedIndexChanged += (sender, e) => {
                this.projekcija_id  = int.Parse(this.sveProjekcijeComboBox.SelectedKey);
                this.obrisi.Visible = true;
            };

            layout = new DynamicLayout()
            {
                Spacing = new Size(0, 3)
            };

            layout.BeginVertical();
            layout.Add(null, true, true);
            layout.BeginHorizontal();
            layout.Add(null);
            layout.Add(this.sveProjekcijeLabela, true, false);
            layout.Add(null);
            layout.EndHorizontal();

            layout.BeginHorizontal();
            layout.Add(null);
            layout.Add(this.sveProjekcijeComboBox, true, false);
            layout.Add(null);
            layout.EndHorizontal();

            layout.Add(null, true, true);

            layout.BeginHorizontal();
            layout.Add(null);
            layout.Add(this.obrisi, true, false);
            layout.Add(null);
            layout.EndHorizontal();

            layout.Add(null, true, true);

            Content = layout;
        }
Exemple #14
0
        public Preferences()
        {
            /* dialog attributes */

            this.Text       = "Preferences";
            this.ClientSize = new Size(400, 120);
            this.Resizable  = false;

            /* dialog controls */

            var groupBoxFolder = new GroupBox();

            groupBoxFolder.Text = "Notes folder";

            var textBoxFolder = new TextBox();

            textBoxFolder.Text = Notedown.Preferences.Folder;

            var buttonOk = new Button();

            buttonOk.Text   = "Ok";
            buttonOk.Size   = new Size(90, 26);
            buttonOk.Click += delegate
            {
                this.DialogResult = DialogResult.Ok;
                this.Close();
            };

            var buttonCancel = new Button();

            buttonCancel.Text   = "Cancel";
            buttonCancel.Size   = new Size(90, 26);
            buttonCancel.Click += delegate
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            };

            /* dialog layout */

            var layoutFolder = new DynamicLayout(groupBoxFolder);

            layoutFolder.BeginVertical();
            layoutFolder.Add(textBoxFolder);
            layoutFolder.EndVertical();

            var layout = new DynamicLayout(this);

            layout.BeginVertical(new Padding(10, 5), new Size(10, 10));

            layout.Add(groupBoxFolder);

            layout.BeginVertical(Padding.Empty, Size.Empty);
            layout.BeginHorizontal();
            layout.Add(null, true);
            layout.Add(buttonCancel);
            layout.Add(buttonOk);
            layout.Add(null, true);
            layout.EndHorizontal();
            layout.EndVertical();

            layout.EndVertical();

            /* dialog accessors */

            TextBoxFolder = textBoxFolder;
        }
Exemple #15
0
        public DragDropSection()
        {
            // drag data object

            showDragOverEvents = new CheckBox {
                Text = "Show DragOver Events"
            };
            var includeImageCheck = new CheckBox {
                Text = "Include Image"
            };
            var textBox = new TextBox {
                Text = "Some text"
            };
            var allowedEffectDropDown = new EnumDropDown <DragEffects> {
                SelectedValue = DragEffects.All
            };

            dragOverEffect = new EnumDropDown <DragEffects> {
                SelectedValue = DragEffects.Copy
            };

            var htmlTextArea      = new TextArea();
            var selectFilesButton = new Button {
                Text = "Select Files"
            };

            Uri[] uris = null;
            selectFilesButton.Click += (sender, e) =>
            {
                var ofd = new OpenFileDialog();
                ofd.MultiSelect = true;
                ofd.ShowDialog(this);
                uris = ofd.Filenames.Select(r => new Uri(r)).ToArray();
                if (uris.Length == 0)
                {
                    uris = null;
                }
            };

            Func <DataObject> createDataObject = () =>
            {
                var data = new DataObject();
                if (!string.IsNullOrEmpty(textBox.Text))
                {
                    data.Text = textBox.Text;
                }
                if (uris != null)
                {
                    data.Uris = uris;
                }
                if (!string.IsNullOrEmpty(htmlTextArea.Text))
                {
                    data.Html = htmlTextArea.Text;
                }
                if (includeImageCheck.Checked == true)
                {
                    data.Image = TestIcons.Logo;
                }
                return(data);
            };

            // sources

            var buttonSource = new Button {
                Text = "Source"
            };

            buttonSource.MouseDown += (sender, e) =>
            {
                buttonSource.DoDragDrop(createDataObject(), allowedEffectDropDown.SelectedValue);
                e.Handled = true;
            };

            var panelSource = new Panel {
                BackgroundColor = Colors.Red, Size = new Size(50, 50)
            };

            panelSource.MouseDown += (sender, e) =>
            {
                panelSource.DoDragDrop(createDataObject(), allowedEffectDropDown.SelectedValue);
                e.Handled = true;
            };

            var treeSource = new TreeGridView {
                Size = new Size(200, 200)
            };

            treeSource.DataStore = CreateTreeData();
            SetupTreeColumns(treeSource);
            treeSource.MouseMove += (sender, e) =>
            {
                if (e.Buttons == MouseButtons.Primary)
                {
                    var cell = treeSource.GetCellAt(e.Location);
                    if (cell.Item == null || cell.ColumnIndex == -1)
                    {
                        return;
                    }
                    var data     = createDataObject();
                    var selected = treeSource.SelectedItems.OfType <TreeGridItem>().Select(r => (string)r.Values[0]);
                    data.SetString(string.Join(";", selected), "my-tree-data");

                    treeSource.DoDragDrop(data, allowedEffectDropDown.SelectedValue);
                    e.Handled = true;
                }
            };

            var gridSource = new GridView {
            };

            SetupGridColumns(gridSource);
            gridSource.DataStore  = CreateGridData();
            gridSource.MouseMove += (sender, e) =>
            {
                if (e.Buttons == MouseButtons.Primary)
                {
                    var data     = createDataObject();
                    var selected = gridSource.SelectedItems.OfType <GridItem>().Select(r => (string)r.Values[0]);
                    data.SetString(string.Join(";", selected), "my-grid-data");

                    gridSource.DoDragDrop(data, allowedEffectDropDown.SelectedValue);
                    e.Handled = true;
                }
            };


            // destinations

            var buttonDestination = new Button {
                Text = "Drop here!", AllowDrop = true
            };

            buttonDestination.DragEnter += (sender, e) => buttonDestination.Text = "Now, drop it!";
            buttonDestination.DragLeave += (sender, e) => buttonDestination.Text = "Drop here!";
            LogEvents(buttonDestination);

            var drawableDest = new Drawable {
                BackgroundColor = Colors.Blue, AllowDrop = true, Size = new Size(50, 50)
            };

            LogEvents(drawableDest);
            drawableDest.DragEnter += (sender, e) =>
            {
                if (e.Effects != DragEffects.None)
                {
                    drawableDest.BackgroundColor = Colors.Green;
                }
            };
            drawableDest.DragLeave += (sender, e) =>
            {
                if (e.Effects != DragEffects.None)
                {
                    drawableDest.BackgroundColor = Colors.Blue;
                }
            };
            drawableDest.DragDrop += (sender, e) =>
            {
                if (e.Effects != DragEffects.None)
                {
                    drawableDest.BackgroundColor = Colors.Blue;
                }
            };

            var dragMode = new RadioButtonList
            {
                Orientation = Orientation.Vertical,
                Items       =
                {
                    new ListItem {
                        Text = "No Restriction", Key = ""
                    },
                    new ListItem {
                        Text = "RestrictToOver", Key = "over"
                    },
                    new ListItem {
                        Text = "RestrictToInsert", Key = "insert"
                    },
                    new ListItem {
                        Text = "RestrictToNode", Key = "node"
                    },
                    new ListItem {
                        Text = "No Node", Key = "none"
                    }
                },
                SelectedIndex = 0
            };
            var treeDest = new TreeGridView {
                AllowDrop = true, Size = new Size(200, 200)
            };
            var treeDestData = CreateTreeData();

            treeDest.DataStore = treeDestData;
            treeDest.DragOver += (sender, e) =>
            {
                var info = treeDest.GetDragInfo(e);
                if (info == null)
                {
                    return;                     // not supported
                }
                switch (dragMode.SelectedKey)
                {
                case "over":
                    info.RestrictToOver();
                    break;

                case "insert":
                    info.RestrictToInsert();
                    break;

                case "node":
                    info.RestrictToNode(treeDestData[2]);
                    break;

                case "none":
                    info.Item = info.Parent = null;
                    break;
                }
            };
            SetupTreeColumns(treeDest);
            LogEvents(treeDest);

            var gridDest = new GridView {
                AllowDrop = true
            };
            var gridDestData = CreateGridData();

            gridDest.DataStore = gridDestData;
            gridDest.DragOver += (sender, e) =>
            {
                var info = gridDest.GetDragInfo(e);
                if (info == null)
                {
                    return;                     // not supported
                }
                switch (dragMode.SelectedKey)
                {
                case "over":
                    info.RestrictToOver();
                    break;

                case "insert":
                    info.RestrictToInsert();
                    break;

                case "node":
                    info.Index    = 2;
                    info.Position = GridDragPosition.Over;
                    break;

                case "none":
                    info.Index = -1;
                    break;
                }
            };
            SetupGridColumns(gridDest);
            LogEvents(gridDest);



            // layout

            var layout = new DynamicLayout {
                Padding = 10, DefaultSpacing = new Size(4, 4)
            };

            layout.BeginHorizontal();

            layout.BeginCentered();

            layout.AddSeparateRow(showDragOverEvents);
            layout.AddSeparateRow("AllowedEffect", allowedEffectDropDown, null);
            layout.AddSeparateRow("DragOver Effect", dragOverEffect, null);

            layout.BeginGroup("DataObject", 10);
            layout.AddRow("Text", textBox);
            layout.AddRow("Html", htmlTextArea);
            layout.BeginHorizontal();
            layout.AddSpace();
            layout.BeginVertical();
            layout.AddCentered(includeImageCheck);
            layout.AddCentered(selectFilesButton);
            layout.EndVertical();
            layout.EndGroup();
            layout.Add(dragMode);
            layout.AddSpace();

            layout.EndCentered();

            layout.BeginVertical(xscale: true);
            layout.AddRange("Drag sources:", buttonSource, panelSource);
            layout.Add(treeSource, yscale: true);
            layout.Add(gridSource, yscale: true);
            layout.EndVertical();

            layout.BeginVertical(xscale: true);
            layout.AddRange("Drag destinations:", buttonDestination, drawableDest);
            layout.Add(treeDest, yscale: true);
            layout.Add(gridDest, yscale: true);
            layout.EndVertical();

            layout.EndHorizontal();

            Content = layout;
        }
Exemple #16
0
        public ScalingSection()
        {
            TableLayout tableLayout;

            var layout = new DynamicLayout {
                DefaultSpacing = new Size(5, 5), Padding = new Padding(10)
            };
            var size = new Size(-1, 100);

            tableLayout = new TableLayout(1, 1)
            {
                BackgroundColor = Colors.Blue, Size = size, Spacing = new Size(5, 5), Padding = new Padding(5)
            };
            tableLayout.Add(new Label {
                Text = "1x1, should scale to fill entire region with 5px padding around border", BackgroundColor = Colors.Red
            }, 0, 0, false, false);
            layout.Add(tableLayout, yscale: true);

            tableLayout = new TableLayout(2, 2)
            {
                BackgroundColor = Colors.Blue, Size = size, Spacing = new Size(5, 5), Padding = new Padding(5)
            };
            tableLayout.Add(new Label {
                Text = "2x2, should scale with extra space on top && left", BackgroundColor = Colors.Red
            }, 1, 1, false, false);
            layout.Add(tableLayout, yscale: true);

            tableLayout = new TableLayout(2, 2)
            {
                BackgroundColor = Colors.Blue, Size = size, Spacing = new Size(5, 5), Padding = new Padding(5)
            };
            tableLayout.Add(new Label {
                Text = "2x2, should scale with extra space on bottom && right", BackgroundColor = Colors.Red
            }, 0, 0, true, true);
            layout.Add(tableLayout, yscale: true);

            tableLayout = new TableLayout(3, 3)
            {
                BackgroundColor = Colors.Blue, Size = size, Spacing = new Size(5, 5), Padding = new Padding(5)
            };
            tableLayout.Add(new Label {
                Text = "3x3, should scale with extra space all around (10px)", BackgroundColor = Colors.Red
            }, 1, 1, true, true);
            layout.Add(tableLayout, yscale: true);

            tableLayout = new TableLayout(2, 2)
            {
                BackgroundColor = Colors.Blue, Size = size, Spacing = new Size(5, 5), Padding = new Padding(5)
            };
            tableLayout.Add(new Label {
                Text = "2x2, should not scale and be top left", BackgroundColor = Colors.Red
            }, 0, 0, false, false);
            layout.Add(tableLayout, yscale: true);

            tableLayout = new TableLayout(2, 2)
            {
                BackgroundColor = Colors.Blue, Size = size, Spacing = new Size(5, 5), Padding = new Padding(5)
            };
            tableLayout.SetColumnScale(0);
            tableLayout.SetRowScale(0);
            tableLayout.Add(new Label {
                Text = "2x2, should not scale and be bottom-right", BackgroundColor = Colors.Red
            }, 1, 1);
            layout.Add(tableLayout, yscale: true);

            tableLayout = new TableLayout(3, 3)
            {
                BackgroundColor = Colors.Blue, Size = size, Spacing = new Size(5, 5), Padding = new Padding(5)
            };
            tableLayout.SetColumnScale(0);
            tableLayout.SetRowScale(0);
            tableLayout.Add(new Label {
                Text = "3x3, should not scale and be bottom-right", BackgroundColor = Colors.Red
            }, 1, 1);
            layout.Add(tableLayout, yscale: true);

            tableLayout = new TableLayout(3, 3)
            {
                BackgroundColor = Colors.Blue, Size = size, Spacing = new Size(5, 5), Padding = new Padding(5)
            };
            tableLayout.SetColumnScale(0);
            tableLayout.SetColumnScale(2);
            tableLayout.SetRowScale(0);
            tableLayout.SetRowScale(2);
            tableLayout.Add(new Label {
                Text = "2x2, should not scale and be centered", BackgroundColor = Colors.Red
            }, 1, 1);
            layout.Add(tableLayout, yscale: true);

            Content = layout;
        }
Exemple #17
0
        void InitUi()
        {
            // input
            _textBoxName = new TextBox {
                PlaceholderText = "*Name", Width = 200
            };
            _comboBoxLevel = new ComboBox {
                Width = 100
            };
            _dropDownScritpType = new DropDown {
                Width = 120
            };
            _textBoxShellPath = new TextBox {
                PlaceholderText = "*Shell Url", Width = 300
            };
            _textBoxShellPass = new TextBox {
                PlaceholderText = "*Pass"
            };
            _textBoxRemark = new TextBox {
                PlaceholderText = "Remark"
            };

            // _buttonAdd
            _buttonAdd = new Button {
                Text = StrRes.GetString("StrAdd", "Add")
            };
            _buttonAdd.Click += buttonAdd_Click;

            // _buttonAlter
            _buttonAlter = new Button {
                Text = StrRes.GetString("StrAlter", "Alter")
            };
            _buttonAlter.Click += _buttonAlter_Click;

            // _buttonAdvanced
            _buttonAdvanced = new Button {
                Text = StrRes.GetString("StrAdvanced", "Advanced")
            };
            _buttonAdvanced.Click += _buttonAdvanced_Click;

            var codeList1 = new List <IListItem>
            {
                new ListItem {
                    Text = "UTF-8"
                },
                new ListItem {
                    Text = "GB2312"
                }
            };
            var codeList2 = new List <IListItem>
            {
                new ListItem {
                    Text = "UTF-8"
                },
                new ListItem {
                    Text = "GB2312"
                },
                new ListItem {
                    Text = "Big5"
                },
                new ListItem {
                    Text = "Shift-JIS"
                },
                new ListItem {
                    Text = "EUC-JP"
                },
                new ListItem {
                    Text = "EUC-KR"
                },
                new ListItem {
                    Text = "ISO-8859-1"
                }
            };

            _dropDownServerCoding = new DropDown();
            _dropDownServerCoding.Items.AddRange(codeList1);
            _dropDownServerCoding.SelectedIndex = 0;
            _dropDownWebCoding = new DropDown();
            _dropDownWebCoding.Items.AddRange(codeList2);
            _dropDownWebCoding.SelectedIndex = 0;

            // _buttonDefault
            _buttonDefault = new Button {
                Text = "Default"
            };
            _buttonDefault.Click += _buttonDefault_Click;

            // _richTextBoxSetting
            _richTextBoxSetting = new TextArea {
                Wrap = false
            };

            // _panelAdvanced
            _panelAdvanced = new DynamicLayout {
                Padding = new Padding(5, 5), Spacing = new Size(5, 5)
            };
            _panelAdvanced.BeginVertical();
            _panelAdvanced.BeginHorizontal();
            _panelAdvanced.AddAutoSized(new Label
            {
                Text          = StrRes.GetString("StrServerCoding", "ServerCoding"),
                VerticalAlign = VerticalAlign.Middle
            }, centered: true);
            _panelAdvanced.AddAutoSized(_dropDownServerCoding, centered: true);
            _panelAdvanced.AddAutoSized(new Label
            {
                Text          = StrRes.GetString("StrWebCoding", "WebCoding"),
                VerticalAlign = VerticalAlign.Middle
            }, centered: true);
            _panelAdvanced.AddAutoSized(_dropDownWebCoding, centered: true);
            _panelAdvanced.Add(null);
            _panelAdvanced.AddAutoSized(_buttonDefault, centered: true);
            _panelAdvanced.EndHorizontal();
            _panelAdvanced.EndVertical();
            //_panelAdvanced.AddSeparateRow(new Label { Text = StrRes.GetString("StrServerCoding", "ServerCoding"), VerticalAlign = VerticalAlign.Middle }, _dropDownServerCoding);
            //_panelAdvanced.AddSeparateRow(new Label { Text = StrRes.GetString("StrWebCoding", "WebCoding"), VerticalAlign = VerticalAlign.Middle }, _dropDownWebCoding);
            _panelAdvanced.AddSeparateRow(_richTextBoxSetting);

            var panel1 = new DynamicLayout {
                Padding = new Padding(5, 5), Spacing = new Size(5, 5)
            };

            //line 1
            panel1.BeginVertical();
            panel1.BeginHorizontal();
            panel1.Add(_textBoxName, xscale: true);
            panel1.Add(_comboBoxLevel);
            panel1.Add(_dropDownScritpType);
            panel1.EndHorizontal();
            panel1.EndVertical();
            //line 2
            panel1.BeginVertical();
            panel1.BeginHorizontal();
            panel1.Add(_textBoxShellPath, true);
            panel1.Add(_textBoxShellPass);
            panel1.EndHorizontal();
            panel1.EndVertical();
            //line 3
            panel1.AddRow(_textBoxRemark);
            //line 4
            panel1.BeginVertical();
            panel1.BeginHorizontal();
            panel1.Add(_buttonAdvanced);
            panel1.Add(null, true);
            panel1.Add(_buttonAdd);
            panel1.Add(_buttonAlter);
            panel1.EndHorizontal();
            panel1.EndVertical();
            //line 5
            panel1.Add(_panelAdvanced, false, true);
            _panelAdvanced.Visible = false;

            //_p12 = new Splitter
            //{
            //	Panel1 = panel1,
            //	Panel2 = _panelAdvanced,
            //	Orientation = SplitterOrientation.Vertical,
            //	Position = 130,
            //};
            //_p12.FixedPanel = SplitterFixedPanel.Panel1;
            //_p12.Panel2.Visible = false;

            Content    = panel1;
            ClientSize = new Size(500, 130);
            Title      = "Edit Shell";
            Icon       = Application.Instance.MainForm.Icon;
        }
Exemple #18
0
        public void InitializeComponents()
        {
            meni = new MenuBar {
                Items =
                {
                    new ButtonMenuItem {
                        Text = "Почетна", Items ={ this.pocetnaCmd            }
                    },
                    new SeparatorMenuItem(),
                    new ButtonMenuItem {
                        Text = "Одјави се", Items ={ this.prijaviSeCmd          }
                    }
                }
            };

            // labele
            izdvajamoLabela = new Label {
                Text = "\tИздвајамо: ", Font = new Font(SystemFont.Bold, 14)
            };
            najnovijeLabela = new Label {
                Text = "\tНајновије: ", Font = new Font(SystemFont.Bold, 14)
            };
            kategorijeLabela = new Label {
                Text = "\tКатегорије: ", Font = new Font(SystemFont.Bold, 12)
            };
            separator = new Label {
                Text = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t",
                Font = new Font(SystemFont.Default, 10, FontDecoration.Strikethrough)
            };

            // pretraga
            lupaImg = new ImageView {
                Image = Icon.FromResource("search-icon")
            };
            lupaImg.Width       = 30;
            lupaImg.Height      = 30;
            lupaImg.MouseEnter += (sender, e) => {
                lupaImg.Width  += 10;
                lupaImg.Height += 10;
            };
            lupaImg.MouseLeave += (sender, e) => {
                lupaImg.Width  = 30;
                lupaImg.Height = 30;
            };
            pretragaBox = new TextBox( )
            {
                PlaceholderText = "Унесите назив филма..."
            };
            pretragaBox.ToolTip = "Притисните ентер за претрагу.";
            pretragaBox.KeyUp  += (sender, e) => {
                Console.WriteLine("Pretraga");
            };
            pretragaLayout = new DynamicLayout( )
            {
                Spacing = new Size(10, 10)
            };
            pretragaLayout.BeginVertical();
            pretragaLayout.EndBeginHorizontal();
            pretragaLayout.Add(null, true, false);
            pretragaLayout.Add(lupaImg);
            pretragaLayout.Add(pretragaBox);
            pretragaLayout.Add(null, true, false);
            pretragaLayout.EndHorizontal();
            pretragaLayout.EndVertical();

            // kategorije
            List <string> listaKategorija = ZanrC.VratiSveZanrove();
            List <Label>  listaLabela     = new List <Label> ( );

            listaKategorija.ForEach(x => listaLabela.Add(new Label {
                Text = x.ToString()
            }));

            listaLabela.ForEach(x => {
                x.MouseEnter += (sender, e) => {
                    x.Font = new Font(SystemFont.Default, 10, FontDecoration.Underline);
                };

                x.MouseLeave += (sender, e) => {
                    x.Font = new Font(SystemFont.Default, 10, FontDecoration.None);
                };
                x.MouseDown += (sender, e) => {
                    Console.WriteLine("Kliknuto: " + x.Text);
                };
            });
            kategorijePanel = new DynamicLayout( )
            {
                Spacing = new Size(10, 10),
                Padding = new Padding(10, 10)
            };
            kategorijePanel.BeginVertical();
            listaLabela.ForEach(x => {
                kategorijePanel.BeginHorizontal();
                kategorijePanel.Add(null, true, false);
                kategorijePanel.Add(x);
                //kategorijePanel.Add( null , true , false );
                kategorijePanel.EndHorizontal();
            });
            kategorijePanel.EndVertical();

            // pretraga i desni panel
            desniPanel = new DynamicLayout( )
            {
                Spacing         = new Size(10, 10),
                BackgroundColor = Color.FromArgb(255, 238, 91, 70),
                Size            = new Size(300, 500)
            };
            desniPanel.BeginVertical();
            desniPanel.Add(pretragaLayout);
            desniPanel.Add(kategorijeLabela);
            separator.Text = "\t\t\t\t\t\t\t";
            desniPanel.Add(separator);
            desniPanel.Add(kategorijePanel);
            desniPanel.EndVertical();

            izdvajamoPanel = new DynamicLayout( )
            {
                Padding         = new Padding(10, 10),
                BackgroundColor = Color.FromArgb(40, 40, 40, 50),
                Spacing         = new Size(5, 5),
            };
            izdvajamoPanel.BeginVertical();

            // inicijalizacija izdvajamo panela
            List <Projekcija> listaProjekcijaPodaci = Projekcija.Sve();

            for (int i = 0; i < listaProjekcijaPodaci.Count - 1; i++)
            {
                // nasumicno odabiranje projekcije
                if (i == Metode.VratiNasumicniInt(0, listaProjekcijaPodaci.Count))
                {
                    continue;
                }

                Label nazivFilma = new Label {
                    Text = "Назив филма: " + listaProjekcijaPodaci[i].Film.Naziv
                };
                Label nazivSale = new Label {
                    Text = "Назив сале:  " + listaProjekcijaPodaci[i].Sala.Naziv
                };
                Label vreme = new Label {
                    Text = "Време:\t  " + listaProjekcijaPodaci[i].Vreme
                };
                Button kupi = new Button {
                    Text = "Kупите карту"
                };
                Button vise = new Button {
                    Text = "Више информација"
                };
                var podPanel = new DynamicLayout( )
                {
                    Spacing = new Size(10, 10)
                };
                var dugmici = new DynamicLayout {
                    Spacing = new Size(10, 10)
                };

                kupi.Click += (sender, e) => KupiKartu(listaProjekcijaPodaci[i]);
                vise.Click += (sender, e) => PrikaziVise(listaProjekcijaPodaci[i]);

                podPanel.BeginVertical();
                podPanel.Add(nazivFilma);
                podPanel.Add(nazivSale);
                podPanel.Add(vreme);

                dugmici.BeginVertical();
                dugmici.BeginHorizontal();
                dugmici.Add(null, true, false);
                dugmici.Add(kupi);
                dugmici.Add(null, true, false);
                dugmici.EndHorizontal();

                dugmici.BeginHorizontal();
                dugmici.Add(null, true, false);
                dugmici.Add(vise);
                dugmici.Add(null, true, false);
                dugmici.EndHorizontal();
                dugmici.EndVertical();

                podPanel.Add(dugmici);
                podPanel.EndVertical();

                izdvajamoPanel.Add(podPanel);
            }
            izdvajamoPanel.EndVertical();

            najnovijePanel = new DynamicLayout()
            {
                Padding         = new Padding(10, 10),
                BackgroundColor = Color.FromArgb(40, 40, 40, 50),
                Spacing         = new Size(10, 10),
            };

            najnovijePanel.BeginVertical();
            for (int i = 0; i < listaProjekcijaPodaci.Count - 1; i++)
            {
                if (i == Metode.VratiNasumicniInt(0, listaProjekcijaPodaci.Count))
                {
                    continue;
                }

                Label nazivFilma = new Label {
                    Text = "Назив филма: " + listaProjekcijaPodaci[i].Film.Naziv
                };
                Label nazivSale = new Label {
                    Text = "Назив сале:  " + listaProjekcijaPodaci[i].Sala.Naziv
                };
                Label vreme = new Label {
                    Text = "Време:\t  " + listaProjekcijaPodaci[i].Vreme
                };
                Button kupi = new Button {
                    Text = "Kупите карту"
                };
                Button vise = new Button {
                    Text = "Више информација"
                };
                var podPanel = new DynamicLayout( )
                {
                    Spacing = new Size(10, 10)
                };
                var dugmici = new DynamicLayout {
                    Spacing = new Size(5, 5)
                };

                kupi.Click += (sender, e) => KupiKartu(listaProjekcijaPodaci[i]);
                vise.Click += (sender, e) => PrikaziVise(listaProjekcijaPodaci[i]);

                podPanel.BeginVertical();
                podPanel.Add(nazivFilma);
                podPanel.Add(nazivSale);
                podPanel.Add(vreme);

                dugmici.BeginVertical();
                dugmici.BeginHorizontal();
                dugmici.Add(null, true, false);
                dugmici.Add(kupi);
                dugmici.Add(null, true, false);
                dugmici.EndHorizontal();

                dugmici.BeginHorizontal();
                dugmici.Add(null, true, false);
                dugmici.Add(vise);
                dugmici.Add(null, true, false);
                dugmici.EndHorizontal();
                dugmici.EndVertical();


                podPanel.Add(dugmici);
                podPanel.EndVertical();

                najnovijePanel.Add(podPanel);
            }
            najnovijePanel.EndBeginVertical();


            leviPanel = new DynamicLayout()
            {
                Spacing = new Size(10, 10),
                Padding = new Padding(10, 10)
            };
            leviPanel.BeginVertical();
            leviPanel.Add(izdvajamoLabela);
            leviPanel.Add(separator);
            leviPanel.Add(izdvajamoPanel);
            leviPanel.Add(najnovijeLabela);
            leviPanel.Add(separator);
            leviPanel.Add(najnovijePanel);
            leviPanel.EndVertical();

            Scrollable scrollLeviPanel = new Scrollable {
                Content = leviPanel, Size = new Size(400, 500)
            };

            // try with table layout
            var mainPanel = new TableLayout()
            {
                Padding = new Padding(10),                // padding around cells
                Spacing = new Size(5, 5),                 // spacing between each cell
                Rows    =
                {
                    new TableRow(
                        new TableCell(scrollLeviPanel),
                        new TableCell(desniPanel)
                        )
                }
            };

            panel = mainPanel;
        }
Exemple #19
0
        void Initialize()
        {
            var su  = MatStream.GetFlowsheet().FlowsheetOptions.SelectedUnitSystem;
            var nf  = MatStream.GetFlowsheet().FlowsheetOptions.NumberFormat;
            var nff = MatStream.GetFlowsheet().FlowsheetOptions.FractionNumberFormat;

            var container2 = new DynamicLayout();

            s.CreateAndAddLabelRow(container, "Material Stream Property Editor");

            s.CreateAndAddDescriptionRow(container, "Except for compound amounts, property values are updated/stored as they are changed/edited.");

            s.CreateAndAddLabelRow(container, "Material Stream Details");

            s.CreateAndAddTwoLabelsRow(container, "Status", MatStream.GraphicObject.Active ? "Active" : "Inactive");

            s.CreateAndAddStringEditorRow(container, "Name", MatStream.GraphicObject.Tag, (TextBox arg3, EventArgs ev) =>
            {
                MatStream.GraphicObject.Tag = arg3.Text;
            }, () => CallSolverIfNeeded());

            s.CreateAndAddDropDownRow(container, "Compound Amount Basis",
                                      new List <string>()
            {
                "Molar Fractions", "Mass Fractions", "Volumetric Fractions", "Molar Flows", "Mass Flows", "Volumetric Flows", "Default"
            },
                                      (int)MatStream.FloatingTableAmountBasis, (sender, e) =>
            {
                MatStream.FloatingTableAmountBasis = (DWSIM.Interfaces.Enums.CompositionBasis)sender.SelectedIndex;
            });
            s.CreateAndAddDescriptionRow(container, "Select the basis to display compound amounts in floating tables, if enabled.");

            s.CreateAndAddLabelRow(container, "Property Package");

            var proppacks = MatStream.GetFlowsheet().PropertyPackages.Values.Select((x) => x.Tag).ToList();

            if (proppacks.Count == 0)
            {
                MatStream.GetFlowsheet().ShowMessage("Error: please add at least one Property Package before continuing.", IFlowsheet.MessageType.GeneralError);
            }
            else
            {
                var selectedpp = MatStream.PropertyPackage.Tag;
                s.CreateAndAddDropDownRow(container, "Property Package", proppacks, proppacks.IndexOf(selectedpp), (DropDown arg1, EventArgs ev) =>
                {
                    if (proppacks.Count > 0)
                    {
                        MatStream.PropertyPackage = (PropertyPackage)MatStream.GetFlowsheet().PropertyPackages.Values.Where((x) => x.Tag == proppacks[arg1.SelectedIndex]).FirstOrDefault();
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
            }

            var flashalgos = MatStream.GetFlowsheet().FlowsheetOptions.FlashAlgorithms.Select(x => x.Tag).ToList();

            flashalgos.Insert(0, "Default");

            var cbFlashAlg = s.CreateAndAddDropDownRow(container, "Flash Algorithm", flashalgos, 0, null);

            if (!string.IsNullOrEmpty(MatStream.PreferredFlashAlgorithmTag))
            {
                cbFlashAlg.SelectedIndex = Array.IndexOf(flashalgos.ToArray(), MatStream.PreferredFlashAlgorithmTag);
            }
            else
            {
                cbFlashAlg.SelectedIndex = 0;
            }

            cbFlashAlg.SelectedIndexChanged += (sender, e) =>
            {
                MatStream.PreferredFlashAlgorithmTag = cbFlashAlg.SelectedValue.ToString();
                if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                {
                    ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                }
            };

            container.Add(container2);

            s.CreateAndAddLabelRow(container2, "State Specification");

            switch (MatStream.GraphicObject.ObjectType)
            {
            case ObjectType.MaterialStream:
                var    ms       = MatStream;
                int    position = 0;
                Double val;
                switch (ms.SpecType)
                {
                case StreamSpec.Temperature_and_Pressure:
                    position = 0;
                    break;

                case StreamSpec.Temperature_and_VaporFraction:
                    position = 1;
                    break;

                case StreamSpec.Pressure_and_VaporFraction:
                    position = 2;
                    break;

                case StreamSpec.Pressure_and_Enthalpy:
                    position = 3;
                    break;

                case StreamSpec.Pressure_and_Entropy:
                    position = 4;
                    break;
                }

                s.CreateAndAddDropDownRow(container2, "Specified Variables", StringResources.flash_spec().ToList(), position, (DropDown arg3, EventArgs ev) =>
                {
                    switch (arg3.SelectedIndex)
                    {
                    case 0:
                        ms.SpecType = StreamSpec.Temperature_and_Pressure;
                        break;

                    case 1:
                        ms.SpecType = StreamSpec.Temperature_and_VaporFraction;
                        break;

                    case 2:
                        ms.SpecType = StreamSpec.Pressure_and_VaporFraction;
                        break;

                    case 3:
                        ms.SpecType = StreamSpec.Pressure_and_Enthalpy;
                        break;

                    case 4:
                        ms.SpecType = StreamSpec.Pressure_and_Entropy;
                        break;
                    }
                });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Flash Specification"));
                s.CreateAndAddTextBoxRow(container2, nf, "Temperature (" + su.temperature + ")", cv.ConvertFromSI(su.temperature, ms.Phases[0].Properties.temperature.GetValueOrDefault()),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.temperature = cv.ConvertToSI(su.temperature, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Temperature"));
                s.CreateAndAddTextBoxRow(container2, nf, "Pressure (" + su.pressure + ")", cv.ConvertFromSI(su.pressure, ms.Phases[0].Properties.pressure.GetValueOrDefault()),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.pressure = cv.ConvertToSI(su.pressure, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Pressure"));
                s.CreateAndAddTextBoxRow(container2, nf, "Specific Enthalpy (" + su.enthalpy + ")", cv.ConvertFromSI(su.enthalpy, ms.Phases[0].Properties.enthalpy.GetValueOrDefault()),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.enthalpy = cv.ConvertToSI(su.enthalpy, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Specific Enthalpy"));
                s.CreateAndAddTextBoxRow(container2, nf, "Specific Entropy (" + su.entropy + ")", cv.ConvertFromSI(su.entropy, ms.Phases[0].Properties.entropy.GetValueOrDefault()),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.entropy = cv.ConvertToSI(su.entropy, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Specific Entropy"));

                s.CreateAndAddTextBoxRow(container2, nf, "Vapor Phase Mole Fraction (spec)", ms.Phases[2].Properties.molarfraction.GetValueOrDefault(),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[2].Properties.molarfraction = arg3.Text.ToString().ParseExpressionToDouble();
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });

                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Vapor Phase Mole Fraction (spec)"));

                s.CreateAndAddLabelRow(container2, "Flow Specification");

                var txtW = s.CreateAndAddTextBoxRow(container2, nf, "Mass Flow (" + su.massflow + ")", cv.ConvertFromSI(su.massflow, ms.Phases[0].Properties.massflow.GetValueOrDefault()),
                                                    (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.volumetric_flow = null;
                        ms.Phases[0].Properties.molarflow       = null;
                        ms.Phases[0].Properties.massflow        = cv.ConvertToSI(su.massflow, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Mass Flow"));
                var txtQ = s.CreateAndAddTextBoxRow(container2, nf, "Molar Flow (" + su.molarflow + ")", cv.ConvertFromSI(su.molarflow, ms.Phases[0].Properties.molarflow.GetValueOrDefault()),
                                                    (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.massflow        = null;
                        ms.Phases[0].Properties.volumetric_flow = null;
                        ms.Phases[0].Properties.molarflow       = cv.ConvertToSI(su.molarflow, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Molar Flow"));
                s.CreateAndAddTextBoxRow(container2, nf, "Volumetric Flow (" + su.volumetricFlow + ")", cv.ConvertFromSI(su.volumetricFlow, ms.Phases[0].Properties.volumetric_flow.GetValueOrDefault()),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.massflow        = null;
                        ms.Phases[0].Properties.molarflow       = null;
                        ms.Phases[0].Properties.volumetric_flow = cv.ConvertToSI(su.volumetricFlow, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Volumetric Flow"));

                s.CreateAndAddLabelRow(container2, "Mixture Composition");

                s.CreateAndAddDescriptionRow(container2, "Composition changes will only be committed after clicking on the 'Accept' button.");

                DropDown spinner1 = s.CreateAndAddDropDownRow(container2, "Amount Basis", StringResources.mscompinputtype().ToList(), 0, null);

                var tblist = new List <TextBox>();

                foreach (var comp in ms.Phases[0].Compounds)
                {
                    var tbox = s.CreateAndAddTextBoxRow(container2, nf, comp.Key, comp.Value.MoleFraction.GetValueOrDefault(),
                                                        (TextBox arg3, EventArgs ev) => { });
                    tbox.Tag = comp.Key;
                    tblist.Add(tbox);
                }

                spinner1.SelectedIndexChanged += (sender, e) =>
                {
                    var W = ms.Phases[0].Properties.massflow.GetValueOrDefault();
                    var Q = ms.Phases[0].Properties.molarflow.GetValueOrDefault();
                    switch (spinner1.SelectedIndex)
                    {
                    case 0:
                        foreach (var etext in tblist)
                        {
                            etext.Text = ms.Phases[0].Compounds[(String)etext.Tag].MoleFraction.GetValueOrDefault().ToString(nff);
                        }
                        break;

                    case 1:
                        foreach (var etext in tblist)
                        {
                            etext.Text = ms.Phases[0].Compounds[(String)etext.Tag].MassFraction.GetValueOrDefault().ToString(nff);
                        }
                        break;

                    case 2:
                        foreach (var etext in tblist)
                        {
                            etext.Text = (ms.Phases[0].Compounds[(String)etext.Tag].MoleFraction.GetValueOrDefault() * Q).ConvertFromSI(su.molarflow).ToString(nff);
                        }
                        break;

                    case 3:
                        foreach (var etext in tblist)
                        {
                            etext.Text = (ms.Phases[0].Compounds[(String)etext.Tag].MassFraction.GetValueOrDefault() * W).ConvertFromSI(su.massflow).ToString(nff);
                        }
                        break;
                    }
                };

                Double total = 0.0f;

                var btnNormalize = new Button {
                    Text = "Normalize"
                };
                btnNormalize.Font = new Font(SystemFont.Default, s.GetEditorFontSize());

                btnNormalize.Click += (sender, e) =>
                {
                    total = 0.0f;
                    foreach (var etext in tblist)
                    {
                        if (Double.TryParse(etext.Text.ToString(), out val))
                        {
                            etext.TextColor = (SystemColors.ControlText);
                            total          += Double.Parse(etext.Text.ToString());
                        }
                        else
                        {
                            etext.TextColor = (Colors.Red);
                            //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                        }
                    }
                    foreach (var etext in tblist)
                    {
                        if (Double.TryParse(etext.Text.ToString(), out val))
                        {
                            etext.Text = (Double.Parse(etext.Text.ToString()) / total).ToString(nff);
                        }
                    }
                };

                var btnEqualize = new Button {
                    Text = "Equalize"
                };
                btnEqualize.Font = new Font(SystemFont.Default, s.GetEditorFontSize());

                btnEqualize.Click += (sender, e) =>
                {
                    foreach (var etext in tblist)
                    {
                        etext.Text = (1.0 / tblist.Count).ToString(nff);
                    }
                };

                var btnClear = new Button {
                    Text = "Clear"
                };
                btnClear.Font = new Font(SystemFont.Default, s.GetEditorFontSize());

                btnClear.Click += (sender, e) =>
                {
                    foreach (var etext in tblist)
                    {
                        etext.Text = 0.0f.ToString(nff);
                    }
                };

                var btnAccept = new Button {
                    Text = "Accept/Update"
                };
                btnAccept.Font = new Font(SystemFont.Default, s.GetEditorFontSize());

                btnAccept.Click += (sender, e) =>
                {
                    Double W, Q, mtotal = 0.0f, mmtotal = 0.0f;

                    total = 0.0f;

                    switch (spinner1.SelectedIndex)
                    {
                    case 0:

                        btnNormalize.PerformClick();
                        foreach (var etext in tblist)
                        {
                            if (Double.TryParse(etext.Text.ToString(), out val))
                            {
                                MatStream.Phases[0].Compounds[(String)etext.Tag].MoleFraction = Double.Parse(etext.Text.ToString());
                            }
                            else
                            {
                                //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                            }
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            mtotal += comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight;
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            comp.MassFraction = comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight / mtotal;
                        }

                        break;

                    case 1:

                        btnNormalize.PerformClick();
                        foreach (var etext in tblist)
                        {
                            if (Double.TryParse(etext.Text.ToString(), out val))
                            {
                                MatStream.Phases[0].Compounds[(String)etext.Tag].MassFraction = Double.Parse(etext.Text.ToString());
                            }
                            else
                            {
                                //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                            }
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            mmtotal += comp.MassFraction.GetValueOrDefault() / comp.ConstantProperties.Molar_Weight;
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            comp.MoleFraction = comp.MassFraction.GetValueOrDefault() / comp.ConstantProperties.Molar_Weight / mmtotal;
                        }

                        break;

                    case 2:

                        total = 0;
                        foreach (var etext in tblist)
                        {
                            if (Double.TryParse(etext.Text.ToString(), out val))
                            {
                                total += Double.Parse(etext.Text.ToString());
                            }
                            else
                            {
                                //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                            }
                        }

                        Q = cv.ConvertToSI(su.molarflow, total);
                        foreach (var etext in tblist)
                        {
                            MatStream.Phases[0].Compounds[(String)etext.Tag].MoleFraction = Double.Parse(etext.Text.ToString()) / total;
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            mtotal += comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight;
                        }

                        W = 0;
                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            comp.MassFraction = comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight / mtotal;
                            W += comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight / 1000 * Q;
                        }

                        MatStream.Phases[0].Properties.molarflow = Q;
                        MatStream.Phases[0].Properties.massflow  = W;

                        txtQ.Text = cv.ConvertFromSI(su.molarflow, Q).ToString(nf);

                        break;

                    case 3:

                        total = 0;
                        foreach (var etext in tblist)
                        {
                            if (Double.TryParse(etext.Text.ToString(), out val))
                            {
                                total += Double.Parse(etext.Text.ToString());
                            }
                            else
                            {
                                //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                            }
                        }

                        W = cv.ConvertToSI(su.massflow, total);
                        foreach (var etext in tblist)
                        {
                            MatStream.Phases[0].Compounds[(String)etext.Tag].MassFraction = Double.Parse(etext.Text.ToString()) / total;
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            mmtotal += comp.MassFraction.GetValueOrDefault() / comp.ConstantProperties.Molar_Weight;
                        }

                        Q = 0;
                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            comp.MoleFraction = comp.MassFraction.GetValueOrDefault() / comp.ConstantProperties.Molar_Weight / mmtotal;
                            Q += comp.MassFraction.GetValueOrDefault() * W / comp.ConstantProperties.Molar_Weight * 1000;
                        }

                        MatStream.Phases[0].Properties.molarflow = Q;
                        MatStream.Phases[0].Properties.massflow  = W;

                        txtW.Text = cv.ConvertFromSI(su.massflow, W).ToString(nf);

                        break;
                    }

                    if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                    {
                        ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                    }
                };

                s.CreateAndAddControlRow(container2, btnAccept);
                s.CreateAndAddControlRow(container2, btnNormalize);
                s.CreateAndAddControlRow(container2, btnEqualize);
                s.CreateAndAddControlRow(container2, btnClear);

                s.CreateAndAddEmptySpace(container2);
                s.CreateAndAddEmptySpace(container2);
                s.CreateAndAddEmptySpace(container2);
                s.CreateAndAddEmptySpace(container2);

                if (ms.GraphicObject.InputConnectors[0].IsAttached &&
                    ms.GraphicObject.InputConnectors[0].AttachedConnector.AttachedFrom.ObjectType != ObjectType.OT_Recycle)
                {
                    container2.Enabled = false;
                }

                break;
            }
        }
Exemple #20
0
        void Init()
        {
            //page1
            var page1 = new DynamicLayout();

            _gridViewInstalled = new GridView();
            _gridViewInstalled.ColumnHeaderClick += _gridViewInstalled_ColumnHeaderClick;
            _gridViewInstalled.Columns.Add(new GridColumn()
            {
                DataCell   = new CheckBoxCell("Checked"),
                HeaderText = StrRes.GetString("StrChecked", "Checked"),
                Editable   = true
            });
            _gridViewInstalled.Columns.Add(new GridColumn()
            {
                ID         = "Name",
                DataCell   = new TextBoxCell("Name"),
                HeaderText = StrRes.GetString("StrName", "Name"),
                Sortable   = true,
                AutoSize   = false,
                Width      = 150
            });
            _gridViewInstalled.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("Author"),
                HeaderText = StrRes.GetString("StrAuthor", "Author"),
                AutoSize   = false,
                Width      = 100
            });
            _gridViewInstalled.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("InstalledVersion"),
                HeaderText = StrRes.GetString("StrInstalledVersion", "InstalledVersion"),
                AutoSize   = false,
                Width      = 150
            });
            _gridViewInstalled.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("FileName"),
                HeaderText = StrRes.GetString("StrFileName", "FileName"),
                AutoSize   = false,
                Width      = 150
            });
            _gridViewInstalled.SelectionChanged += _gridViewInstalled_SelectionChanged;
            _textAreatInstalledDes = new TextArea();
            _buttonRemove          = new Button {
                Text = StrRes.GetString("StrRemove", "Remove")
            };
            _buttonRemove.Click += _buttonRemove_Click;
            page1.Add(_gridViewInstalled, true, true);
            page1.Add(_textAreatInstalledDes, true, false);
            page1.AddSeparateRow(null, _buttonRemove);

            //page2
            var page2 = new DynamicLayout();

            _gridViewAvailable = new GridView();
            _gridViewAvailable.ColumnHeaderClick += _gridViewAvailable_ColumnHeaderClick;
            _gridViewAvailable.Columns.Add(new GridColumn()
            {
                DataCell   = new CheckBoxCell("Checked"),
                HeaderText = StrRes.GetString("StrChecked", "Checked"),
                Editable   = true
            });
            _gridViewAvailable.Columns.Add(new GridColumn()
            {
                ID         = "Name",
                DataCell   = new TextBoxCell("Name"),
                HeaderText = StrRes.GetString("StrName", "Name"),
                Sortable   = true,
                AutoSize   = false,
                Width      = 150
            });
            _gridViewAvailable.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("Author"),
                HeaderText = StrRes.GetString("StrAuthor", "Author"),
                AutoSize   = false,
                Width      = 100
            });
            _gridViewAvailable.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("AvailableVersion"),
                HeaderText = StrRes.GetString("StrAvailableVersion", "AvailableVersion"),
                AutoSize   = false,
                Width      = 150
            });
            _gridViewAvailable.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("RequiredVersion"),
                HeaderText = StrRes.GetString("StrRequiredVersion", "RequiredVersion"),
                AutoSize   = false,
                Width      = 150
            });
            _gridViewAvailable.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("CanInstall"),
                HeaderText = StrRes.GetString("StrCanInstall", "CanInstall"),
                AutoSize   = false,
                Width      = 100
            });
            _gridViewAvailable.SelectionChanged += _gridViewAvailable_SelectionChanged;
            _textAreatAvailableDes = new TextArea();
            _buttonRefresh         = new Button {
                Text = StrRes.GetString("StrRefresh", "Refresh")
            };
            _buttonRefresh.Click += _buttonRefresh_Click;
            _buttonInstall        = new Button {
                Text = StrRes.GetString("StrInstall", "Install")
            };
            _buttonInstall.Click += _buttonInstall_Click;
            page2.Add(_gridViewAvailable, true, true);
            page2.Add(_textAreatAvailableDes, true, false);
            page2.AddSeparateRow(null, _buttonRefresh, _buttonInstall);

            //page3
            var page3 = new DynamicLayout();

            _gridViewUpdatable = new GridView();
            _gridViewUpdatable.ColumnHeaderClick += _gridViewUpdatable_ColumnHeaderClick;
            _gridViewUpdatable.Columns.Add(new GridColumn()
            {
                DataCell   = new CheckBoxCell("Checked"),
                HeaderText = StrRes.GetString("StrChecked", "Checked"),
                Editable   = true
            });
            _gridViewUpdatable.Columns.Add(new GridColumn()
            {
                ID         = "Name",
                DataCell   = new TextBoxCell("Name"),
                HeaderText = StrRes.GetString("StrName", "Name"),
                Sortable   = true,
                AutoSize   = false,
                Width      = 150
            });
            _gridViewUpdatable.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("Author"),
                HeaderText = StrRes.GetString("StrAuthor", "Author"),
                AutoSize   = false,
                Width      = 100
            });
            _gridViewUpdatable.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("InstalledVersion"),
                HeaderText = StrRes.GetString("StrInstalledVersion", "InstalledVersion"),
                AutoSize   = false,
                Width      = 150
            });
            _gridViewUpdatable.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("AvailableVersion"),
                HeaderText = StrRes.GetString("StrAvailableVersion", "AvailableVersion"),
                AutoSize   = false,
                Width      = 150
            });
            _gridViewUpdatable.Columns.Add(new GridColumn()
            {
                DataCell   = new TextBoxCell("CanUpdate"),
                HeaderText = StrRes.GetString("StrCanUpdate", "CanUpdate"),
                AutoSize   = false,
                Width      = 100
            });
            _gridViewUpdatable.SelectionChanged += _gridViewUpdatable_SelectionChanged;
            _textAreatUpdatesDes = new TextArea();
            _buttonUpdate        = new Button {
                Text = StrRes.GetString("StrUpdate", "Update")
            };
            _buttonUpdate.Click += _buttonUpdate_Click;
            page3.Add(_gridViewUpdatable, true, true);
            page3.Add(_textAreatUpdatesDes, true, false);
            page3.AddSeparateRow(null, _buttonUpdate);

            //_tabPageInstalled
            _tabPageInstalled = new TabPage {
                Text = StrRes.GetString("StrInstalled", "Installed")
            };
            _tabPageInstalled.Content = page1;

            //_tabPageAvailable
            _tabPageAvailable = new TabPage {
                Text = StrRes.GetString("StrAvailable", "Available")
            };
            _tabPageAvailable.Content = page2;

            //_tabPageUpdatable
            _tabPageUpdatable = new TabPage {
                Text = StrRes.GetString("StrUpdatable", "Updatable")
            };
            _tabPageUpdatable.Content = page3;

            //_tabControl
            _tabControl = new TabControl();
            _tabControl.Pages.Add(_tabPageInstalled);
            _tabControl.Pages.Add(_tabPageAvailable);
            _tabControl.Pages.Add(_tabPageUpdatable);
            _tabControl.SelectedIndexChanged += _tabControl_SelectedIndexChanged;

            //_buttonSetting
            _buttonSetting = new Button {
                Text = StrRes.GetString("StrSetting", "Setting")
            };
            _buttonSetting.Click += _buttonSetting_Click;

            //_buttonClose
            _buttonClose = new Button {
                Text = StrRes.GetString("StrClose", "Close")
            };
            _buttonClose.Click += _buttonClose_Click;

            //_labelMsg
            _labelMsg = new Label
            {
                TextColor = Colors.Red,
                Text      =
                    StrRes.GetString("StrYourOperationWillTakeEffectWhenTheProgramStartNextTime",
                                     "Your operation will take effect when the program start next time.")
            };
            _labelMsg.Visible = false;

            var layout = new DynamicLayout {
                Padding = new Padding(5, 5), Spacing = new Size(5, 5)
            };

            layout.Add(_tabControl, true, true);
            layout.AddSeparateRow(_buttonSetting, _labelMsg, null, _buttonClose);

            Content = layout;
            Size    = new Size(610, 430);
            Title   = "PluginManager";
            Icon    = Application.Instance.MainForm.Icon;
        }
Exemple #21
0
        private DynamicLayout ConstructStatusPanel()
        {
            // Processing label
            var processingLabel = new Label();

            void UpdatingProcessingLabel(object sender, BackgroundProcessorEventArgs args)
            {
                Application.Instance.AsyncInvoke(() =>
                {
                    bool finished = args.CurrentScheduledItems == 0;
                    int logCount  = logs.Count;
                    // The log count check is to prevent a log count of 0 being shown when logs are being loaded and
                    // log processing catches up with searching for logs.
                    processingLabel.Text = finished && logCount > 0
                                                ? $"{logCount} logs found."
                                                : $"Processing logs {args.TotalProcessedItems}/{args.TotalScheduledItems}...";
                });
            }

            LogDataProcessor.Processed   += UpdatingProcessingLabel;
            LogDataProcessor.Scheduled   += UpdatingProcessingLabel;
            LogDataProcessor.Unscheduled += UpdatingProcessingLabel;
            LogCollectionsRecreated      += (sender, args) => processingLabel.Text = $"{logs.Count} logs found.";
            LogSearchStarted             += (sender, args) => processingLabel.Text = "Finding logs...";

            // Upload state label
            var uploadLabel = new Label();

            void UpdateUploadLabel(object sender, BackgroundProcessorEventArgs args)
            {
                Application.Instance.AsyncInvoke(() =>
                {
                    bool finished    = args.CurrentScheduledItems == 0;
                    uploadLabel.Text = finished
                                                ? ""
                                                : $"Uploading {args.TotalProcessedItems}/{args.TotalScheduledItems}...";
                });
            }

            UploadProcessor.Processed   += UpdateUploadLabel;
            UploadProcessor.Scheduled   += UpdateUploadLabel;
            UploadProcessor.Unscheduled += UpdateUploadLabel;

            // API state label
            var apiLabel = new Label();

            void UpdateApiLabel(object sender, BackgroundProcessorEventArgs args)
            {
                Application.Instance.AsyncInvoke(() =>
                {
                    bool finished = args.CurrentScheduledItems == 0;
                    apiLabel.Text = finished ? "" : $"GW2 API {args.TotalProcessedItems}/{args.TotalScheduledItems}";
                });
            }

            ApiProcessor.Processed   += UpdateApiLabel;
            ApiProcessor.Scheduled   += UpdateApiLabel;
            ApiProcessor.Unscheduled += UpdateApiLabel;

            // Layout of the status bar
            var layout = new DynamicLayout();

            layout.BeginHorizontal();
            {
                layout.Add(processingLabel, xscale: true);
                layout.Add(uploadLabel, xscale: true);
                layout.Add(apiLabel, xscale: true);
            }
            layout.EndHorizontal();

            return(layout);
        }
Exemple #22
0
        public MainForm()
        {
            _service = new GreetingService();

            Title      = "EtoPlayground";
            ClientSize = new Size(348, 80);

            var nameBox = new TextBox {
                PlaceholderText = "Your name"
            };

            nameBox.Bind(c => c.Text, _service, m => m.Name);

            var greetingField = new Label {
                Text = "Waiting"
            };

            greetingField.Bind(c => c.Text, _service, m => m.Greeting);

            var upperButton = new Button {
                Text = "Upper"
            };

            upperButton.Click += (sender, e) => _service.ChangeNameUpper();
            var notifyButton = new Button {
                Text = "Notify"
            };

            notifyButton.Click += (sender, e) => _service.Notify();

            var layout = new DynamicLayout {
                Padding = new Padding(10)
            };

            layout.BeginVertical();
            layout.BeginHorizontal();
            layout.Add(nameBox, true);
            layout.Add(upperButton);
            layout.EndHorizontal();
            layout.BeginHorizontal();
            layout.Add(greetingField, true);
            layout.Add(notifyButton);
            layout.EndHorizontal();
            layout.EndVertical();
            Content = layout;

            var quitCommand = new Command {
                MenuText = "Quit",
                Shortcut = Application.Instance.CommonModifier | Keys.Q
            };

            quitCommand.Executed += (sender, e) => Application.Instance.Quit();

            var aboutCommand = new Command {
                MenuText = "About..."
            };

            aboutCommand.Executed += (sender, e) => MessageBox.Show(this, "About my app...");

            // create menu
            Menu = new MenuBar {
                Items =
                {
                    // File submenu
                    new ButtonMenuItem {
                        Text = "&File", Items ={           }
                    },
                },
                ApplicationItems =
                {
                    // application (OS X) or file menu (others)
                    new ButtonMenuItem {
                        Text = "&Preferences..."
                    },
                },
                QuitItem  = quitCommand,
                AboutItem = aboutCommand
            };
        }
Exemple #23
0
        public ManagerForm(LogCache logCache, ApiData apiData)
        {
            LogCache = logCache ?? throw new ArgumentNullException(nameof(logCache));
            ApiData  = apiData ?? throw new ArgumentNullException(nameof(apiData));

            // Background processors
            var dpsReportUploader = new DpsReportUploader();

            UploadProcessor  = new UploadProcessor(dpsReportUploader, LogCache);
            ApiProcessor     = new ApiProcessor(ApiData, new Gw2Client());
            LogDataProcessor = new LogDataProcessor(LogCache, ApiProcessor, LogAnalytics);
            LogNameProvider  = new TranslatedLogNameProvider(GameLanguage.English);

            Filters = new LogFilters(new SettingsFilters());
            Filters.PropertyChanged += (sender, args) => logsFiltered.Refresh();

            if (Settings.UseGW2Api)
            {
                ApiProcessor.StartBackgroundTask();
            }

            Settings.UseGW2ApiChanged += (sender, args) =>
            {
                if (Settings.UseGW2Api)
                {
                    ApiProcessor.StartBackgroundTask();
                }
                else
                {
                    ApiProcessor.StopBackgroundTask();
                }
            };

            Settings.DpsReportDomainChanged += (sender, args) => { dpsReportUploader.Domain = Settings.DpsReportDomain; };

            // Form layout
            Icon       = Resources.GetProgramIcon();
            Title      = "arcdps Log Manager";
            ClientSize = new Size(1300, 768);
            var formLayout = new DynamicLayout();

            Content = formLayout;

            Menu = ConstructMenuBar();

            formLayout.BeginVertical(new Padding(5), yscale: false);
            {
                formLayout.Add(ConstructMainSplitter(), yscale: true);
                formLayout.Add(ConstructStatusPanel());
            }
            formLayout.EndVertical();

            // Event handlers
            ApiProcessor.Processed += (sender, args) =>
            {
                bool last = args.CurrentScheduledItems == 0;

                if (last)
                {
                    ApiData.SaveDataToFile();
                }
            };

            Settings.LogRootPathChanged += (sender, args) => Application.Instance.Invoke(ReloadLogs);

            Shown   += (sender, args) => ReloadLogs();
            Closing += (sender, args) =>
            {
                if (LogCache?.ChangedSinceLastSave ?? false)
                {
                    LogCache?.SaveToFile();
                }

                ApiData?.SaveDataToFile();
            };
            LogCollectionsRecreated += (sender, args) =>
            {
                logsFiltered.Filter = Filters.FilterLog;
                logsFiltered.Refresh();
            };
            LogSearchFinished += (sender, args) =>
            {
                var updates = LogDataUpdater.GetUpdates(logs).ToList();
                if (updates.Count > 0)
                {
                    new UpdateDialog(LogDataProcessor, updates).ShowModal(this);
                }
            };

            // Collection initialization
            RecreateLogCollections(new ObservableCollection <LogData>(logs));
        }
Exemple #24
0
        void Initialize()
        {
            var su  = MatStream.GetFlowsheet().FlowsheetOptions.SelectedUnitSystem;
            var nf  = MatStream.GetFlowsheet().FlowsheetOptions.NumberFormat;
            var nff = MatStream.GetFlowsheet().FlowsheetOptions.FractionNumberFormat;

            var container2 = new DynamicLayout();

            s.CreateAndAddLabelRow(container, "Material Stream Property Editor");

            s.CreateAndAddDescriptionRow(container, "Except for compound amounts, property values are updated/stored as they are changed/edited.");

            if ((Host.Items.Where(x => x.Name.Contains(MatStream.GraphicObject.Tag)).Count() > 0))
            {
                var ctn = new DynamicLayout();
                ctn.BackgroundColor = Colors.LightGrey;
                s.CreateAndAddLabelRow(ctn, "Inspector Reports");
                s.CreateAndAddLabelAndButtonRow(ctn, "An Inspector Report is ready for viewing.", "View Report", null, (btn, e) =>
                {
                    var f = s.GetDefaultEditorForm("Inspector Report for '" + MatStream.GraphicObject.Tag + "'", 1024, 768, Window2_Eto.GetInspectorWindow(MatStream), false);
                    f.Show();
                });
                container.Add(ctn);
            }

            s.CreateAndAddLabelRow(container, "Material Stream Details");

            s.CreateAndAddTwoLabelsRow(container, "Status", MatStream.GraphicObject.Active ? "Active" : "Inactive");

            s.CreateAndAddStringEditorRow(container, "Name", MatStream.GraphicObject.Tag, (TextBox arg3, EventArgs ev) =>
            {
                MatStream.GraphicObject.Tag = arg3.Text;
                MatStream.GetFlowsheet().UpdateInterface();
            }, () => {
                MatStream.GetFlowsheet().UpdateOpenEditForms();
            });

            s.CreateAndAddDropDownRow(container, "Compound Amount Basis",
                                      new List <string>()
            {
                "Molar Fractions", "Mass Fractions", "Volumetric Fractions", "Molar Flows", "Mass Flows", "Volumetric Flows", "Default"
            },
                                      (int)MatStream.FloatingTableAmountBasis, (sender, e) =>
            {
                MatStream.FloatingTableAmountBasis = (DWSIM.Interfaces.Enums.CompositionBasis)sender.SelectedIndex;
            });
            s.CreateAndAddDescriptionRow(container, "Select the basis to display compound amounts in floating tables, if enabled.");

            s.CreateAndAddLabelRow(container, "Property Package");

            var proppacks = MatStream.GetFlowsheet().PropertyPackages.Values.Select((x) => x.Tag).ToList();

            if (proppacks.Count == 0)
            {
                MatStream.GetFlowsheet().ShowMessage("Error: please add at least one Property Package before continuing.", IFlowsheet.MessageType.GeneralError);
            }
            else
            {
                var selectedpp = MatStream.PropertyPackage.Tag;
                s.CreateAndAddDropDownRow(container, "Property Package", proppacks, proppacks.IndexOf(selectedpp), (DropDown arg1, EventArgs ev) =>
                {
                    if (proppacks.Count > 0)
                    {
                        MatStream.PropertyPackage = (PropertyPackage)MatStream.GetFlowsheet().PropertyPackages.Values.Where((x) => x.Tag == proppacks[arg1.SelectedIndex]).FirstOrDefault();
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
            }

            container.Add(container2);

            s.CreateAndAddLabelRow(container2, "State Specification");

            switch (MatStream.GraphicObject.ObjectType)
            {
            case ObjectType.MaterialStream:
                var    ms       = MatStream;
                int    position = 0;
                Double val;
                switch (ms.SpecType)
                {
                case StreamSpec.Temperature_and_Pressure:
                    position = 0;
                    break;

                case StreamSpec.Temperature_and_VaporFraction:
                    position = 1;
                    break;

                case StreamSpec.Pressure_and_VaporFraction:
                    position = 2;
                    break;

                case StreamSpec.Pressure_and_Enthalpy:
                    position = 3;
                    break;

                case StreamSpec.Pressure_and_Entropy:
                    position = 4;
                    break;
                }

                s.CreateAndAddDropDownRow(container2, "Specified Variables", StringResources.flash_spec().ToList(), position, (DropDown arg3, EventArgs ev) =>
                {
                    switch (arg3.SelectedIndex)
                    {
                    case 0:
                        ms.SpecType = StreamSpec.Temperature_and_Pressure;
                        break;

                    case 1:
                        ms.SpecType = StreamSpec.Temperature_and_VaporFraction;
                        break;

                    case 2:
                        ms.SpecType = StreamSpec.Pressure_and_VaporFraction;
                        break;

                    case 3:
                        ms.SpecType = StreamSpec.Pressure_and_Enthalpy;
                        break;

                    case 4:
                        ms.SpecType = StreamSpec.Pressure_and_Entropy;
                        break;
                    }
                });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Flash Specification"));
                s.CreateAndAddTextBoxRow(container2, nf, "Temperature (" + su.temperature + ")", cv.ConvertFromSI(su.temperature, ms.Phases[0].Properties.temperature.GetValueOrDefault()),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.temperature = cv.ConvertToSI(su.temperature, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Temperature"));
                var txtP = s.CreateAndAddTextBoxRow(container2, nf, "Pressure (" + su.pressure + ")", cv.ConvertFromSI(su.pressure, ms.Phases[0].Properties.pressure.GetValueOrDefault()),
                                                    (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.pressure = cv.ConvertToSI(su.pressure, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Pressure"));
                s.CreateAndAddTextBoxRow(container2, nf, "Specific Enthalpy (" + su.enthalpy + ")", cv.ConvertFromSI(su.enthalpy, ms.Phases[0].Properties.enthalpy.GetValueOrDefault()),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.enthalpy = cv.ConvertToSI(su.enthalpy, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Specific Enthalpy"));
                s.CreateAndAddTextBoxRow(container2, nf, "Specific Entropy (" + su.entropy + ")", cv.ConvertFromSI(su.entropy, ms.Phases[0].Properties.entropy.GetValueOrDefault()),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.entropy = cv.ConvertToSI(su.entropy, arg3.Text.ToString().ParseExpressionToDouble());
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Specific Entropy"));

                s.CreateAndAddTextBoxRow(container2, nf, "Vapor Phase Mole Fraction (spec)", ms.Phases[2].Properties.molarfraction.GetValueOrDefault(),
                                         (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[2].Properties.molarfraction = arg3.Text.ToString().ParseExpressionToDouble();
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });

                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Vapor Phase Mole Fraction (spec)"));

                s.CreateAndAddLabelRow(container2, "Flow Specification");

                var txtW = s.CreateAndAddTextBoxRow(container2, nf, "Mass Flow (" + su.massflow + ")", cv.ConvertFromSI(su.massflow, ms.Phases[0].Properties.massflow.GetValueOrDefault()),
                                                    (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.volumetric_flow = null;
                        ms.Phases[0].Properties.molarflow       = null;
                        ms.Phases[0].Properties.massflow        = cv.ConvertToSI(su.massflow, arg3.Text.ToString().ParseExpressionToDouble());
                        ms.DefinedFlow = FlowSpec.Mass;
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Mass Flow"));
                var txtQ = s.CreateAndAddTextBoxRow(container2, nf, "Molar Flow (" + su.molarflow + ")", cv.ConvertFromSI(su.molarflow, ms.Phases[0].Properties.molarflow.GetValueOrDefault()),
                                                    (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.massflow        = null;
                        ms.Phases[0].Properties.volumetric_flow = null;
                        ms.Phases[0].Properties.molarflow       = cv.ConvertToSI(su.molarflow, arg3.Text.ToString().ParseExpressionToDouble());
                        ms.DefinedFlow = FlowSpec.Mole;
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Molar Flow"));
                var txtV = s.CreateAndAddTextBoxRow(container2, nf, "Volumetric Flow (" + su.volumetricFlow + ")", cv.ConvertFromSI(su.volumetricFlow, ms.Phases[0].Properties.volumetric_flow.GetValueOrDefault()),
                                                    (TextBox arg3, EventArgs ev) =>
                {
                    if (arg3.Text.IsValidDoubleExpression())
                    {
                        arg3.TextColor = (SystemColors.ControlText);
                        ms.Phases[0].Properties.massflow        = null;
                        ms.Phases[0].Properties.molarflow       = null;
                        ms.Phases[0].Properties.volumetric_flow = cv.ConvertToSI(su.volumetricFlow, arg3.Text.ToString().ParseExpressionToDouble());
                        ms.DefinedFlow = FlowSpec.Volumetric;
                    }
                    else
                    {
                        arg3.TextColor = (Colors.Red);
                    }
                }, () => { if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                           {
                               ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                           }
                    });
                s.CreateAndAddDescriptionRow(container2, ms.GetPropertyDescription("Volumetric Flow"));

                switch (MatStream.DefinedFlow)
                {
                case FlowSpec.Mass:
                    txtW.BackgroundColor = Colors.LightBlue;
                    txtW.ToolTip         = "Defined by the user";
                    txtQ.ToolTip         = "Calculated";
                    txtV.ToolTip         = "Calculated";
                    break;

                case FlowSpec.Mole:
                    txtQ.BackgroundColor = Colors.LightBlue;
                    txtW.ToolTip         = "Calculated";
                    txtQ.ToolTip         = "Defined by the user";
                    txtV.ToolTip         = "Calculated";
                    break;

                case FlowSpec.Volumetric:
                    txtV.BackgroundColor = Colors.LightBlue;
                    txtW.ToolTip         = "Calculated";
                    txtQ.ToolTip         = "Calculated";
                    txtV.ToolTip         = "Defined by the user";
                    break;
                }

                s.CreateAndAddLabelRow(container2, "Mixture Composition");

                s.CreateAndAddDescriptionRow(container2, "Composition changes will only be committed after clicking on the 'Accept' button.");

                DropDown spinner1 = s.CreateAndAddDropDownRow(container2, "Amount Basis", StringResources.mscompinputtype().ToList(), 0, null);

                var tblist = new List <TextBox>();

                foreach (var comp0 in ms.GetFlowsheet().SelectedCompounds.Values)
                {
                    var comp = ms.Phases[0].Compounds[comp0.Name];
                    var tbox = s.CreateAndAddTextBoxRow(container2, nf, comp.Name, comp.MoleFraction.GetValueOrDefault(),
                                                        (TextBox arg3, EventArgs ev) => { });
                    tbox.Tag = comp.Name;
                    tblist.Add(tbox);
                }

                spinner1.SelectedIndexChanged += (sender, e) =>
                {
                    var W = ms.Phases[0].Properties.massflow.GetValueOrDefault();
                    var Q = ms.Phases[0].Properties.molarflow.GetValueOrDefault();
                    switch (spinner1.SelectedIndex)
                    {
                    case 0:
                        foreach (var etext in tblist)
                        {
                            etext.Text = ms.Phases[0].Compounds[(String)etext.Tag].MoleFraction.GetValueOrDefault().ToString(nff);
                        }
                        break;

                    case 1:
                        foreach (var etext in tblist)
                        {
                            etext.Text = ms.Phases[0].Compounds[(String)etext.Tag].MassFraction.GetValueOrDefault().ToString(nff);
                        }
                        break;

                    case 2:
                        foreach (var etext in tblist)
                        {
                            etext.Text = (ms.Phases[0].Compounds[(String)etext.Tag].MoleFraction.GetValueOrDefault() * Q).ConvertFromSI(su.molarflow).ToString(nff);
                        }
                        break;

                    case 3:
                        foreach (var etext in tblist)
                        {
                            etext.Text = (ms.Phases[0].Compounds[(String)etext.Tag].MassFraction.GetValueOrDefault() * W).ConvertFromSI(su.massflow).ToString(nff);
                        }
                        break;
                    }
                };

                Double total = 0.0f;

                var btnNormalize = new Button {
                    Text = "Normalize"
                };
                btnNormalize.Font = new Font(SystemFont.Default, s.GetEditorFontSize());

                btnNormalize.Click += (sender, e) =>
                {
                    total = 0.0f;
                    foreach (var etext in tblist)
                    {
                        if (Double.TryParse(etext.Text.ToString(), out val))
                        {
                            etext.TextColor = (SystemColors.ControlText);
                            total          += Double.Parse(etext.Text.ToString());
                        }
                        else
                        {
                            etext.TextColor = (Colors.Red);
                            //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                        }
                    }
                    foreach (var etext in tblist)
                    {
                        if (Double.TryParse(etext.Text.ToString(), out val))
                        {
                            etext.Text = (Double.Parse(etext.Text.ToString()) / total).ToString(nff);
                        }
                    }
                };

                var btnEqualize = new Button {
                    Text = "Equalize"
                };
                btnEqualize.Font = new Font(SystemFont.Default, s.GetEditorFontSize());

                btnEqualize.Click += (sender, e) =>
                {
                    foreach (var etext in tblist)
                    {
                        etext.Text = (1.0 / tblist.Count).ToString(nff);
                    }
                };

                var btnClear = new Button {
                    Text = "Clear"
                };
                btnClear.Font = new Font(SystemFont.Default, s.GetEditorFontSize());

                btnClear.Click += (sender, e) =>
                {
                    foreach (var etext in tblist)
                    {
                        etext.Text = 0.0f.ToString(nff);
                    }
                };

                var btnAccept = new Button {
                    Text = "Accept/Update"
                };
                btnAccept.Font = new Font(SystemFont.Default, s.GetEditorFontSize());

                btnAccept.Click += (sender, e) =>
                {
                    Double W, Q, mtotal = 0.0f, mmtotal = 0.0f;

                    total = 0.0f;

                    switch (spinner1.SelectedIndex)
                    {
                    case 0:

                        btnNormalize.PerformClick();
                        foreach (var etext in tblist)
                        {
                            if (Double.TryParse(etext.Text.ToString(), out val))
                            {
                                MatStream.Phases[0].Compounds[(String)etext.Tag].MoleFraction = Double.Parse(etext.Text.ToString());
                            }
                            else
                            {
                                //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                            }
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            mtotal += comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight;
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            comp.MassFraction = comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight / mtotal;
                        }

                        break;

                    case 1:

                        btnNormalize.PerformClick();
                        foreach (var etext in tblist)
                        {
                            if (Double.TryParse(etext.Text.ToString(), out val))
                            {
                                MatStream.Phases[0].Compounds[(String)etext.Tag].MassFraction = Double.Parse(etext.Text.ToString());
                            }
                            else
                            {
                                //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                            }
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            mmtotal += comp.MassFraction.GetValueOrDefault() / comp.ConstantProperties.Molar_Weight;
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            comp.MoleFraction = comp.MassFraction.GetValueOrDefault() / comp.ConstantProperties.Molar_Weight / mmtotal;
                        }

                        break;

                    case 2:

                        total = 0;
                        foreach (var etext in tblist)
                        {
                            if (Double.TryParse(etext.Text.ToString(), out val))
                            {
                                total += Double.Parse(etext.Text.ToString());
                            }
                            else
                            {
                                //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                            }
                        }

                        Q = cv.ConvertToSI(su.molarflow, total);
                        foreach (var etext in tblist)
                        {
                            MatStream.Phases[0].Compounds[(String)etext.Tag].MoleFraction = Double.Parse(etext.Text.ToString()) / total;
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            mtotal += comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight;
                        }

                        W = 0;
                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            comp.MassFraction = comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight / mtotal;
                            W += comp.MoleFraction.GetValueOrDefault() * comp.ConstantProperties.Molar_Weight / 1000 * Q;
                        }

                        MatStream.Phases[0].Properties.molarflow = Q;
                        MatStream.Phases[0].Properties.massflow  = W;

                        txtQ.Text = cv.ConvertFromSI(su.molarflow, Q).ToString(nf);

                        break;

                    case 3:

                        total = 0;
                        foreach (var etext in tblist)
                        {
                            if (Double.TryParse(etext.Text.ToString(), out val))
                            {
                                total += Double.Parse(etext.Text.ToString());
                            }
                            else
                            {
                                //Toast.MakeText(this.Context, "Error parsing '" + etext.Text + "' for " + (String)etext.Tag + ", not a valid number. Please input a valid number and try again.", ToastLength.Short).Show();
                            }
                        }

                        W = cv.ConvertToSI(su.massflow, total);
                        foreach (var etext in tblist)
                        {
                            MatStream.Phases[0].Compounds[(String)etext.Tag].MassFraction = Double.Parse(etext.Text.ToString()) / total;
                        }

                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            mmtotal += comp.MassFraction.GetValueOrDefault() / comp.ConstantProperties.Molar_Weight;
                        }

                        Q = 0;
                        foreach (var comp in MatStream.Phases[0].Compounds.Values)
                        {
                            comp.MoleFraction = comp.MassFraction.GetValueOrDefault() / comp.ConstantProperties.Molar_Weight / mmtotal;
                            Q += comp.MassFraction.GetValueOrDefault() * W / comp.ConstantProperties.Molar_Weight * 1000;
                        }

                        MatStream.Phases[0].Properties.molarflow = Q;
                        MatStream.Phases[0].Properties.massflow  = W;

                        txtW.Text = cv.ConvertFromSI(su.massflow, W).ToString(nf);

                        break;
                    }

                    if (GlobalSettings.Settings.CallSolverOnEditorPropertyChanged)
                    {
                        ((Shared.Flowsheet)MatStream.GetFlowsheet()).HighLevelSolve.Invoke();
                    }
                };

                s.CreateAndAddLabelAndTwoButtonsRow(container2, "Copy/Paste", "Copy Data", null, "Paste Data", null,
                                                    (btn1, e1) =>
                {
                    string data = "";
                    foreach (var tb in tblist)
                    {
                        data += tb.Tag.ToString() + "\t" + tb.Text + "\n";
                    }
                    Clipboard.Instance.Text = data;
                },
                                                    (btn2, e2) =>
                {
                    if (Clipboard.Instance.ContainsText)
                    {
                        var textdata = Clipboard.Instance.Text;
                        var data     = textdata.Split(new[] { '\n', '\t', ' ' });
                        int i        = 0;
                        foreach (var line in data)
                        {
                            if (line != " " && line != "\t" && line != "\n" && i < tblist.Count)
                            {
                                tblist[i].Text = line.Trim();
                                i += 1;
                            }
                        }
                    }
                });

                s.CreateAndAddControlRow(container2, btnAccept);
                s.CreateAndAddControlRow(container2, btnNormalize);
                s.CreateAndAddControlRow(container2, btnEqualize);
                s.CreateAndAddControlRow(container2, btnClear);

                s.CreateAndAddEmptySpace(container2);
                s.CreateAndAddEmptySpace(container2);
                s.CreateAndAddEmptySpace(container2);
                s.CreateAndAddEmptySpace(container2);

                if (ms.GraphicObject.InputConnectors[0].IsAttached &&
                    ms.GraphicObject.InputConnectors[0].AttachedConnector.AttachedFrom.ObjectType != ObjectType.OT_Recycle)
                {
                    if (!ms.GetFlowsheet().DynamicMode)
                    {
                        container2.Enabled = false;
                    }
                }
                break;
            }
        }
Exemple #25
0
        Control LeftPane()
        {
            var layout = new DynamicLayout();

            layout.DefaultPadding = Padding.Empty;
            layout.BeginVertical();
            layout.BeginHorizontal();
            layout.Add(new Label {
                Text = "Label", VerticalAlign = VerticalAlign.Middle
            });
            layout.AddAutoSized(new Button {
                Text = "Button Control"
            }, centered: true);
            layout.Add(new ImageView {
                Image = icon1, Size = new Size(64, 64)
            });
            layout.Add(null);
            layout.EndHorizontal();
            layout.EndBeginVertical();
            layout.AddRow(new CheckBox {
                Text = "Check Box (/w three state)", ThreeState = true, Checked = null
            }, RadioButtons(), null);
            layout.EndBeginVertical();
            layout.AddRow(new TextBox {
                Text = "Text Box", Size = new Size(150, -1)
            }, new PasswordBox {
                Text = "Password Box", Size = new Size(150, -1)
            }, null);
            layout.EndBeginVertical();
            layout.AddRow(ComboBox(), new DateTimePicker {
                Value = DateTime.Now
            }, null);
            layout.EndBeginVertical();
            layout.AddRow(new NumericUpDown {
                Value = 50
            }, null);
            layout.EndBeginVertical();
            layout.AddRow(ListBox(), new TextArea {
                Text = "Text Area", Size = new Size(150, 50)
            }, null);
            layout.EndBeginVertical();
            layout.AddRow(new Slider {
                Value = 50, TickFrequency = 10
            });
            layout.EndBeginVertical();
            layout.AddRow(new ProgressBar {
                Value = 25
            });
            layout.EndBeginVertical();
            layout.AddRow(new GroupBox {
                Text = "Group Box", Content = new Label {
                    Text = "I'm in a group box"
                }
            });

            layout.EndBeginVertical();


            layout.EndVertical();
            layout.Add(null);

            return(layout);
        }
        public KitchenSinkSection()
        {
            var layout = new DynamicLayout(this);

            layout.Add(Tabs());
        }
Exemple #27
0
        void InitializeComponent()
        {
            //exception handling

            Application.Instance.UnhandledException += (sender, e) =>
            {
                new DWSIM.UI.Desktop.Editors.UnhandledExceptionView((Exception)e.ExceptionObject).ShowModalAsync();
            };

            string imgprefix = "DWSIM.UI.Forms.Resources.Icons.";

            Title = "DWSIMLauncher".Localize();

            switch (GlobalSettings.Settings.RunningPlatform())
            {
            case GlobalSettings.Settings.Platform.Windows:
                ClientSize = new Size(690, 420);
                break;

            case GlobalSettings.Settings.Platform.Linux:
                ClientSize = new Size(690, 370);
                break;

            case GlobalSettings.Settings.Platform.Mac:
                ClientSize = new Size(690, 350);
                break;
            }

            Icon = Eto.Drawing.Icon.FromResource(imgprefix + "DWSIM_ico.ico");

            var bgcolor = new Color(0.051f, 0.447f, 0.651f);

            Eto.Style.Add <Button>("main", button =>
            {
                button.BackgroundColor = bgcolor;
                button.Font            = new Font(FontFamilies.Sans, 12f, FontStyle.None);
                button.TextColor       = Colors.White;
                button.ImagePosition   = ButtonImagePosition.Left;
                button.Width           = 230;
            });

            Eto.Style.Add <Button>("donate", button =>
            {
                button.BackgroundColor = Colors.LightYellow;
                button.Font            = new Font(FontFamilies.Sans, 12f, FontStyle.None);
                button.TextColor       = bgcolor;
                button.ImagePosition   = ButtonImagePosition.Left;
                button.Width           = 230;
            });

            var btn1 = new Button()
            {
                Style = "main", Text = "OpenSavedFile".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "OpenFolder_100px.png"), 40, 40, ImageInterpolation.Default)
            };
            var btn2 = new Button()
            {
                Style = "main", Text = "NewSimulation".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "Workflow_100px.png"), 40, 40, ImageInterpolation.Default)
            };
            var btn3 = new Button()
            {
                Style = "main", Text = "NewCompound".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "Peptide_100px.png"), 40, 40, ImageInterpolation.Default)
            };
            var btn4 = new Button()
            {
                Style = "main", Text = "NewDataRegression".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "AreaChart_100px.png"), 40, 40, ImageInterpolation.Default)
            };
            var btn6 = new Button()
            {
                Style = "main", Text = "Help".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "Help_100px.png"), 40, 40, ImageInterpolation.Default)
            };
            var btn7 = new Button()
            {
                Style = "main", Text = "About".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "Info_100px.png"), 40, 40, ImageInterpolation.Default)
            };
            var btn8 = new Button()
            {
                Style = "donate", Text = "Donate ", Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "PayPal_100px.png"), 40, 40, ImageInterpolation.Default)
            };
            var btn9 = new Button()
            {
                Style = "main", Text = "Preferences".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "VerticalSettingsMixer_100px.png"), 40, 40, ImageInterpolation.Default)
            };

            btn9.Click += (sender, e) =>
            {
                new Forms.Forms.GeneralSettings().GetForm().Show();
            };

            btn6.Click += (sender, e) =>
            {
                Process.Start("http://dwsim.inforside.com.br/docs/crossplatform/help/");
            };

            btn1.Click += (sender, e) =>
            {
                var dialog = new OpenFileDialog();
                dialog.Title = "Open File".Localize();
                dialog.Filters.Add(new FileFilter("XML Simulation File".Localize(), new[] { ".dwxml", ".dwxmz" }));
                dialog.Filters.Add(new FileFilter("Mobile XML Simulation File (Android/iOS)", new[] { ".xml" }));
                dialog.MultiSelect        = false;
                dialog.CurrentFilterIndex = 0;
                if (dialog.ShowDialog(this) == DialogResult.Ok)
                {
                    LoadSimulation(dialog.FileName);
                }
            };

            btn2.Click += (sender, e) =>
            {
                var form = new Forms.Flowsheet();
                AddUserCompounds(form.FlowsheetObject);
                OpenForms   += 1;
                form.Closed += (sender2, e2) =>
                {
                    OpenForms -= 1;
                };
                form.newsim = true;
                form.Show();
            };

            btn7.Click += (sender, e) => new AboutBox().Show();
            btn8.Click += (sender, e) => Process.Start("http://sourceforge.net/p/dwsim/donate/");

            var stack = new StackLayout {
                Orientation = Orientation.Vertical, Spacing = 5
            };

            stack.Items.Add(btn1);
            stack.Items.Add(btn2);
            stack.Items.Add(btn9);
            stack.Items.Add(btn6);
            stack.Items.Add(btn7);
            stack.Items.Add(btn8);

            var tableright = new TableLayout();

            tableright.Padding = new Padding(5, 5, 5, 5);
            tableright.Spacing = new Size(10, 10);

            MostRecentList = new ListBox {
                BackgroundColor = bgcolor, Height = 330
            };
            SampleList = new ListBox {
                BackgroundColor = bgcolor, Height = 330
            };
            FoldersList = new ListBox {
                BackgroundColor = bgcolor, Height = 330
            };

            if (Application.Instance.Platform.IsGtk &&
                GlobalSettings.Settings.RunningPlatform() == GlobalSettings.Settings.Platform.Mac)
            {
                MostRecentList.TextColor = bgcolor;
                SampleList.TextColor     = bgcolor;
                FoldersList.TextColor    = bgcolor;
            }
            else
            {
                MostRecentList.TextColor = Colors.White;
                SampleList.TextColor     = Colors.White;
                FoldersList.TextColor    = Colors.White;
            }

            var invertedlist = new List <string>(GlobalSettings.Settings.MostRecentFiles);

            invertedlist.Reverse();

            foreach (var item in invertedlist)
            {
                if (File.Exists(item))
                {
                    MostRecentList.Items.Add(new ListItem {
                        Text = Path.GetFileName(item), Key = item
                    });
                }
            }

            var samplist = Directory.EnumerateFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "samples"), "*.dwxm*");

            foreach (var item in samplist)
            {
                if (File.Exists(item))
                {
                    SampleList.Items.Add(new ListItem {
                        Text = Path.GetFileName(item), Key = item
                    });
                }
            }

            foreach (String f in invertedlist)
            {
                if (Path.GetExtension(f).ToLower() != ".dwbcs")
                {
                    if (FoldersList.Items.Where((x) => x.Text == Path.GetDirectoryName(f)).Count() == 0)
                    {
                        FoldersList.Items.Add(new ListItem {
                            Text = Path.GetDirectoryName(f), Key = Path.GetDirectoryName(f)
                        });
                    }
                }
            }

            FoldersList.SelectedIndexChanged += (sender, e) =>
            {
                if (FoldersList.SelectedIndex >= 0)
                {
                    var dialog = new OpenFileDialog();
                    dialog.Title     = "Open File".Localize();
                    dialog.Directory = new Uri(FoldersList.SelectedKey);
                    dialog.Filters.Add(new FileFilter("XML Simulation File".Localize(), new[] { ".dwxml", ".dwxmz" }));
                    dialog.MultiSelect        = false;
                    dialog.CurrentFilterIndex = 0;
                    if (dialog.ShowDialog(this) == DialogResult.Ok)
                    {
                        LoadSimulation(dialog.FileName);
                    }
                }
            };

            MostRecentList.SelectedIndexChanged += (sender, e) =>
            {
                if (MostRecentList.SelectedIndex >= 0)
                {
                    LoadSimulation(MostRecentList.SelectedKey);
                    MostRecentList.SelectedIndex = -1;
                }
                ;
            };

            SampleList.SelectedIndexChanged += (sender, e) =>
            {
                if (SampleList.SelectedIndex >= 0)
                {
                    LoadSimulation(SampleList.SelectedKey);
                    MostRecentList.SelectedIndex = -1;
                }
                ;
            };

            var tabview = new TabControl();
            var tab1    = new TabPage(MostRecentList)
            {
                Text = "Recent Files"
            };;
            var tab2 = new TabPage(SampleList)
            {
                Text = "Samples"
            };;
            var tab3 = new TabPage(FoldersList)
            {
                Text = "Recent Folders"
            };;

            tabview.Pages.Add(tab1);
            tabview.Pages.Add(tab2);
            tabview.Pages.Add(tab3);

            tableright.Rows.Add(new TableRow(tabview));

            var tl = new DynamicLayout();

            tl.Add(new TableRow(stack, tableright));

            TableContainer = new TableLayout
            {
                Padding         = 10,
                Spacing         = new Size(5, 5),
                Rows            = { new TableRow(tl) },
                BackgroundColor = bgcolor,
            };

            Content = TableContainer;

            var quitCommand = new Command {
                MenuText = "Quit".Localize(), Shortcut = Application.Instance.CommonModifier | Keys.Q
            };

            quitCommand.Executed += (sender, e) => Application.Instance.Quit();

            var aboutCommand = new Command {
                MenuText = "About".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "information.png"))
            };

            aboutCommand.Executed += (sender, e) => new AboutBox().Show();

            var aitem1 = new ButtonMenuItem {
                Text = "Preferences".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "icons8-sorting_options.png"))
            };

            aitem1.Click += (sender, e) =>
            {
                new Forms.Forms.GeneralSettings().GetForm().Show();
            };

            var aitem2 = new ButtonMenuItem {
                Text = "Open Classic UI", Shortcut = Keys.Alt | Keys.C
            };

            aitem2.Click += (sender, e) =>
            {
                DWSIM.macOS.ClassicUILoader.Loader.Load();
            };

            var hitem1 = new ButtonMenuItem {
                Text = "Help".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "help_browser.png"))
            };

            hitem1.Click += (sender, e) =>
            {
                Process.Start("http://dwsim.inforside.com.br/docs/crossplatform/help/");
            };

            var hitem2 = new ButtonMenuItem {
                Text = "Support".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "help_browser.png"))
            };

            hitem2.Click += (sender, e) =>
            {
                Process.Start("http://dwsim.inforside.com.br/wiki/index.php?title=Support");
            };

            var hitem3 = new ButtonMenuItem {
                Text = "Report a Bug".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "help_browser.png"))
            };

            hitem3.Click += (sender, e) =>
            {
                Process.Start("https://sourceforge.net/p/dwsim/tickets/");
            };

            var hitem4 = new ButtonMenuItem {
                Text = "Go to DWSIM's Website".Localize(), Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "help_browser.png"))
            };

            hitem4.Click += (sender, e) =>
            {
                Process.Start("http://dwsim.inforside.com.br");
            };

            // create menu
            Menu = new MenuBar
            {
                ApplicationItems = { aitem1, aitem2 },
                QuitItem         = quitCommand,
                HelpItems        = { hitem1, hitem4, hitem2, hitem3 },
                AboutItem        = aboutCommand
            };

            Shown += MainForm_Shown;

            Closing += MainForm_Closing;

            //Plugins

            LoadPlugins();
        }
        public Dialog_ProgramType(ref HB.ModelProperties libSource, HB.ProgramTypeAbridged programType, bool lockedMode = false)
        {
            try
            {
                libSource.FillNulls();

                _vm = new ProgramTypeViewModel(this, ref libSource, programType);

                Title       = $"Program Type - {DialogHelper.PluginName}";
                WindowStyle = WindowStyle.Default;
                Width       = 450;
                this.Icon   = DialogHelper.HoneybeeIcon;


                //Generate ProgramType Panel

                var nameTbx = new TextBox();
                nameTbx.TextBinding.Bind(_vm, c => c.Name);

                var loadGroup = GenLoadsPanel(lockedMode);


                var locked = new CheckBox()
                {
                    Text = "Locked", Enabled = false
                };
                locked.Checked = lockedMode;

                var OkButton = new Button {
                    Text = "OK", Enabled = !lockedMode
                };
                OkButton.Click += (sender, e) => {
                    try
                    {
                        OkCommand.Execute(_vm.GetHBObject());
                    }
                    catch (Exception er)
                    {
                        MessageBox.Show(er.Message);
                        //throw;
                    }
                };

                AbortButton = new Button {
                    Text = "Cancel"
                };
                AbortButton.Click += (sender, e) => Close();

                // Json Data
                var hbData = new Button {
                    Text = "Schema Data"
                };
                hbData.Command = _vm.HBDataBtnClick;

                //Create layout
                var layout = new DynamicLayout()
                {
                    DefaultPadding = new Padding(5), DefaultSpacing = new Size(5, 5)
                };
                layout.BeginScrollable(BorderType.None);

                layout.AddRow("Name");
                layout.AddRow(nameTbx);
                layout.AddRow(loadGroup);
                layout.AddRow(null);
                layout.EndScrollable();
                layout.AddSeparateRow(locked, null, OkButton, AbortButton, null, hbData);
                layout.Add(null);
                //Create layout
                Content = layout;
            }
            catch (Exception e)
            {
                //throw e;
                Dialog_Message.Show(e.ToString());
            }
        }
        public ProjectWizardPageView(ProjectWizardPageModel model)
        {
            var content = new DynamicLayout
            {
                Spacing = new Size(10, 10)
            };

            if (model.SupportsAppName)
            {
                var nameBox = new TextBox();
                nameBox.TextBinding.BindDataContext((ProjectWizardPageModel m) => m.AppName);
                Application.Instance.AsyncInvoke(nameBox.Focus);

                var nameValid = new Label {
                    TextColor = Colors.Red
                };
                nameValid.BindDataContext(c => c.Visible, (ProjectWizardPageModel m) => m.AppNameInvalid);
                nameValid.BindDataContext(c => c.Text, (ProjectWizardPageModel m) => m.AppNameValidationText);


                content.BeginHorizontal();
                content.Add(new Label {
                    Text = (model.IsLibrary ? "Library" : "App") + " Name:", TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center
                });
                content.AddColumn(nameBox, nameValid);
                content.EndHorizontal();
            }
            else if (!string.IsNullOrEmpty(model.AppName))
            {
                var label = new Label {
                    Text = model.AppName, VerticalAlignment = VerticalAlignment.Center
                };
                content.AddRow(new Label {
                    Text = (model.IsLibrary ? "Library" : "App") + " Name:", TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center
                }, label);
            }

            if (model.SupportsSeparated)
            {
                var platformTypeList = new RadioButtonList
                {
                    Orientation = Orientation.Vertical,
                    Spacing     = new Size(0, 0),
                    Items       =
                    {
                        new ListItem {
                            Text = "Single Windows, Linux, and Mac desktop project", Key = "combined"
                        },
                        new ListItem {
                            Text = "Separate projects for each platform", Key = "separate"
                        }
                    }
                };
                platformTypeList.SelectedKeyBinding
                .Convert(v => v == "separate", v => v ? "separate" : "combined")
                .BindDataContext((ProjectWizardPageModel m) => m.Separate);
                content.AddRow(new Label {
                    Text = "Launcher:", TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center
                }, platformTypeList);
            }

            if (model.SupportsXamMac)
            {
                var cb = new CheckBox
                {
                    Text    = "Include Xamarin.Mac project",
                    ToolTip = "This enables you to bundle mono with your app so your users don't have to install it separately.  You can only compile this on a Mac"
                };
                cb.CheckedBinding.BindDataContext((ProjectWizardPageModel m) => m.IncludeXamMac);
                content.AddRow(new Panel(), cb);
            }

            /*
             * eventually select platforms to include?
             *
             * var platformCheckBoxes = new DynamicLayout();
             * platformCheckBoxes.BeginHorizontal();
             * platformCheckBoxes.Add(new CheckBox { Text = "Gtk2" });
             * platformCheckBoxes.Add(new CheckBox { Text = "Gtk3" });
             * platformCheckBoxes.EndBeginHorizontal();
             * platformCheckBoxes.Add(new CheckBox { Text = "WinForms" });
             * platformCheckBoxes.Add(new CheckBox { Text = "Wpf" });
             * platformCheckBoxes.Add(new CheckBox { Text = "Direct2D" });
             * platformCheckBoxes.EndBeginHorizontal();
             * platformCheckBoxes.Add(new CheckBox { Text = "Mac" });
             * platformCheckBoxes.Add(new CheckBox { Text = "XamMac" });
             * platformCheckBoxes.Add(new CheckBox { Text = "XamMac2" });
             * platformCheckBoxes.EndHorizontal();
             *
             * content.Rows.Add(new TableRow(new Label { Text = "Platforms:", TextAlignment = TextAlignment.Right }, platformCheckBoxes));
             * /**/

            if (model.SupportsProjectType)
            {
                var sharedCodeList = new RadioButtonList
                {
                    Orientation = Orientation.Vertical,
                    Spacing     = new Size(0, 0),
                };
                if (model.SupportsPCL)
                {
                    sharedCodeList.Items.Add(new ListItem {
                        Text = "Portable Class Library", Key = "pcl"
                    });
                    sharedCodeList.SelectedKeyBinding.Convert(v => v == "pcl", v => v ? "pcl" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UsePCL);
                }
                if (model.SupportsNetStandard)
                {
                    sharedCodeList.Items.Add(new ListItem {
                        Text = ".NET Standard", Key = "netstandard"
                    });
                    sharedCodeList.SelectedKeyBinding.Convert(v => v == "netstandard", v => v ? "netstandard" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseNetStandard);
                }
                if (model.SupportsSAL)
                {
                    sharedCodeList.Items.Add(new ListItem {
                        Text = "Shared Project", Key = "sal"
                    });
                    sharedCodeList.SelectedKeyBinding.Convert(v => v == "sal", v => v ? "sal" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseSAL);
                }

                sharedCodeList.Items.Add(new ListItem {
                    Text = "Full .NET", Key = "net"
                });
                sharedCodeList.SelectedKeyBinding.Convert(v => v == "net", v => v ? "net" : sharedCodeList.SelectedKey).BindDataContext((ProjectWizardPageModel m) => m.UseNET);

                content.AddRow(new Label {
                    Text = model.IsLibrary ? "Type:" : "Shared Code:", TextAlignment = TextAlignment.Right
                }, sharedCodeList);
            }

            if (model.SupportsPanelType)
            {
                var panelTypeList = new RadioButtonList
                {
                    Orientation = Orientation.Horizontal,
                    Spacing     = new Size(0, 0),
                };

                panelTypeList.Items.Add(new ListItem {
                    Text = "Code", Key = "code"
                });
                panelTypeList.SelectedKeyBinding.BindDataContext((ProjectWizardPageModel m) => m.Mode);

                if (model.SupportsXeto)
                {
                    panelTypeList.Items.Add(new ListItem {
                        Text = "Xaml", Key = "xaml"
                    });
                }
                if (model.SupportsJeto)
                {
                    panelTypeList.Items.Add(new ListItem {
                        Text = "Json", Key = "json"
                    });
                }
                if (model.SupportsCodePreview)
                {
                    panelTypeList.Items.Add(new ListItem {
                        Text = "Code Preview", Key = "preview"
                    });
                }

                content.AddRow(new Label {
                    Text = "Form:", TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center
                }, panelTypeList);
            }

            if (model.SupportsBase)
            {
                var baseTypeList = new RadioButtonList
                {
                    Orientation = Orientation.Horizontal,
                    Spacing     = new Size(0, 0),
                };

                baseTypeList.Items.Add(new ListItem {
                    Text = "Panel", Key = "Panel"
                });
                baseTypeList.Items.Add(new ListItem {
                    Text = "Dialog", Key = "Dialog"
                });
                baseTypeList.Items.Add(new ListItem {
                    Text = "Form", Key = "Form"
                });
                baseTypeList.SelectedKeyBinding.BindDataContext((ProjectWizardPageModel m) => m.Base);

                content.AddRow(new Label {
                    Text = "Base:", TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center
                }, baseTypeList);
            }

            var informationLabel = new Label();

            informationLabel.TextBinding.BindDataContext((ProjectWizardPageModel m) => m.Information);
            Information = informationLabel;

            Content     = content;
            DataContext = model;
        }
Exemple #30
0
        public ParticleSystemManager(uint documentSerialNumber)
        {
            _document_sn = documentSerialNumber;

            // set up grid vies
            _gV_ParticleSystems.ShowHeader = true;
            _model_list = RhinoFaceMePlugIn.Instance.FaceMeTable;

            // set up bindings for grid view
            _gV_ParticleSystems.DataContext = _model_list;
            _gV_ParticleSystems.DataStore   = _model_list.Conduits;
            _gV_ParticleSystems.SelectedItemBinding.BindDataContext((ParticleConduitListViewModel avm) =>
                                                                    avm.SelectedIndex);

            // set up events for grid view
            _gV_ParticleSystems.CellClick += On_CellClick;

            #region Grid Columns

            // name
            _gV_ParticleSystems.Columns.Add(new GridColumn
            {
                HeaderText = "Name",
                DataCell   = new TextBoxCell("Name"),
                Editable   = false,
            });

            // image
            _gV_ParticleSystems.Columns.Add(new GridColumn
            {
                HeaderText = "Image",
                DataCell   = new ImageViewCell {
                    Binding = Binding.Property <ParticleConduitModel, Image>(
                        l => new System.Drawing.Bitmap(l.Bitmap.GetThumbnailImage(50, 50, null, IntPtr.Zero)).ToEto())
                },
                Editable = true
            });

            // active
            _gV_ParticleSystems.Columns.Add(new GridColumn
            {
                HeaderText = "Active",
                DataCell   = new CheckBoxCell("IsActive"),
                Editable   = true,
            });

            // size
            _gV_ParticleSystems.Columns.Add(new GridColumn
            {
                HeaderText = "Size",
                DataCell   = new TextBoxCell("Size"),
                Editable   = true,
            });

            // color
            var bitmapSize = 12;
            _gV_ParticleSystems.Columns.Add(new GridColumn
            {
                DataCell = new ImageViewCell {
                    Binding = Binding.Property <ParticleConduitModel, Image>(l => new Bitmap(bitmapSize, bitmapSize, PixelFormat.Format24bppRgb, from index in Enumerable.Repeat(0, bitmapSize * bitmapSize) select l.Color.ToEto()))
                },
                HeaderText = "Color",
                Editable   = true
            });

            // alignment
            _gV_ParticleSystems.Columns.Add(new GridColumn
            {
                HeaderText = "Alignment",
                DataCell   = new AlignmentCell(),
                Editable   = true,
            });

            #endregion

            // write layout
            var layout = new DynamicLayout();
            layout.Padding = 10;
            layout.Spacing = new Size(5, 5);

            layout.Add(_gV_ParticleSystems);
            layout.Add(null);

            Content = layout;
        }