Exemple #1
0
 public void Close ()
 {
     if (Visible) {
         try {
             UnityEngine.Object.Destroy (popup.gameObject);
         } catch (NullReferenceException) {
             //FIXME: Nasty hack catching this. Dialog may have already been removed by other UI logic.
         }
         Visible = false;
         dialog = null;
         popup = null;
         Closed ();
         EventHandlerExtensions.Invoke (OnClose, this);
     }
 }
Exemple #2
0
 public void Open ()
 {
     if (!hasInit) {
         Init ();
         hasInit = true;
     }
     if (!Visible) {
         if (Skin == null)
             Skin = HighLogic.UISkin;
         Visible = true;
         Opened ();
         EventHandlerExtensions.Invoke (OnOpen, this);
         dialog = new MultiOptionDialog (Message, Title, Skin, Options.ToArray ());
         popup = PopupDialog.SpawnPopupDialog (new Vector2 (0.5f, 0.5f), new Vector2 (0.5f, 0.5f), dialog, true, HighLogic.UISkin);
     }
 }
Exemple #3
0
        void LaunchButton()
        {
            List<DialogOption> LaunchOptionsList = new List<DialogOption>();

            LaunchOptionsList.Add(new DialogOption("Proceed to Launch", InvokeLaunch));
            LaunchOptionsList.Add( new DialogOption("Simulate this Vessel", InvokeSimulation));
            LaunchOptionsList.Add(new DialogOption("Cancel Launch", null));

            // This is how you hide tooltips.
            EditorTooltip.Instance.HideToolTip();
            GameEvents.onTooltipDestroyRequested.Fire();

            // Lock inputs
            EditorLogic.fetch.Lock(true, true, true, "KCT_EDITOR_LAUNCH_A");
            InputLockManager.SetControlLock(ControlTypes.EDITOR_SOFT_LOCK, "KCT_EDITOR_LAUNCH_B");

            // Display the new launch prompt
            LaunchDialog = PopupDialog.SpawnPopupDialog(new MultiOptionDialog(null, null, Skin, LaunchOptionsList.ToArray()), false, Skin);
        }
Exemple #4
0
    private void _closeNetworkFail()
    {
        PopupDialog popupdialogNetork = (PopupDialog)GetNode("CanvasLayer/NetworkErrorMessage");

        popupdialogNetork.Hide();
    }
        public void Start()
        {
            //Checkers are identified by the type name and _version field name.
            FieldInfo[] fields =
                GetAllTypes()
                .Where(t => t.Name == "CompatibilityChecker")
                .Select(t => t.GetField("_version", BindingFlags.Static | BindingFlags.NonPublic))
                .Where(f => f != null)
                .Where(f => f.FieldType == typeof(int))
                .ToArray();

            //Let the latest version of the checker execute.
            if (_version != fields.Max(f => (int)f.GetValue(null)))
            {
                return;
            }

            Debug.Log(string.Format("[CompatibilityChecker] Running checker version {0} from '{1}'", _version, Assembly.GetExecutingAssembly().GetName().Name));

            //Other checkers will see this version and not run.
            //This accomplishes the same as an explicit "ran" flag with fewer moving parts.
            _version = int.MaxValue;

            //A mod is incompatible if its compatibility checker has an IsCompatible method which returns false.
            string[] incompatible =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsCompatible", Type.EmptyTypes))
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    //If a mod throws an exception from IsCompatible, it's not compatible.
                    Debug.LogWarning(string.Format("[CompatibilityChecker] Exception while invoking IsCompatible() from '{0}':\n\n{1}", m.DeclaringType.Assembly.GetName().Name, e));
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            //A mod is incompatible with Unity if its compatibility checker has an IsUnityCompatible method which returns false.
            string[] incompatibleUnity =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsUnityCompatible", Type.EmptyTypes))
                .Where(m => m != null)  //Mods without IsUnityCompatible() are assumed to be compatible.
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    //If a mod throws an exception from IsUnityCompatible, it's not compatible.
                    Debug.LogWarning(string.Format("[CompatibilityChecker] Exception while invoking IsUnityCompatible() from '{0}':\n\n{1}", m.DeclaringType.Assembly.GetName().Name, e));
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            Array.Sort(incompatible);
            Array.Sort(incompatibleUnity);

            string message = string.Empty;

            /*if (SixtyFourBitsMayHaveAChanceAtLife())
             *{
             *   message += "WARNING: You are using 64-bit KSP on Windows. This version of KSP is known to cause crashes. It's highly recommended that you use either 32-bit KSP on Windows or switch to Linux.";
             *}*/

            if (incompatible.Length > 0 || incompatibleUnity.Length > 0)
            {
                message += Localizer.Format("FARCompatCheckWarning");

                if (incompatible.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods detected: " + string.Join(", ", incompatible));
                    message += Localizer.Format("FARCompatCheckKSP", Versioning.version_major, Versioning.version_minor, Versioning.Revision);
                    message += string.Join("\n", incompatible);
                }

                if (incompatibleUnity.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods (Unity) detected: " + string.Join(", ", incompatibleUnity));
                    message += Localizer.Format("FARCompatCheckUnity", Application.unityVersion);
                    message += string.Join("\n", incompatibleUnity);
                }
            }

            if (incompatible.Length > 0 || incompatibleUnity.Length > 0)
            {
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "CompatibilityChecker", Localizer.Format("FARCompatCheckTitle"), message, Localizer.Format("FARGUIOKButton"), true, HighLogic.UISkin);
            }
        }
Exemple #6
0
        private void RemoveIssue(QuickIssue quickIssue)
        {
            if (!CMS.EffectivePrivileges.IssueTab.CanDelete || !CMS.EffectivePrivileges.AdminTab.CanModify || !quickIssue.IsActive)
            {
                return;
            }

            string message = String.Format("Delete Issue {0} - '{1}'  Issue?", quickIssue.Id, quickIssue.Name);
            var popupDialog = new PopupDialog(PopupDialogType.ConfirmDelete, message);

            popupDialog.Show();
            popupDialog.Closed +=
                (s2, e2) =>
                {
                    if (popupDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {
                        //DELETE
                        var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

                        cmsWebServiceClient.DeleteIssueCompleted +=
                            (s1, e1) =>
                            {
                                EventAggregator.GetEvent<PrismEvents.CloseTabPrismEvent>().Publish(quickIssue);
                            };

                        cmsWebServiceClient.DeleteIssueAsync(quickIssue.Id, CMS.User.Id);
                    }
                };
        }
        private void OkButtonHandler(object parameter)
        {
            if (CanExecuteAddButtonHandler(parameter))
            {
                if (AreAllValid() && PurchaseOrders.All(x => !x.HasErrors) && OtherAccruals.All(x => !x.HasErrors))
                {
                    var undeliveredPortionHigherThanAccrue = PurchaseOrders.Where(x => x.UndeliveredPortion.HasValue && x.AmountAccruedDecimal > x.UndeliveredPortion.Value).ToList();

                    if (undeliveredPortionHigherThanAccrue.Any())
                    {
                        StringBuilder errorMessage = new StringBuilder();
                        foreach (var purchaseOrderAccureModel in undeliveredPortionHigherThanAccrue)
                        {
                            errorMessage.Append(String.Format("Accrue {0:c} is more than Undelivered Proportion {1:c}.{2}", purchaseOrderAccureModel.AmountAccruedDecimal,
                                purchaseOrderAccureModel.UndeliveredPortion.Value, Environment.NewLine));
                        }

                        errorMessage.Append(Environment.NewLine);

                        errorMessage.Append("Click OK to accept or Cancel to modify.");

                        PopupDialog popupDialog = new PopupDialog(PopupDialogType.SaveComfirm, errorMessage.ToString(), "Warning", 700, 250);
                        popupDialog.Show();
                        popupDialog.Closed += (sender, args) =>
                        {
                            if (popupDialog.PopupDialogResult == PopupDialogResult.Ok)
                            {
                                Save();
                            }
                            else
                            {
                                foreach (var purchaseOrderAccureModel in undeliveredPortionHigherThanAccrue)
                                {
                                    purchaseOrderAccureModel.AddValidationError("Accrue", "Accrue is more than the Undelivered amount");
                                }
                            }
                        };

                    }
                    else
                    {
                        Save();
                    }
                }
                else
                {
                    var validationErrors = GetErrors();
                    if (validationErrors.Any())
                    {
                        View.ValidationPopup.Show(validationErrors);
                    }
                }
            }
        }
        private void AddExistingControlSystemComponentTypeAlarmProperty(NodeView nodeView)
        {
            var controlSystemEquipmentComponentTypeId = nodeView.Parent.Id;
            var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.GetControlSystemComponentTypeCompleted +=
                (s, e) =>
                {
                    var dialog = new AddEditExistingControlSystemComponentAlarmPropertyDialog(e.Result);
                    dialog.Show();

                    dialog.Closed += (s1, e1) =>
                    {
                        if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
                        {
                            EventHandler<SaveControlSystemComponentTypeAlarmPropertyCompletedEventArgs> addCompleted = null;
                            addCompleted = (s2, eventArgs) =>
                            {
                                var entityResult = eventArgs.Result.EntityResult;

                                if (eventArgs.Result.HasErrors)
                                {
                                    var popup = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(eventArgs.Result.ServerErrorMessages));
                                    popup.Show();
                                    return;
                                }

                                if (entityResult != null)
                                {
                                    var child = new NodeView(nodeView)
                                    {
                                        Id = entityResult.Id,
                                        Name = dialog.ControlSystemComponentTypeAlarmProperty.ControlSystemAlarmProperty.Name,
                                        Description = dialog.ControlSystemComponentTypeAlarmProperty.ControlSystemAlarmProperty.Description,
                                        Icon = "/CmsEquipmentDatabase;component/Images/Configuration.png",
                                        Type = NodeType.ControlSystemComponentTypeAlarmProperty,
                                        HasChildren = false,
                                        SortField = entityResult.Ordinal.ToString()
                                    };
                                    if (nodeView.ChildrenLoaded)
                                    {
                                        nodeView.Children.Add(child);
                                        nodeView.Sort();
                                    }
                                }

                                cmsWebServiceClient.SaveControlSystemComponentTypeAlarmPropertyCompleted -= addCompleted;
                            };
                            cmsWebServiceClient.SaveControlSystemComponentTypeAlarmPropertyCompleted += addCompleted;

                            var systemComponentTypeTuningProperty = new ControlSystemComponentTypeAlarmProperty
                            {
                                ComponentTypeId = controlSystemEquipmentComponentTypeId,
                                AlarmPropertyId = dialog.ControlSystemComponentTypeAlarmProperty.AlarmPropertyId,
                                Ordinal = dialog.ControlSystemComponentTypeAlarmProperty.Ordinal
                            };

                            cmsWebServiceClient.SaveControlSystemComponentTypeAlarmPropertyAsync(systemComponentTypeTuningProperty);
                        }
                    };
                };
            cmsWebServiceClient.GetControlSystemComponentTypeAsync(controlSystemEquipmentComponentTypeId);
        }
        private void DeleteReport(NodeView nodeView)
        {
            var message = string.Format("Delete Report {0} ?", nodeView.Name);
            var popupDialog = new PopupDialog(PopupDialogType.ConfirmDelete, message);
            popupDialog.Show();
            popupDialog.Closed +=
                (s, e) =>
                {
                    if (popupDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {
                        var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                        EventHandler<DeleteReportLinkCompletedEventArgs> deleteCompleted = null;
                        deleteCompleted = (s2, eventArgs) =>
                        {
                            var ds = eventArgs.Result;

                            if (!ds.HasErrors)
                            {
                                nodeView.Parent.Children.Remove(nodeView);
                                var existing = (from x in CMS.Cache.ReportLinks
                                                where x.Id == nodeView.Id
                                                select x).FirstOrDefault();
                                CMS.Cache.ReportLinks.Remove(existing);
                            }
                            else
                            {
                                var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(ds.ServerErrorMessages));
                                errorDialog.Show();
                            }

                            cmsWebServiceClient.DeleteReportLinkCompleted -= deleteCompleted;
                        };

                        cmsWebServiceClient.DeleteReportLinkCompleted += deleteCompleted;
                        cmsWebServiceClient.DeleteReportLinkAsync(nodeView.Id);
                    }
                };
        }
        private void OkButtonHander(object parameter)
        {
            if (CanExecuteOkButtonHandler(parameter))
            {
                if (AreAllValid())
                {
                    var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

                    cmsWebServiceClient.SaveIssueSubTypeCompleted += (s1, e1) =>
                    {
                        if (e1.Result.HasErrors)
                        {
                            var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(e1.Result.ServerErrorMessages));
                            errorDialog.Show();
                            return;
                        }

                        View.IssueSubType = e1.Result.EntityResult;
                        View.DialogResult = true;
                    };
                    cmsWebServiceClient.SaveIssueSubTypeAsync(mIssueSubType);
                }
            }
        }
Exemple #11
0
        public bool ElectionAndCheck()
        {
            #region Type election

            // TODO : Move the old version check in a process that call Update.

            // Check for old version and MMSarbianExt
            IEnumerable <AssemblyLoader.LoadedAssembly> oldMM =
                AssemblyLoader.loadedAssemblies.Where(
                    a => a.assembly.GetName().Name == Assembly.GetExecutingAssembly().GetName().Name)
                .Where(a => a.assembly.GetName().Version.CompareTo(new System.Version(1, 5, 0)) == -1);
            IEnumerable <AssemblyLoader.LoadedAssembly> oldAssemblies =
                oldMM.Concat(AssemblyLoader.loadedAssemblies.Where(a => a.assembly.GetName().Name == "MMSarbianExt"));
            if (oldAssemblies.Any())
            {
                IEnumerable <string> badPaths =
                    oldAssemblies.Select(a => a.path)
                    .Select(
                        p =>
                        Uri.UnescapeDataString(
                            new Uri(Path.GetFullPath(KSPUtil.ApplicationRootPath)).MakeRelativeUri(new Uri(p))
                            .ToString()
                            .Replace('/', Path.DirectorySeparatorChar)));
                string status =
                    "You have old versions of Module Manager (older than 1.5) or MMSarbianExt.\nYou will need to remove them for Module Manager and the mods using it to work\nExit KSP and delete those files :\n" +
                    String.Join("\n", badPaths.ToArray());
                PopupDialog.SpawnPopupDialog(new Vector2(0f, 1f), new Vector2(0f, 1f), "ModuleManagerOldVersions", "Old versions of Module Manager", status, "OK", false, UISkinManager.defaultSkin);
                Log("Old version of Module Manager present. Stopping");
                return(false);
            }


            //PopupDialog.SpawnPopupDialog(new Vector2(0.1f, 1f), new Vector2(0.2f, 1f), "Test of the dialog", "Stuff", "OK", false, UISkinManager.defaultSkin);

            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            IEnumerable <AssemblyLoader.LoadedAssembly> eligible = from a in AssemblyLoader.loadedAssemblies
                                                                   let ass = a.assembly
                                                                             where ass.GetName().Name == currentAssembly.GetName().Name
                                                                             orderby ass.GetName().Version descending, a.path ascending
            select a;

            // Elect the newest loaded version of MM to process all patch files.
            // If there is a newer version loaded then don't do anything
            // If there is a same version but earlier in the list, don't do anything either.
            if (eligible.First().assembly != currentAssembly)
            {
                //loaded = true;
                Log("version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location +
                    " lost the election");
                Destroy(gameObject);
                return(false);
            }
            string candidates = "";
            foreach (AssemblyLoader.LoadedAssembly a in eligible)
            {
                if (currentAssembly.Location != a.path)
                {
                    candidates += "Version " + a.assembly.GetName().Version + " " + a.path + " " + "\n";
                }
            }
            if (candidates.Length > 0)
            {
                Log("version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location +
                    " won the election against\n" + candidates);
            }

            #endregion Type election

            return(true);
        }
Exemple #12
0
        /* Not required anymore. At least
         * public static bool IsABadIdea()
         * {
         *  return (intPtr.ToInt64() == long.MaxValue) && (Environment.OSVersion.Platform == PlatformID.Win32NT);
         * }
         */

        private IEnumerator DataBaseReloadWithMM(bool dump = false)
        {
            QualitySettings.vSyncCount  = 0;
            Application.targetFrameRate = -1;

            patchRunner = new MMPatchRunner(new ModLogger("ModuleManager", new UnityLogger(Debug.unityLogger)));

            float totalLoadWeight = GameDatabase.Instance.LoadWeight() + PartLoader.Instance.LoadWeight();
            bool  startedReload   = false;

            UISkinDef skinDef           = HighLogic.UISkin;
            UIStyle   centeredTextStyle = new UIStyle(skinDef.label)
            {
                alignment = TextAnchor.UpperCenter
            };

            PopupDialog reloadingDialog = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                                       new Vector2(0.5f, 0.5f),
                                                                       new MultiOptionDialog(
                                                                           "ModuleManagerReloading",
                                                                           "",
                                                                           "ModuleManager - Reloading Database",
                                                                           skinDef,
                                                                           new Rect(0.5f, 0.5f, 600f, 60f),
                                                                           new DialogGUIFlexibleSpace(),
                                                                           new DialogGUIVerticalLayout(
                                                                               new DialogGUIFlexibleSpace(),
                                                                               new DialogGUILabel(delegate()
            {
                float progressFraction;
                if (!startedReload)
                {
                    progressFraction = 0f;
                }
                else if (!GameDatabase.Instance.IsReady())
                {
                    progressFraction  = GameDatabase.Instance.ProgressFraction() * GameDatabase.Instance.LoadWeight();
                    progressFraction /= totalLoadWeight;
                }
                else if (!PartLoader.Instance.IsReady())
                {
                    progressFraction  = GameDatabase.Instance.LoadWeight() + (PartLoader.Instance.ProgressFraction() * GameDatabase.Instance.LoadWeight());
                    progressFraction /= totalLoadWeight;
                }
                else
                {
                    progressFraction = 1f;
                }

                return($"Overall progress: {progressFraction:P0}");
            }, centeredTextStyle, expandW : true),
                                                                               new DialogGUILabel(delegate()
            {
                if (!startedReload)
                {
                    return("Starting");
                }
                else if (!GameDatabase.Instance.IsReady())
                {
                    return(GameDatabase.Instance.ProgressTitle());
                }
                else if (!PostPatchLoader.Instance.IsReady())
                {
                    return(PostPatchLoader.Instance.ProgressTitle());
                }
                else if (!PartLoader.Instance.IsReady())
                {
                    return(PartLoader.Instance.ProgressTitle());
                }
                else
                {
                    return("");
                }
            }),
                                                                               new DialogGUISpace(5f),
                                                                               new DialogGUILabel(() => patchRunner.Status)
                                                                               )
                                                                           ),
                                                                       false,
                                                                       skinDef);

            yield return(null);

            GameDatabase.Instance.Recompile = true;
            GameDatabase.Instance.StartLoad();

            startedReload = true;

            yield return(null);

            StartCoroutine(patchRunner.Run());

            // wait for it to finish
            while (!GameDatabase.Instance.IsReady())
            {
                yield return(null);
            }

            PostPatchLoader.Instance.StartLoad();

            while (!PostPatchLoader.Instance.IsReady())
            {
                yield return(null);
            }

            if (dump)
            {
                OutputAllConfigs();
            }

            PartLoader.Instance.StartLoad();

            while (!PartLoader.Instance.IsReady())
            {
                yield return(null);
            }

            // Needs more work.
            //ConfigNode game = HighLogic.CurrentGame.config.GetNode("GAME");

            //if (game != null && ResearchAndDevelopment.Instance != null)
            //{
            //    ScreenMessages.PostScreenMessage("GAME found");
            //    ConfigNode scenario = game.GetNodes("SCENARIO").FirstOrDefault((ConfigNode n) => n.name == "ResearchAndDevelopment");
            //    if (scenario != null)
            //    {
            //        ScreenMessages.PostScreenMessage("SCENARIO found");
            //        ResearchAndDevelopment.Instance.OnLoad(scenario);
            //    }
            //}

            QualitySettings.vSyncCount  = GameSettings.SYNC_VBL;
            Application.targetFrameRate = GameSettings.FRAMERATE_LIMIT;

            reloadingDialog.Dismiss();
        }
Exemple #13
0
        internal void Update()
        {
            if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F11) &&
                (HighLogic.LoadedScene == GameScenes.SPACECENTER || HighLogic.LoadedScene == GameScenes.MAINMENU) &&
                !inRnDCenter)
            {
                if (menu == null)
                {
                    menu = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                        new Vector2(0.5f, 0.5f),
                                                        new MultiOptionDialog(
                                                            "ModuleManagerMenu",
                                                            "",
                                                            "ModuleManager",
                                                            HighLogic.UISkin,
                                                            new Rect(0.5f, 0.5f, 150f, 60f),
                                                            new DialogGUIFlexibleSpace(),
                                                            new DialogGUIVerticalLayout(
                                                                new DialogGUIFlexibleSpace(),
                                                                new DialogGUIButton("Reload Database",
                                                                                    delegate
                    {
                        MMPatchLoader.keepPartDB = false;
                        StartCoroutine(DataBaseReloadWithMM());
                    }, 140.0f, 30.0f, true),
                                                                new DialogGUIButton("Quick Reload Database",
                                                                                    delegate
                    {
                        MMPatchLoader.keepPartDB = true;
                        StartCoroutine(DataBaseReloadWithMM());
                    }, 140.0f, 30.0f, true),
                                                                new DialogGUIButton("Dump Database to Files",
                                                                                    delegate
                    {
                        StartCoroutine(DataBaseReloadWithMM(true));
                    }, 140.0f, 30.0f, true),
                                                                new DialogGUIButton("Close", () => { }, 140.0f, 30.0f, true)
                                                                )),
                                                        false,
                                                        HighLogic.UISkin);
                }
                else
                {
                    menu.Dismiss();
                    menu = null;
                }
            }

            if (totalTime.IsRunning && HighLogic.LoadedScene == GameScenes.MAINMENU)
            {
                totalTime.Stop();
                Log("Total loading Time = " + ((float)totalTime.ElapsedMilliseconds / 1000).ToString("F3") + "s");

                Application.runInBackground = GameSettings.SIMULATE_IN_BACKGROUND;
                QualitySettings.vSyncCount  = GameSettings.SYNC_VBL;
                Application.targetFrameRate = GameSettings.FRAMERATE_LIMIT;
            }

            float offsetY = textPos;
            float h;

            if (patchRunner != null)
            {
                if (warning)
                {
                    h       = warning.text.Length > 0 ? warning.textBounds.size.y : 0;
                    offsetY = offsetY + h;
                    warning.rectTransform.localPosition = new Vector3(0, offsetY);
                }

                if (status)
                {
                    status.text = patchRunner.Status;
                    h           = status.text.Length > 0 ? status.textBounds.size.y : 0;
                    offsetY     = offsetY + h;
                    status.transform.localPosition = new Vector3(0, offsetY);
                }

                if (errors)
                {
                    errors.text = patchRunner.Errors;
                    h           = errors.text.Length > 0 ? errors.textBounds.size.y : 0;
                    offsetY     = offsetY + h;
                    errors.transform.localPosition = new Vector3(0, offsetY);
                }
            }
        }
Exemple #14
0
        public static void DelayedStart()
        {
            if (Utilities.CurrentGameIsMission())
            {
                return;
            }

            KCTDebug.Log("DelayedStart start");
            if (PresetManager.Instance?.ActivePreset == null || !PresetManager.Instance.ActivePreset.GeneralSettings.Enabled)
            {
                return;
            }

            if (KCT_GUI.IsPrimarilyDisabled)
            {
                return;
            }

            //The following should only be executed when fully enabled for the save

            if (KCTGameStates.ActiveKSC == null)
            {
                Utilities.SetActiveKSCToRSS();
            }

            KCTDebug.Log("Checking vessels for missing parts.");
            //check that all parts are valid in all ships. If not, warn the user and disable that vessel (once that code is written)
            if (!KCTGameStates.VesselErrorAlerted)
            {
                var erroredVessels = new List <BuildListVessel>();
                foreach (KSCItem KSC in KCTGameStates.KSCs) //this is faster on subsequent scene changes
                {
                    foreach (BuildListVessel blv in KSC.VABList)
                    {
                        if (!blv.AllPartsValid)
                        {
                            KCTDebug.Log(blv.ShipName + " contains invalid parts!");
                            erroredVessels.Add(blv);
                        }
                    }
                    foreach (BuildListVessel blv in KSC.VABWarehouse)
                    {
                        if (!blv.AllPartsValid)
                        {
                            KCTDebug.Log(blv.ShipName + " contains invalid parts!");
                            erroredVessels.Add(blv);
                        }
                    }
                    foreach (BuildListVessel blv in KSC.SPHList)
                    {
                        if (!blv.AllPartsValid)
                        {
                            KCTDebug.Log(blv.ShipName + " contains invalid parts!");
                            erroredVessels.Add(blv);
                        }
                    }
                    foreach (BuildListVessel blv in KSC.SPHWarehouse)
                    {
                        if (!blv.AllPartsValid)
                        {
                            KCTDebug.Log(blv.ShipName + " contains invalid parts!");
                            erroredVessels.Add(blv);
                        }
                    }
                }
                if (erroredVessels.Count > 0)
                {
                    PopUpVesselError(erroredVessels);
                }
                KCTGameStates.VesselErrorAlerted = true;
            }

            if (HighLogic.LoadedSceneIsEditor && KCTGameStates.EditorShipEditingMode)
            {
                KCTDebug.Log($"Editing {KCTGameStates.EditedVessel.ShipName}");
                EditorLogic.fetch.shipNameField.text = KCTGameStates.EditedVessel.ShipName;
            }

            if (HighLogic.LoadedScene == GameScenes.SPACECENTER)
            {
                KCTDebug.Log("SP Start");
                if (!KCT_GUI.IsPrimarilyDisabled)
                {
                    if (ToolbarManager.ToolbarAvailable && KCTGameStates.Settings.PreferBlizzyToolbar)
                    {
                        if (KCTGameStates.ShowWindows[0])
                        {
                            KCT_GUI.ToggleVisibility(true);
                        }
                        else
                        {
                            if (KCTEvents.Instance != null && KCTGameStates.ToolbarControl != null)
                            {
                                if (KCTGameStates.ShowWindows[0])
                                {
                                    KCT_GUI.ToggleVisibility(true);
                                }
                            }
                        }
                    }
                    KCT_GUI.ResetBLWindow();
                }
                else
                {
                    KCT_GUI.GUIStates.ShowBuildList = false;
                    KCTGameStates.ShowWindows[0]    = false;
                }
                KCTDebug.Log("SP UI done");

                if (KCTGameStates.IsFirstStart)
                {
                    KCTDebug.Log("Showing first start.");
                    KCTGameStates.IsFirstStart     = false;
                    KCT_GUI.GUIStates.ShowFirstRun = true;

                    //initialize the proper launchpad
                    KCTGameStates.ActiveKSC.ActiveLPInstance.level = Utilities.GetBuildingUpgradeLevel(SpaceCenterFacility.LaunchPad);
                }

                KCTDebug.Log("SP switch starting");
                KCTGameStates.ActiveKSC.SwitchLaunchPad(KCTGameStates.ActiveKSC.ActiveLaunchPadID);
                KCTDebug.Log("SP switch done");

                foreach (KSCItem ksc in KCTGameStates.KSCs)
                {
                    for (int i = 0; i < ksc.Recon_Rollout.Count; i++)
                    {
                        ReconRollout rr = ksc.Recon_Rollout[i];
                        if (rr.RRType != ReconRollout.RolloutReconType.Reconditioning && Utilities.FindBLVesselByID(new Guid(rr.AssociatedID)) == null)
                        {
                            KCTDebug.Log($"Invalid Recon_Rollout at {ksc.KSCName}. ID {rr.AssociatedID} not found.");
                            ksc.Recon_Rollout.Remove(rr);
                            i--;
                        }
                    }

                    for (int i = 0; i < ksc.AirlaunchPrep.Count; i++)
                    {
                        AirlaunchPrep ap = ksc.AirlaunchPrep[i];
                        if (Utilities.FindBLVesselByID(new Guid(ap.AssociatedID)) == null)
                        {
                            KCTDebug.Log($"Invalid KCT_AirlaunchPrep at {ksc.KSCName}. ID {ap.AssociatedID} not found.");
                            ksc.AirlaunchPrep.Remove(ap);
                            i--;
                        }
                    }
                }
                KCTDebug.Log("SP done");
            }

            if (HighLogic.LoadedSceneIsFlight && KCTGameStates.IsSimulatedFlight)
            {
                Utilities.EnableSimulationLocks();
                if (KCTGameStates.SimulationParams.SimulationUT > 0 &&
                    FlightDriver.CanRevertToPrelaunch)    // Used for checking whether the player has saved and then loaded back into that save
                {
                    KCTDebug.Log($"Setting simulation UT to {KCTGameStates.SimulationParams.SimulationUT}");
                    Planetarium.SetUniversalTime(KCTGameStates.SimulationParams.SimulationUT);
                }
            }

            if (KCTGameStates.IsSimulatedFlight && HighLogic.LoadedSceneIsGame && !HighLogic.LoadedSceneIsFlight)
            {
                string msg = "Current save appears to be a simulation with no way to automatically revert to the pre-simulation state. An older save needs to be loaded manually now.";
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "errorPopup", "KCT Simulation error", msg, "Understood", false, HighLogic.UISkin);
            }

            KCTDebug.Log("DelayedStart finished");
        }
Exemple #15
0
        public void onEvaStart(GameEvents.FromToAction <Part, Part> data)
        {
            Log.Info("onEvaStart, ModEnabled: " + ModEnabled.ToString());
            if (ModEnabled)
            {
                double fuelInEVAPack = 0;
                double takenFuel     = 0;
                double fuelRequest   = 0;
                //if (!data.from.Resources.Contains(HighLogic.CurrentGame.Parameters.CustomParams<EVAFuelSettings>().ShipPropellantName))
                {
                    //Log.Info("data.to/from not null");
                    //Log.Info("Part does not contain the resource: " + HighLogic.CurrentGame.Parameters.CustomParams<EVAFuelSettings>().ShipPropellantName);
                    fuelInEVAPack = this.onEvaHandler(data);
                }


                double evaTankFuelMax = HighLogic.CurrentGame.Parameters.CustomParams <EVAFuelSettings> ().EvaTankFuelMax;
                // Check available volume for EVA fuel - it might be reduced by some external factors
                // Default value for EVA fuel is 5 units however EVAFuel may be configured for greater amount
                // Treat propellantResourceDefaultAmount as multiplier where 5 units correspond to 100%
                //
                if (data.to.vessel.evaController != null)
                {
                    double defaultEVAFuel = data.to.vessel.evaController.propellantResourceDefaultAmount;
                    Log.Info("default EVA resource amount: " + defaultEVAFuel);
                    evaTankFuelMax *= defaultEVAFuel / 5;
                }

                takenFuel = data.from.RequestResource(HighLogic.CurrentGame.Parameters.CustomParams <EVAFuelSettings>().ShipPropellantName,
                                                      (evaTankFuelMax - fuelInEVAPack) /
                                                      HighLogic.CurrentGame.Parameters.CustomParams <EVAFuelSettings>().FuelConversionFactor);
                fuelRequest = takenFuel * HighLogic.CurrentGame.Parameters.CustomParams <EVAFuelSettings>().FuelConversionFactor;

                Log.Info("fuelInEVAPack: " + fuelInEVAPack.ToString() + "   takenFuel: " + takenFuel.ToString() + "    fuelRequest: " + fuelRequest.ToString());


                bool rescueShip = false;
                if ((fuelRequest + fuelInEVAPack) == 0)
                { //Only check for rescue vessel status if there's no EVA fuel in the current ship.
                    var crewList = data.to.vessel.GetVesselCrew();
                    if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
                    {
                        if (Contracts.ContractSystem.Instance != null)
                        {
                            var contracts = Contracts.ContractSystem.Instance.Contracts;
                            for (int currentCrew = 0; currentCrew < crewList.Count; currentCrew++)
                            {
                                for (int currentContract = 0; currentContract < contracts.Count; currentContract++)
                                {
                                    if (contracts[currentContract].Title.Contains(crewList[currentCrew].name.Split(null)[0]) && data.from.vessel.name.Contains(crewList[currentCrew].name.Split(null)[0]))
                                    {//Please do not rename your ship to have a rescue contract Kerbal name in it if the contract is active.
                                        rescueShip = true;
                                    }
                                }
                            }
                        }
                    }
                }

                //Floats and doubles don't like exact numbers. :/ Need to test for similarity rather than equality.
                if (fuelRequest + fuelInEVAPack + 0.001 > evaTankFuelMax)
                {
                    data.to.RequestResource(resourceName, evaTankFuelMax - (fuelRequest + fuelInEVAPack));
                    if (ShowInfoMessage)
                    {
                        ScreenMessages.PostScreenMessage("Filled EVA tank with " + Math.Round(takenFuel, 2).ToString() + " units of " + resourceName + ".", HighLogic.CurrentGame.Parameters.CustomParams <EVAFuelSettings>().ScreenMessageLife, ScreenMessageStyle.UPPER_CENTER);
                    }
                }
                else if (rescueShip == true && (fuelRequest + fuelInEVAPack) == 0)
                {
                    data.to.RequestResource(resourceName, evaTankFuelMax - 1);                    //give one unit of eva propellant
                    if (ShowLowFuelWarning && (!DisableLowFuelWarningLandSplash || !data.from.vessel.LandedOrSplashed))
                    {
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "evafuel1", "Rescue fuel!", "Warning! There was no fuel aboard ship, so only one single unit of " + resourceName + " was able to be scrounged up for the journey!", "OK", false, HighLogic.UISkin);
                    }
                }
                else
                {
                    data.to.RequestResource(resourceName, evaTankFuelMax - (fuelRequest + fuelInEVAPack));
                    if (ShowLowFuelWarning && (!DisableLowFuelWarningLandSplash || !data.from.vessel.LandedOrSplashed))
                    {
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "evafuel2", "Low EVA Fuel!", "Warning! Only " + Math.Round(takenFuel, 2).ToString() + " units of " + HighLogic.CurrentGame.Parameters.CustomParams <EVAFuelSettings>().ShipPropellantName + " were available for EVA! Meaning you only have " + Math.Round(fuelRequest, 2).ToString() + " units of " + resourceName + "!", "OK", false, HighLogic.UISkin);
                    }
                }
            }
        }
Exemple #16
0
        public static void DrawPresetWindow(int windowID)
        {
            GUIStyle yellowText = new GUIStyle(GUI.skin.label);

            yellowText.normal.textColor = Color.yellow;

            if (WorkingPreset == null)
            {
                SetNewWorkingPreset(new KCT_Preset(KCT_PresetManager.Instance.ActivePreset), false); //might need to copy instead of assign here
                presetIndex = KCT_PresetManager.Instance.GetIndex(WorkingPreset);
            }

            GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();

            //preset selector
            GUILayout.BeginVertical();
            GUILayout.Label("Presets", yellowText, GUILayout.ExpandHeight(false));
            //preset toolbar in a scrollview
            presetScrollView = GUILayout.BeginScrollView(presetScrollView, HighLogic.Skin.textArea, GUILayout.Width(presetPosition.width / 6.0f));
            string[] presetShortNames = KCT_PresetManager.Instance.PresetShortNames(true);
            if (presetIndex == -1)
            {
                SetNewWorkingPreset(null, true);

                /*presetIndex = presetShortNames.Length - 1;
                 * WorkingPreset.name = "Custom";
                 * WorkingPreset.shortName = "Custom";
                 * WorkingPreset.description = "A custom set of configs.";
                 * WorkingPreset.author = HighLogic.SaveFolder;*/
            }
            if (changed && presetIndex < presetShortNames.Length - 1 && !KCT_Utilities.ConfigNodesAreEquivalent(WorkingPreset.AsConfigNode(), KCT_PresetManager.Instance.Presets[presetIndex].AsConfigNode())) //!KCT_PresetManager.Instance.PresetsEqual(WorkingPreset, KCT_PresetManager.Instance.Presets[presetIndex], true)
            {
                SetNewWorkingPreset(null, true);

                /*presetIndex = presetShortNames.Length - 1; //Custom preset
                 * WorkingPreset.name = "Custom";
                 * WorkingPreset.shortName = "Custom";
                 * WorkingPreset.description = "A custom set of configs.";
                 * WorkingPreset.author = HighLogic.SaveFolder;*/
            }

            /* presetIndex = KCT_PresetManager.Instance.GetIndex(WorkingPreset); //Check that the current preset is equal to the expected one
             * if (presetIndex == -1)
             *   presetIndex = presetNames.Length - 1;*/
            int prev = presetIndex;

            presetIndex = GUILayout.SelectionGrid(presetIndex, presetShortNames, 1);
            if (prev != presetIndex) //If a new preset was selected
            {
                if (presetIndex != presetShortNames.Length - 1)
                {
                    SetNewWorkingPreset(new KCT_Preset(KCT_PresetManager.Instance.Presets[presetIndex]), false);
                }
                else
                {
                    SetNewWorkingPreset(null, true);

                    /*WorkingPreset.name = "Custom";
                     * WorkingPreset.shortName = "Custom";
                     * WorkingPreset.description = "A custom set of configs.";
                     * WorkingPreset.author = HighLogic.SaveFolder;*/
                }
            }

            //presetIndex = GUILayout.Toolbar(presetIndex, presetNames);

            GUILayout.EndScrollView();
            if (GUILayout.Button("Save as\nNew Preset", GUILayout.ExpandHeight(false)))
            {
                //create new preset
                SaveAsNewPreset(WorkingPreset);
            }
            if (WorkingPreset.AllowDeletion && presetIndex != presetShortNames.Length - 1 && GUILayout.Button("Delete Preset")) //allowed to be deleted and isn't Custom
            {
                DialogOption[] options = new DialogOption[2];
                options[0] = new DialogOption("Delete File", DeleteActivePreset);
                options[1] = new DialogOption("Cancel", DummyVoid);
                MultiOptionDialog dialog = new MultiOptionDialog("Are you sure you want to delete the selected Preset, file and all? This cannot be undone!", windowTitle: "Confirm Deletion", options: options);
                PopupDialog.SpawnPopupDialog(dialog, false, HighLogic.Skin);
            }
            GUILayout.EndVertical();

            //Main sections
            GUILayout.BeginVertical();
            presetMainScroll = GUILayout.BeginScrollView(presetMainScroll);
            //Preset info section
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.Label("Preset Name: " + WorkingPreset.name);
            GUILayout.Label("Description: " + WorkingPreset.description);
            GUILayout.Label("Author(s): " + WorkingPreset.author);
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            //Features section
            GUILayout.BeginVertical();
            GUILayout.Label("Features", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            WorkingPreset.generalSettings.Enabled                     = GUILayout.Toggle(WorkingPreset.generalSettings.Enabled, "Mod Enabled", HighLogic.Skin.button);
            WorkingPreset.generalSettings.BuildTimes                  = GUILayout.Toggle(WorkingPreset.generalSettings.BuildTimes, "Build Times", HighLogic.Skin.button);
            WorkingPreset.generalSettings.ReconditioningTimes         = GUILayout.Toggle(WorkingPreset.generalSettings.ReconditioningTimes, "Launchpad Reconditioning", HighLogic.Skin.button);
            WorkingPreset.generalSettings.TechUnlockTimes             = GUILayout.Toggle(WorkingPreset.generalSettings.TechUnlockTimes, "Tech Unlock Times", HighLogic.Skin.button);
            WorkingPreset.generalSettings.KSCUpgradeTimes             = GUILayout.Toggle(WorkingPreset.generalSettings.KSCUpgradeTimes, "KSC Upgrade Times", HighLogic.Skin.button);
            WorkingPreset.generalSettings.Simulations                 = GUILayout.Toggle(WorkingPreset.generalSettings.Simulations, "Allow Simulations", HighLogic.Skin.button);
            WorkingPreset.generalSettings.SimulationCosts             = GUILayout.Toggle(WorkingPreset.generalSettings.SimulationCosts, "Simulation Costs", HighLogic.Skin.button);
            WorkingPreset.generalSettings.RequireVisitsForSimulations = GUILayout.Toggle(WorkingPreset.generalSettings.RequireVisitsForSimulations, "Must Visit Planets", HighLogic.Skin.button);
            WorkingPreset.generalSettings.TechUpgrades                = GUILayout.Toggle(WorkingPreset.generalSettings.TechUpgrades, "Upgrades From Tech Tree", HighLogic.Skin.button);
            WorkingPreset.generalSettings.SharedUpgradePool           = GUILayout.Toggle(WorkingPreset.generalSettings.SharedUpgradePool, "Shared Upgrade Pool (KSCSwitcher)", HighLogic.Skin.button);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Starting Upgrades:");
            WorkingPreset.generalSettings.StartingPoints = GUILayout.TextField(WorkingPreset.generalSettings.StartingPoints, GUILayout.Width(100));
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
            GUILayout.EndVertical(); //end Features


            GUILayout.BeginVertical(); //Begin time settings
            GUILayout.Label("Time Settings", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Overall Multiplier: ");
            double.TryParse(OMultTmp = GUILayout.TextField(OMultTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.OverallMultiplier);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Build Effect: ");
            double.TryParse(BEffTmp = GUILayout.TextField(BEffTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.BuildEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Inventory Effect: ");
            double.TryParse(IEffTmp = GUILayout.TextField(IEffTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.InventoryEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Reconditioning Effect: ");
            double.TryParse(ReEffTmp = GUILayout.TextField(ReEffTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.ReconditioningEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Max Reconditioning: ");
            double.TryParse(MaxReTmp = GUILayout.TextField(MaxReTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.MaxReconditioning);
            GUILayout.EndHorizontal();
            GUILayout.Label("Rollout-Reconditioning Split:");
            GUILayout.BeginHorizontal();
            //GUILayout.Label("Rollout", GUILayout.ExpandWidth(false));
            WorkingPreset.timeSettings.RolloutReconSplit = GUILayout.HorizontalSlider((float)Math.Floor(WorkingPreset.timeSettings.RolloutReconSplit * 100f), 0, 100) / 100.0;
            //GUILayout.Label("Recon.", GUILayout.ExpandWidth(false));
            GUILayout.EndHorizontal();
            GUILayout.Label((Math.Floor(WorkingPreset.timeSettings.RolloutReconSplit * 100)) + "% Rollout, " + (100 - Math.Floor(WorkingPreset.timeSettings.RolloutReconSplit * 100)) + "% Reconditioning");
            GUILayout.EndVertical();   //end time settings
            GUILayout.EndVertical();
            GUILayout.EndHorizontal(); //end feature/time setting split

            //begin formula settings
            GUILayout.BeginVertical();
            GUILayout.Label("Formula Settings (Advanced)", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Show/Hide Formulas"))
            {
                showFormula = !showFormula;
            }
            if (GUILayout.Button("View Wiki in Browser"))
            {
                Application.OpenURL("https://github.com/magico13/KCT/wiki");
            }
            GUILayout.EndHorizontal();

            if (showFormula)
            {
                //show half here, half on other side? Or all in one big list
                int textWidth = 350;
                GUILayout.BeginHorizontal();
                GUILayout.Label("NodeFormula: ");
                WorkingPreset.formulaSettings.NodeFormula = GUILayout.TextField(WorkingPreset.formulaSettings.NodeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradeFunds: ");
                WorkingPreset.formulaSettings.UpgradeFundsFormula = GUILayout.TextField(WorkingPreset.formulaSettings.UpgradeFundsFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradeScience: ");
                WorkingPreset.formulaSettings.UpgradeScienceFormula = GUILayout.TextField(WorkingPreset.formulaSettings.UpgradeScienceFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("ResearchFormula: ");
                WorkingPreset.formulaSettings.ResearchFormula = GUILayout.TextField(WorkingPreset.formulaSettings.ResearchFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("EffectivePart: ");
                WorkingPreset.formulaSettings.EffectivePartFormula = GUILayout.TextField(WorkingPreset.formulaSettings.EffectivePartFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("ProceduralPart: ");
                WorkingPreset.formulaSettings.ProceduralPartFormula = GUILayout.TextField(WorkingPreset.formulaSettings.ProceduralPartFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("BPFormula: ");
                WorkingPreset.formulaSettings.BPFormula = GUILayout.TextField(WorkingPreset.formulaSettings.BPFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("KSCUpgrade: ");
                WorkingPreset.formulaSettings.KSCUpgradeFormula = GUILayout.TextField(WorkingPreset.formulaSettings.KSCUpgradeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Reconditioning: ");
                WorkingPreset.formulaSettings.ReconditioningFormula = GUILayout.TextField(WorkingPreset.formulaSettings.ReconditioningFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("BuildRate: ");
                WorkingPreset.formulaSettings.BuildRateFormula = GUILayout.TextField(WorkingPreset.formulaSettings.BuildRateFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("SimCost: ");
                WorkingPreset.formulaSettings.SimCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.SimCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("KerbinSimCost: ");
                WorkingPreset.formulaSettings.KerbinSimCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.KerbinSimCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradeReset: ");
                WorkingPreset.formulaSettings.UpgradeResetFormula = GUILayout.TextField(WorkingPreset.formulaSettings.UpgradeResetFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("InventorySale: ");
                WorkingPreset.formulaSettings.InventorySaleFormula = GUILayout.TextField(WorkingPreset.formulaSettings.InventorySaleFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("RolloutCosts: ");
                WorkingPreset.formulaSettings.RolloutCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.RolloutCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("NewLaunchPadCost: ");
                WorkingPreset.formulaSettings.NewLaunchPadCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.NewLaunchPadCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();
            }

            GUILayout.EndVertical();
            GUILayout.EndVertical(); //end formula settings

            GUILayout.EndScrollView();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Save", GUILayout.ExpandWidth(false)))
            {
                KCT_PresetManager.Instance.ActivePreset = WorkingPreset;
                KCT_PresetManager.Instance.SaveActiveToSaveData();
                WorkingPreset = null;
                showSettings  = false;


                if (!KCT_PresetManager.Instance.ActivePreset.generalSettings.Enabled)
                {
                    KCT_Utilities.DisableModFunctionality();
                }
                //KCT_GameStates.settings.enabledForSave = KCT_PresetManager.Instance.ActivePreset.generalSettings.Enabled;
                KCT_GameStates.settings.MaxTimeWarp          = newTimewarp;
                KCT_GameStates.settings.ForceStopWarp        = forceStopWarp;
                KCT_GameStates.settings.DisableAllMessages   = disableAllMsgs;
                KCT_GameStates.settings.OverrideLaunchButton = overrideLaunchBtn;
                KCT_GameStates.settings.Debug                = debug;
                KCT_GameStates.settings.AutoKACAlarms        = autoAlarms;
                KCT_GameStates.settings.PreferBlizzyToolbar  = useBlizzyToolbar;
                KCT_GameStates.settings.CheckForDebugUpdates = debugUpdateChecking;

                KCT_GameStates.settings.Save();
                showSettings = false;
                if (!PrimarilyDisabled && !showFirstRun)
                {
                    ResetBLWindow();
                    if (KCT_Events.instance.KCTButtonStock != null)
                    {
                        KCT_Events.instance.KCTButtonStock.SetTrue();
                    }
                    else
                    {
                        showBuildList = true;
                    }
                }
                if (!KCT_PresetManager.Instance.ActivePreset.generalSettings.Enabled)
                {
                    InputLockManager.RemoveControlLock("KCTKSCLock");
                }

                for (int j = 0; j < KCT_GameStates.TechList.Count; j++)
                {
                    KCT_GameStates.TechList[j].UpdateBuildRate(j);
                }

                KCT_GUI.ResetFormulaRateHolders();
            }
            if (GUILayout.Button("Cancel", GUILayout.ExpandWidth(false)))
            {
                WorkingPreset = null;
                showSettings  = false;
                if (!PrimarilyDisabled && !showFirstRun)
                {
                    ResetBLWindow();
                    if (KCT_Events.instance.KCTButtonStock != null)
                    {
                        KCT_Events.instance.KCTButtonStock.SetTrue();
                    }
                    else
                    {
                        showBuildList = true;
                    }
                }

                for (int j = 0; j < KCT_GameStates.TechList.Count; j++)
                {
                    KCT_GameStates.TechList[j].UpdateBuildRate(j);
                }
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();                       //end column 2

            GUILayout.BeginVertical(GUILayout.Width(100)); //Start general settings
            GUILayout.Label("General Settings", yellowText);
            GUILayout.Label("NOTE: Affects all saves!", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.Label("Max Timewarp");
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("-", GUILayout.ExpandWidth(false)))
            {
                newTimewarp = Math.Max(newTimewarp - 1, 0);
            }
            //current warp setting
            GUILayout.Label(TimeWarp.fetch.warpRates[newTimewarp] + "x");
            if (GUILayout.Button("+", GUILayout.ExpandWidth(false)))
            {
                newTimewarp = Math.Min(newTimewarp + 1, TimeWarp.fetch.warpRates.Length - 1);
            }
            GUILayout.EndHorizontal();

            forceStopWarp     = GUILayout.Toggle(forceStopWarp, "Auto Stop TimeWarp", HighLogic.Skin.button);
            autoAlarms        = GUILayout.Toggle(autoAlarms, "Auto KAC Alarms", HighLogic.Skin.button);
            overrideLaunchBtn = GUILayout.Toggle(overrideLaunchBtn, "Override Launch Button", HighLogic.Skin.button);
            useBlizzyToolbar  = GUILayout.Toggle(useBlizzyToolbar, "Use Toolbar Mod", HighLogic.Skin.button);
            disableAllMsgs    = !GUILayout.Toggle(!disableAllMsgs, "Use Message System", HighLogic.Skin.button);
            debug             = GUILayout.Toggle(debug, "Debug Logging", HighLogic.Skin.button);
#if DEBUG
            debugUpdateChecking = GUILayout.Toggle(debugUpdateChecking, "Check for Dev Updates", HighLogic.Skin.button);
#endif
            GUILayout.EndVertical();
            GUILayout.EndVertical();

            GUILayout.EndHorizontal(); //end main split
            GUILayout.EndVertical();   //end window

            changed = GUI.changed;

            if (!Input.GetMouseButtonDown(1) && !Input.GetMouseButtonDown(2))
            {
                GUI.DragWindow();
            }
        }
 private static bool ShowDialog(PopupDialog type, object data = null)
 {
     return((bool)MessageManager.SendMessage <ShowDialogMessage>(type, data));
 }
        private void Reinstate(QuickDocument quickDocument)
        {
            var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.UnDeleteDocumentCompleted += (s, e) =>
            {
                if (e.Result.HasErrors)
                {
                    var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(e.Result.ServerErrorMessages));
                    errorDialog.Show();
                    return;
                }
            };
            cmsWebServiceClient.UnDeleteDocumentAsync(quickDocument.Id);
        }
        private void DeleteButtonHandler(object parameter)
        {
            var selected = (from x in DocumentLocations where x.Checked select x).ToList();

            if (selected.Count == 0)
            {
                return;
            }

            string message = string.Format("Remove selected Locations? ({0})", selected.Count);
            PopupDialog popupDialog = new PopupDialog(PopupDialogType.ConfirmDelete, message);
            popupDialog.Show();
            popupDialog.Closed +=
                (s2, e2) =>
                {
                    if (popupDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {
                        List<DocumentAssignedLocation> keep = new List<DocumentAssignedLocation>((from x in DocumentLocations where !x.Checked select x).ToList());
                        mDocument.DocumentAssignedLocations = keep;

                        RaisePropertyChanged("DocumentLocations");
                        OnCollectionChanged();
                        Utils.OnCollectionChanged(EventAggregator, mDocument, "DocumentLocationsViewModel", true);
                    }
                };
        }
Exemple #20
0
//		public static void Log(string message)
//		{
//			Debug.Log("KRASH: " + message);
//		}
        public static void ErrorPopup(string message)
        {
            //PopupDialog.SpawnPopupDialog("Error", message, "Close", true, HighLogic.Skin);
            PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Error", message, "Close", true, HighLogic.UISkin);
        }
Exemple #21
0
        private void Save()
        {
            List<RolePrivilege> rolePrivileges = new List<RolePrivilege>();

            //Add only privileges that have access
            foreach (var mRolePrivilegeViewModel in mRolePrivilegesViewModel)
            {
                if (mRolePrivilegeViewModel.HasAccess)
                {
                    mRolePrivilegeViewModel.RolePrivilege.Privilege = null;
                    mRolePrivilegeViewModel.RolePrivilege.Role = null;
                    mRolePrivilegeViewModel.RolePrivilege.SecurityObject = null;

                    rolePrivileges.Add(mRolePrivilegeViewModel.RolePrivilege);
                }
            }

            mRole.RolePrivileges.Clear();
            mRole.RolePrivileges = rolePrivileges;

            //Update Role privileges for this role
            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
            cmsWebServiceClient.SaveRolePrivilegesCompleted += (s1, e1) =>
                                                                   {

                                                                       if (e1.Result.HasErrors)
                                                                       {
                                                                           var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(e1.Result.ServerErrorMessages));
                                                                           errorDialog.Show();
                                                                           return;
                                                                       }

                                                                       mRole = e1.Result.EntityResult;

                                                                       if (CMS.User.RoleId == mRole.Id)
                                                                       {
                                                                           //Update the role if the user has the same role assigned
                                                                           CMS.User.Role = mRole;
                                                                       }

                                                                       var existingRole = (from x in CMS.Cache.Roles where x.Id == mRole.Id select x).FirstOrDefault();
                                                                       if (existingRole != null)
                                                                       {
                                                                           //Update role
                                                                           CommonUtils.CloneObject(existingRole, mRole, "Id");
                                                                       }
                                                                       else
                                                                       {
                                                                           //Add new role to the Cache
                                                                           CMS.Cache.Roles.Add(mRole);
                                                                       }
                                                                       Utils.SetEffectivePrivileges();
                                                                       //Close the dialog
                                                                       DialogResult = true;
                                                                   };

            cmsWebServiceClient.SaveRolePrivilegesAsync(CMS.User.Id, mRole);
        }
Exemple #22
0
        private void VesselRecoveryProcessing(ProtoVessel v, MissionRecoveryDialog mrDialog, float data)
        {
            Debug.Log("[RP-0] - Vessel recovery processing");

            var retirementChanges = new List <string>();
            var inactivity        = new List <string>();

            double UT = Planetarium.GetUniversalTime();

            // normally we would use v.missionTime, but that doesn't seem to update
            // when you're not actually controlling the vessel
            double elapsedTime = UT - v.launchTime;

            Debug.Log($"[RP-0] mission elapsedTime: {KSPUtil.PrintDateDeltaCompact(elapsedTime, true, true)}");

            // When flight duration was too short, mission training should not be set as expired.
            // This can happen when an on-the-pad failure occurs and the vessel is recovered.
            // We could perhaps override this if they're not actually in flight
            // (if the user didn't recover right from the pad I think this is a fair assumption)
            if (elapsedTime < Settings.minFlightDurationSecondsForTrainingExpire)
            {
                Debug.Log($"[RP-0] - mission time too short for crew to be inactive (elapsed time was {elapsedTime}, settings set for {Settings.minFlightDurationSecondsForTrainingExpire})");
                return;
            }

            var validStatuses = new List <string>
            {
                FlightLog.EntryType.Flight.ToString(), Situation_FlightHigh, FlightLog.EntryType.Suborbit.ToString(),
                FlightLog.EntryType.Orbit.ToString(), FlightLog.EntryType.ExitVessel.ToString(),
                FlightLog.EntryType.Land.ToString(), FlightLog.EntryType.Flyby.ToString()
            };

            foreach (ProtoCrewMember pcm in v.GetVesselCrew())
            {
                Debug.Log("[RP-0] - Found ProtoCrewMember: " + pcm.displayName);

                var    allFlightsDict = new Dictionary <string, int>();
                int    curFlight      = pcm.careerLog.Last().flight;
                double inactivityMult = 0;
                double retirementMult = 0;

                foreach (FlightLog.Entry e in pcm.careerLog.Entries)
                {
                    if (e.type == "Nationality")
                    {
                        continue;
                    }
                    if (e.type == TrainingType_Mission)
                    {
                        SetExpiration(pcm.name, e, Planetarium.GetUniversalTime());
                    }

                    if (validStatuses.Contains(e.type))
                    {
                        int situationCount;
                        var key = $"{e.target}-{e.type}";
                        if (allFlightsDict.ContainsKey(key))
                        {
                            situationCount      = allFlightsDict[key];
                            allFlightsDict[key] = ++situationCount;
                        }
                        else
                        {
                            situationCount = 1;
                            allFlightsDict.Add(key, situationCount);
                        }

                        if (e.flight != curFlight)
                        {
                            continue;
                        }

                        if (TryGetBestSituationMatch(e.target, e.type, "Retire", out double situationMult))
                        {
                            double countMult = 1 + Math.Pow(situationCount - 1, Settings.retireOffsetFlightNumPow);
                            retirementMult += situationMult / countMult;
                        }

                        if (TryGetBestSituationMatch(e.target, e.type, "Inactive", out double inactivMult))
                        {
                            inactivityMult += inactivMult;
                        }
                    }
                }

                Debug.Log("[RP-0]  retirementMult: " + retirementMult);
                Debug.Log("[RP-0]  inactivityMult: " + inactivityMult);

                double acMult = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) + 1;
                Debug.Log("[RP-0]  AC multiplier: " + acMult);

                if (KerbalRetireTimes.TryGetValue(pcm.name, out double retTime))
                {
                    double stupidityPenalty = UtilMath.Lerp(Settings.retireOffsetStupidMin, Settings.retireOffsetStupidMax, pcm.stupidity);
                    Debug.Log($"[RP-0]  stupidityPenalty for {pcm.stupidity}: {stupidityPenalty}");
                    double retireOffset = retirementMult * 86400 * Settings.retireOffsetBaseMult / stupidityPenalty;

                    if (retireOffset > 0)
                    {
                        KerbalRetireIncreases.TryGetValue(pcm.name, out double retIncreaseTotal);
                        retIncreaseTotal += retireOffset;
                        if (retIncreaseTotal > Settings.retireIncreaseCap)
                        {
                            // Cap the total retirement increase at a specific number of years
                            retireOffset    -= retIncreaseTotal - Settings.retireIncreaseCap;
                            retIncreaseTotal = Settings.retireIncreaseCap;
                        }
                        KerbalRetireIncreases[pcm.name] = retIncreaseTotal;

                        string sRetireOffset = KSPUtil.PrintDateDelta(retireOffset, false, false);
                        Debug.Log("[RP-0] retire date increased by: " + sRetireOffset);

                        retTime += retireOffset;
                        KerbalRetireTimes[pcm.name] = retTime;
                        retirementChanges.Add($"\n{pcm.name}, +{sRetireOffset}, no earlier than {KSPUtil.PrintDate(retTime, false)}");
                    }
                }

                inactivityMult = Math.Max(1, inactivityMult);
                double elapsedTimeDays  = elapsedTime / 86400;
                double inactiveTimeDays = Math.Pow(Math.Max(Settings.inactivityMinFlightDurationDays, elapsedTimeDays), Settings.inactivityFlightDurationExponent) *
                                          Math.Min(Settings.inactivityMaxSituationMult, inactivityMult) / acMult;
                double inactiveTime = inactiveTimeDays * 86400;
                Debug.Log("[RP-0] inactive for: " + KSPUtil.PrintDateDeltaCompact(inactiveTime, true, false));

                pcm.SetInactive(inactiveTime, false);
                inactivity.Add($"\n{pcm.name}, until {KSPUtil.PrintDate(inactiveTime + UT, true, false)}");
            }

            if (inactivity.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("The following crew members will be on leave:");
                foreach (string s in inactivity)
                {
                    sb.Append(s);
                }

                if (RetirementEnabled && retirementChanges.Count > 0)
                {
                    sb.Append("\n\nThe following retirement changes have occurred:");
                    foreach (string s in retirementChanges)
                    {
                        sb.Append(s);
                    }
                }

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                             new Vector2(0.5f, 0.5f),
                                             "CrewUpdateNotification",
                                             "Crew Updates",
                                             sb.ToString(),
                                             "OK",
                                             true,
                                             HighLogic.UISkin);
            }
        }
        private void RemoveControlSystemComponentTypeAlarmProperty(NodeView nodeView)
        {
            var confirmDialog = new PopupDialog(PopupDialogType.ConfirmDelete, string.Format("Delete property '{0}'?", nodeView.Name));
            confirmDialog.Show();
            confirmDialog.Closed +=
                (s, e) =>
                {
                    if (confirmDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {
                        var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                        EventHandler<DeleteControlSystemComponentTypeAlarmPropertyCompletedEventArgs> deleteCompleted = null;
                        deleteCompleted = (s2, eventArgs) =>
                        {
                            if (!eventArgs.Result.HasErrors)
                            {
                                nodeView.Parent.Children.Remove(nodeView);
                            }
                            else
                            {
                                var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(eventArgs.Result.ServerErrorMessages));
                                errorDialog.Show();
                            }

                            cmsWebServiceClient.DeleteControlSystemComponentTypeAlarmPropertyCompleted -= deleteCompleted;
                        };

                        cmsWebServiceClient.DeleteControlSystemComponentTypeAlarmPropertyCompleted += deleteCompleted;
                        cmsWebServiceClient.DeleteControlSystemComponentTypeAlarmPropertyAsync(nodeView.Id);
                    }
                };
        }
Exemple #24
0
        private void ProcessRetirements(double time)
        {
            if (RetirementEnabled)
            {
                foreach (KeyValuePair <string, double> kvp in KerbalRetireTimes)
                {
                    ProtoCrewMember pcm = HighLogic.CurrentGame.CrewRoster[kvp.Key];
                    if (pcm == null)
                    {
                        _toRemove.Add(kvp.Key);
                    }
                    else
                    {
                        if (pcm.rosterStatus != ProtoCrewMember.RosterStatus.Available)
                        {
                            if (pcm.rosterStatus != ProtoCrewMember.RosterStatus.Assigned)
                            {
                                _toRemove.Add(kvp.Key);
                            }

                            continue;
                        }

                        if (pcm.inactive)
                        {
                            continue;
                        }

                        if (time > kvp.Value)
                        {
                            _toRemove.Add(kvp.Key);
                            _retirees.Add(kvp.Key);
                            pcm.rosterStatus = ProtoCrewMember.RosterStatus.Dead;
                            pcm.type         = ProtoCrewMember.KerbalType.Crew;
                        }
                    }
                }
            }

            // TODO remove from courses? Except I think they won't retire if inactive either so that's ok.
            if (_toRemove.Count > 0)
            {
                string msgStr = string.Empty;
                foreach (string s in _toRemove)
                {
                    KerbalRetireTimes.Remove(s);
                    if (HighLogic.CurrentGame.CrewRoster[s] != null && _retirees.Contains(s))
                    {
                        msgStr = $"{msgStr}\n{s}";
                    }
                }
                if (!string.IsNullOrEmpty(msgStr))
                {
                    PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                 new Vector2(0.5f, 0.5f),
                                                 "CrewRetirementNotification",
                                                 "Crew Retirement",
                                                 "The following retirements have occurred:\n" + msgStr,
                                                 "OK",
                                                 true,
                                                 HighLogic.UISkin);
                }

                _toRemove.Clear();
            }

            if (_toRemove.Count > 0)
            {
                MaintenanceHandler.Instance?.ScheduleMaintenanceUpdate();
            }
        }
        private void ProccessTransferFiles(int fileNumber, FileInfo dialogFile, List<FileInfo> dialogFiles)
        {
            var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            try
            {
                Stream stream = dialogFile.OpenRead();

                View.RadProgressBar1.Maximum = stream.Length;
                View.RadProgressBar1.Minimum = 0;
                View.RadProgressBar1.Visibility = Visibility.Visible;
                View.RadProgressBar1.Value = 0;

                if (stream.Length > int.MaxValue)
                {
                    var errorDialog = new PopupDialog(PopupDialogType.Warning, string.Format("File [{0}] can not be bigger than 2GB.", dialogFile.Name), "Warning: File is to large");
                    errorDialog.Show();
                    return;
                }

                int transferChunkSize = Utils.GetTransferChunkSize(stream);
                var file = new CommonUploadFile {Name = dialogFile.Name, Size = stream.Length, Path = Guid.NewGuid().ToString()};

                var newAttachment = new IssueFile
                {
                    DateUploaded = DateTime.Now,
                    Filename = file.Name,
                    IssueId = mIssue.Id,
                    Issue = mIssue,
                    Path = file.Path,
                    UploadedById = CMS.User.Id,
                    User = CMS.User,
                    AttachmentType = new AttachmentType {Id = (int) CommonUtils.AttachmentType.Unknown},
                    AttachmentTypeId = (int) CommonUtils.AttachmentType.Unknown,
                    AttachmentTypes = mAttachmentTypes,
                    RestrictedContent = false,
                    SelectedAttachmentType = new AttachmentType {Id = (int) CommonUtils.AttachmentType.Unknown}
                };

                file.Attachment = newAttachment;

                if (stream.Position > -1 && stream.Position < stream.Length)
                {
                    int chunkSize = Utils.GetCurrentChunkSize(stream, transferChunkSize);

                    var fileBytes = new byte[chunkSize];
                    stream.Read(fileBytes, 0, chunkSize);

                    EventHandler<UploadAttachmentCompletedEventArgs> uploadFileChunkCompleted = null;
                    uploadFileChunkCompleted = (s1, e1) =>
                    {
                        if (stream.Position > -1 && stream.Position < stream.Length)
                        {
                            chunkSize = Utils.GetCurrentChunkSize(stream, transferChunkSize);
                            double percentage = (stream.Position/file.Size);

                            string fileName = file.Attachment.Filename.Remove(0, file.Attachment.Filename.IndexOf(']') + 1).Trim();
                            file.Attachment.Filename = String.Format("[{0:#.##%}] {1}", percentage, fileName);

                            fileBytes = new byte[chunkSize];
                            stream.Read(fileBytes, 0, chunkSize);

                            View.RadProgressBar1.Value = View.RadProgressBar1.Value + chunkSize;

                            cmsWebServiceClient.UploadAttachmentAsync(file.Name, fileBytes, file.Path, true);
                        }
                        else
                        {
                            file.Attachment.Filename = file.Name;

                            cmsWebServiceClient.UploadAttachmentCompleted -= uploadFileChunkCompleted;

                            Attachments.Add(newAttachment);

                            //Close the stream when all files are uploaded
                            stream.Close();
                            UploadInProgress = false;
                            if (dialogFiles.Count > fileNumber + 1)
                            {
                                fileNumber++;
                                ProccessTransferFiles(fileNumber, dialogFiles[fileNumber], dialogFiles);
                            }

                            mIssue.IssueFiles.Add(newAttachment);
                            RaisePropertyChanged("SelectedAttachmentType");
                            RaisePropertyChanged("Attachments");
                            OnCollectionChanged();

                            //UPLOAD IS COMPLETE - Save Model
                            cmsWebServiceClient.SaveIssueFilesCompleted += ((sender, args) =>
                            {
                                EventAggregator.GetEvent<PrismEvents.RefreshIssueRevisionHistoryPrismEvent>().Publish(null);
                            });
                            cmsWebServiceClient.SaveIssueFilesAsync(new List<IssueFile> {newAttachment});

                            View.RadProgressBar1.Visibility = Visibility.Collapsed;

                            OnUploadComplete();
                        }
                    };

                    cmsWebServiceClient.UploadAttachmentCompleted += uploadFileChunkCompleted;
                    cmsWebServiceClient.UploadAttachmentAsync(file.Name, fileBytes, file.Path, false);
                }
            }
            catch (IOException)
            {
                OnErrorOccurred(string.Format("Cannot upload the file '{0}' because it is currently open. Please close the file and try again", dialogFile.Name));
            }
            catch (SecurityException)
            {
                OnErrorOccurred(string.Format("Cannot upload the file '{0}' because it is currently open. Please close the file and try again", dialogFile.Name));
            }
            catch (Exception ex)
            {
                OnErrorOccurred(ex.Message);
            }
        }
        /// <summary>
        /// Loads the contract group details from the given config node.
        /// </summary>
        /// <param name="configNode">The config node to load from</param>
        /// <returns>Whether we were successful.</returns>
        public bool Load(ConfigNode configNode)
        {
            try
            {
                dataNode = new DataNode(configNode.GetValue("name"), this);

                LoggingUtil.CaptureLog = true;
                ConfigNodeUtil.SetCurrentDataNode(dataNode);
                bool   valid = true;
                string unused;

                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "name", x => name = x, this);
                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "displayName", x => displayName = x, this, name);
                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "minVersion", x => minVersionStr = x, this, "");
                valid &= ConfigNodeUtil.ParseValue <int>(configNode, "maxCompletions", x => maxCompletions = x, this, 0, x => Validation.GE(x, 0));
                valid &= ConfigNodeUtil.ParseValue <int>(configNode, "maxSimultaneous", x => maxSimultaneous = x, this, 0, x => Validation.GE(x, 0));
                valid &= ConfigNodeUtil.ParseValue <List <string> >(configNode, "disabledContractType", x => disabledContractType = x, this, new List <string>());
                valid &= ConfigNodeUtil.ParseValue <Agent>(configNode, "agent", x => agent = x, this, (Agent)null);
                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "sortKey", x => sortKey = x, this, displayName);
                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "tip", x => unused = x, this, "");

                if (configNode.HasValue("sortKey") && parent == null)
                {
                    sortKey = displayName;
                    LoggingUtil.LogWarning(this, ErrorPrefix() + ": Using the sortKey field is only applicable on child CONTRACT_GROUP elements");
                }

                if (!string.IsNullOrEmpty(minVersionStr))
                {
                    if (Util.Version.VerifyAssemblyVersion("ContractConfigurator", minVersionStr) == null)
                    {
                        valid = false;

                        var    ainfoV  = Attribute.GetCustomAttribute(typeof(ExceptionLogWindow).Assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
                        string title   = "Contract Configurator " + ainfoV.InformationalVersion + " Message";
                        string message = "The contract group '" + name + "' requires at least Contract Configurator " + minVersionStr +
                                         " to work, and you are running version " + ainfoV.InformationalVersion +
                                         ".  Please upgrade Contract Configurator to use the contracts in this group.";
                        DialogGUIButton dialogOption = new DialogGUIButton("Okay", new Callback(DoNothing), true);
                        PopupDialog.SpawnPopupDialog(new MultiOptionDialog("ContractConfiguratorMsg", message, title, UISkinManager.GetSkin("default"), dialogOption), false, UISkinManager.GetSkin("default"));
                    }
                }

                // Load DATA nodes
                valid &= dataNode.ParseDataNodes(configNode, this, dataValues, uniquenessChecks);

                // Do the deferred loads
                valid &= ConfigNodeUtil.ExecuteDeferredLoads();

                // Do post-deferred load warnings
                if (agent == null)
                {
                    LoggingUtil.LogWarning(this, ErrorPrefix() + ": Providing the agent field for all CONTRACT_GROUP nodes is highly recommended, as the agent is used to group contracts in Mission Control.");
                }
                if (string.IsNullOrEmpty(minVersionStr) || minVersion < ContractConfigurator.ENHANCED_UI_VERSION)
                {
                    LoggingUtil.LogWarning(this, ErrorPrefix() + ": No minVersion or older minVersion provided.  It is recommended that the minVersion is set to at least 1.15.0 to turn important warnings for deprecated functionality into errors.");
                }
                if (!configNode.HasValue("displayName"))
                {
                    LoggingUtil.LogWarning(this, ErrorPrefix() + ": No display name provided.  A display name is recommended, as it is used in the Mission Control UI.");
                }

                config = configNode.ToString();
                log   += LoggingUtil.capturedLog;
                LoggingUtil.CaptureLog = false;

                // Load child groups
                foreach (ConfigNode childNode in ConfigNodeUtil.GetChildNodes(configNode, "CONTRACT_GROUP"))
                {
                    ContractGroup child     = null;
                    string        childName = childNode.GetValue("name");
                    try
                    {
                        child = new ContractGroup(childName);
                    }
                    catch (ArgumentException)
                    {
                        LoggingUtil.LogError(this, "Couldn't load CONTRACT_GROUP '" + childName + "' due to a duplicate name.");
                        valid = false;
                        continue;
                    }

                    child.parent          = this;
                    valid                &= child.Load(childNode);
                    child.dataNode.Parent = dataNode;
                    if (child.hasWarnings)
                    {
                        hasWarnings = true;
                    }
                }

                // Check for unexpected values - always do this last
                valid &= ConfigNodeUtil.ValidateUnexpectedValues(configNode, this);

                // Invalidate children
                if (!valid)
                {
                    Invalidate();
                }

                enabled = valid;
                return(valid);
            }
            catch
            {
                enabled = false;
                throw;
            }
        }
        private void UnMarkIssueAsRestrictedContent(QuickIssue quickIssue)
        {
            var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.UnMarkIssueAsRestrictedCompleted += (s, e) =>
            {
                if (e.Result)
                {
                    quickIssue.RestrictedContent = false;

                }
                else
                {
                    var dialog = new PopupDialog(PopupDialogType.Error,
                        "Access is restricted due to issue content – please contact the System Administrator.",
                        "Restricted Content Issue");
                    dialog.Show();
                }
            };
            cmsWebServiceClient.UnMarkIssueAsRestrictedAsync(quickIssue.Id, CMS.User.Id);
        }
Exemple #28
0
        protected void promptPref()
        {
            //Enabled
            PopupDialog.SpawnPopupDialog(
                new MultiOptionDialog(
                    @"Ok, here's the deal:

One way or another, if intentional or not, ModStatistics has been installed into
your KSP GameData folder. ModStatistics is a very useful program for mod authors.
ModStatistics is not built to help indentify you - in fact, with censorship to the
output log, there's no identifiable information at all. At the end of the day,
ModStatistics is built to benefit your gameplay, and give you an all around
better KSP modding experience.

By choosing 'AGREE' below, you agree to allow <SERVER> to collect - periodically, 
over the internet, and completely anonymously:

Mod Usage and Installation, Errors, Exceptions, Crashes, KSP Version, Log File
(WITH CENSORED DIRECTORY), and your Program ID.

Your program ID is not traceable back to you, and is only used to identify individual
instances of KSP - this is so we can tell which reports are from the same game
installation. While this does mean we build information on your specific installation,
it also means we can identify problems from installation and uninstallation, as well
as find out what mods people are using together, identify errors from using mods
together, possible reasons for uninstallation, KSP version incompatibility, and much
more. This is all made to ultimately benefit you.

Some of this information can be turned off independently by the upcoming questions
in addition to config files, and some only by disabling ModStatistics completely,
either by config file or by choosing 'DISAGREE' below.

If you have agreed, the above information will be generated into a report at the
closing or crashing of KSP and sent to < SERVER > the next time KSP is opened.",
                    "ModStatistics - End-User License Agreement",
                    HighLogic.UISkin,
                    new DialogGUIButton("AGREE", () => { enabledChoice(true); writeConfig(); }, true),
                    new DialogGUIButton("DISAGREE", () => { enabledChoice(false); updateChoice(false); writeConfig(); }, true)
                    ),
                true,
                HighLogic.UISkin
                );

            if (!enabled)
            {
                return;
            }

            PopupDialog.SpawnPopupDialog(
                new MultiOptionDialog(
                    @"Would you like ModStatistics to automatically update when new versions are available?
This makes sure your version is set to the correct one, and ensures that mod authors get the most relavant information
possible. Please consider accepting. Updates will be automatically downloaded from: < SERVER >",
                    "ModStatistics - Automatic Updates",
                    HighLogic.UISkin,
                    new DialogGUIButton("Allow Updates", () => { updateChoice(true); writeConfig(); }, true), // checkUpdates(); }, true),
                    new DialogGUIButton("Do Not Allow Updates", () => { updateChoice(false); writeConfig(); }, true)
                    ),
                true,
                HighLogic.UISkin
                );
        }
        private void DeleteButtonHandler(object parameter)
        {
            if (SelectedComponent != null)
            {
                string message = string.Format("Remove selected Calibration? ({0})", SelectedComponent.Name);
                PopupDialog popupDialog = new PopupDialog(PopupDialogType.ConfirmDelete, message);
                popupDialog.Show();
                popupDialog.Closed +=
                    (s2, e2) =>
                    {
                        if (popupDialog.PopupDialogResult == PopupDialogResult.Yes)
                        {
                            mInstrument.CalibrationComponents.Remove(SelectedComponent);

                            View.ComponentPropertiesControl.Content = null;
                            RaisePropertyChanged("Components");
                            RaisePropertyChanged("SelectedComponent");

                            mSelectedComponent = null;
                            RaiseChangeEvent();

                            OnCollectionChanged();
                        }
                    };

            }
        }
 public ShowDialogMessage(object source, PopupDialog type, bool moduleDialog)
     : this(type, (object)null)
 {
     Source = source;
     ModuleDialog = moduleDialog;
 }
Exemple #31
0
 // Displays a warning if Kopernicus failed to load for some reason
 public static void DisplayWarning()
 {
     PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "KopernicusFail", "Warning", "Kopernicus was not able to load the custom planetary system due to an exception in the loading process.\n" +
                                  "Loading your savegame is NOT recommended, because the missing planets could corrupt it and delete your progress.\n\n" +
                                  "Please contact the planet pack author or the Kopernicus team about the issue and send them a valid bugreport, including your KSP.log, your ModuleManager.ConfigCache file and the folder Logs/Kopernicus/ from your KSP root directory.\n\n", "OK", true, UISkinManager.GetSkin("MainMenuSkin"));
 }
Exemple #32
0
        public void FixedUpdate()
        {
            var vessel = GetComponent <Vessel>();

            if (vessel != FlightGlobals.ActiveVessel)
            {
                KRASHShelter.instance.SetSimActiveNotification();
                Destroy(this);
                return;
            }
            KRASHShelter.instance.SetSimNotification("Simulation Setup in Progress");
            if (AlreadyTeleported)
            {
                if (vessel.LandedOrSplashed)
                {
                    if (!pausebeforestarting)
                    {
                        pausebeforestarting = true;
                        FlightDriver.SetPause(true);
                        //PopupDialog.SpawnPopupDialog ("Vessel has landed", "Vessel has landed.  Click the OK button to continue", "OK", true, HighLogic.Skin);
                        var dialog = new MultiOptionDialog("krash4", "Vessel has landed.  Click the OK button to continue", "", HighLogic.UISkin, new DialogGUIBase[] {
                            new DialogGUIButton("OK", () => {
                                FlightDriver.SetPause(false);
                                KRASHShelter.instance.SetSimActiveNotification();
                                Destroy(this);
                                //	_activePopup.Dismiss ();
                            })
                        });
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin, true);
                    }
                }
                else
                {
                    var accel = (vessel.srf_velocity + vessel.upAxis) * -0.5;
                    vessel.ChangeWorldVelocity(accel);
                    Hyperedit.RateLimitedLogger.Log(accelLogObject,
                                                    string.Format("(Happening every frame) Soft-lander changed ship velocity this frame by vector {0},{1},{2} (mag {3})",
                                                                  accel.x, accel.y, accel.z, accel.magnitude));
                }
            }
            else
            {
                Log.Info("NotTeleported");
                var pqs = Body.pqsController;
                if (pqs == null)
                {
                    KRASHShelter.instance.SetSimActiveNotification();
                    Destroy(this);
                    return;
                }

                var alt = pqs.GetSurfaceHeight(
                    QuaternionD.AngleAxis(Longitude, Vector3d.down) *
                    QuaternionD.AngleAxis(Latitude, Vector3d.forward) * Vector3d.right) -
                          pqs.radius;
                alt = Math.Max(alt, 0);                 // Underwater!

                if (TimeWarp.CurrentRateIndex != 0)
                {
                    TimeWarp.SetRate(0, true);
                    Log.Info("Set time warp to index 0");
                }
                // HoldVesselUnpack is in display frames, not physics frames
                Log.Info("alt: " + alt.ToString() + "   Altitude: " + Altitude.ToString());
                Log.Info("Latitude: " + Latitude.ToString() + "   Longitude: " + Longitude.ToString());

                //var teleportPosition = Body.GetRelSurfacePosition(Latitude, Longitude, alt + Altitude);
                var teleportPosition = Body.GetWorldSurfacePosition(Latitude, Longitude, alt + Altitude) - Body.position;

                var teleportVelocity = Body.getRFrmVel(teleportPosition + Body.position);
                // convert from world space to orbit space
                teleportPosition = teleportPosition.xzy;
                teleportVelocity = teleportVelocity.xzy;
                // counter for the momentary fall when on rails (about one second)
                teleportVelocity += teleportPosition.normalized * (Body.gravParameter / teleportPosition.sqrMagnitude);

                //	var oldUp = vessel.orbit.pos.xzy.normalized; // can also be vessel.vesselTransform.position, I think
                //	var newUp = teleportPosition.xzy.normalized; // teleportPosition is the orbitspace location (note the .xzy)
                //	var rotation = Quaternion.FromToRotation(oldUp, newUp)*vessel.vesselTransform.rotation;

                var from     = Vector3d.up;
                var to       = teleportPosition.xzy.normalized;
                var rotation = Quaternion.FromToRotation(from, to);


                var orbit = vessel.orbitDriver.orbit.Clone();
                orbit.UpdateFromStateVectors(teleportPosition, teleportVelocity, Body, Planetarium.GetUniversalTime());


                vessel.SetOrbit(orbit);
                vessel.SetRotation(rotation);

                AlreadyTeleported = true;
            }
        }
 public ShowDialogMessage(object source, PopupDialog type, object data)
     : this(type, data)
 {
     Source = source;
 }
Exemple #34
0
        internal void ProcessUpgrade()
        {
            int oldLevel = getMember <int>("level");

            KCTDebug.Log($"Upgrading from level {oldLevel}");

            string facilityID = GetFacilityID();
            SpaceCenterFacility facilityType = GetFacilityType();

            string gate = GetTechGate(facilityID, oldLevel + 1);

            KCTDebug.Log("[KCTT] Gate for " + facilityID + "? " + gate);
            if (!string.IsNullOrEmpty(gate))
            {
                if (ResearchAndDevelopment.GetTechnologyState(gate) != RDTech.State.Available)
                {
                    PopupDialog.SpawnPopupDialog(new MultiOptionDialog("kctUpgradePadConfirm",
                                                                       "Can't upgrade this facility. Requires " + KerbalConstructionTimeData.techNameToTitle[gate] + ".",
                                                                       "Lack Tech to Upgrade",
                                                                       HighLogic.UISkin,
                                                                       new DialogGUIButton("Ok", stub)),
                                                 false,
                                                 HighLogic.UISkin);

                    return;
                }
            }

            KCT_UpgradingBuilding upgrading = new KCT_UpgradingBuilding(facilityType, facilityID, oldLevel + 1, oldLevel, facilityID.Split('/').Last());

            upgrading.isLaunchpad = facilityID.ToLower().Contains("launchpad");
            if (upgrading.isLaunchpad)
            {
                upgrading.launchpadID = KCT_GameStates.ActiveKSC.ActiveLaunchPadID;
                if (upgrading.launchpadID > 0)
                {
                    upgrading.commonName += KCT_GameStates.ActiveKSC.ActiveLPInstance.name;
                }
            }

            if (!upgrading.AlreadyInProgress())
            {
                float cost = getMember <float>("upgradeCost");

                if (Funding.CanAfford(cost))
                {
                    Funding.Instance.AddFunds(-cost, TransactionReasons.Structures);
                    KCT_GameStates.ActiveKSC.KSCTech.Add(upgrading);
                    upgrading.SetBP(cost);
                    upgrading.cost = cost;

                    ScreenMessages.PostScreenMessage("Facility upgrade requested!", 4.0f, ScreenMessageStyle.UPPER_CENTER);
                    KCTDebug.Log($"Facility {facilityID} upgrade requested to lvl {oldLevel + 1} for {cost} funds, resulting in a BP of {upgrading.BP}");
                }
                else
                {
                    KCTDebug.Log("Couldn't afford to upgrade.");
                    ScreenMessages.PostScreenMessage("Not enough funds to upgrade facility!", 4.0f, ScreenMessageStyle.UPPER_CENTER);
                }
            }
            else if (oldLevel + 1 != upgrading.currentLevel)
            {
                ScreenMessages.PostScreenMessage("Facility is already being upgraded!", 4.0f, ScreenMessageStyle.UPPER_CENTER);
                KCTDebug.Log($"Facility {facilityID} tried to upgrade to lvl {oldLevel + 1} but already in list!");
            }
        }
 private void CheckForTooManyFavourites()
 {
     //if we try and save too many at once silverlight throws an "too large" exception.  set the max using the const. 150 should be enough.
     if (mFilteredQuickDocuments.Count > MaxFav)
     {
         var errors = new List<string> { string.Format("Added the first {0} items of {1} to Favourites.  This is the maximum that can be saved at once.", MaxFav, mFilteredQuickDocuments.Count) };
         var errorDialog = new PopupDialog(PopupDialogType.Information, Utils.DisplayErrorMessages(errors));
         errorDialog.Show();
     }
 }
 private void Button_Confirm_Click(object sender, RoutedEventArgs e)
 {
     PopupDialog.OnConfirmInvoke();
     PopupDialog.Close();
 }
        private void Save(TimesheetDialog view)
        {
            if (!HasErrors())
            {
                mTimesheet.LastModifiedByUserId = CMS.User.Id;
                mTimesheet.LastModifiedDate = DateTime.Now;

                mSavingTimesheet = true;
                OkButtonCommand.RaiseCanExecuteChanged();
                SubmitButtonCommand.RaiseCanExecuteChanged();

                var cee = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                cee.SaveTimesheetCompleted += (s, e) =>
                {
                    if (e.Result.HasErrors)
                    {
                        var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(e.Result.ServerErrorMessages));
                        errorDialog.Show();
                        mSavingTimesheet = false;
                        OkButtonCommand.RaiseCanExecuteChanged();
                        SubmitButtonCommand.RaiseCanExecuteChanged();
                    }
                    else
                    {
                        view.Timesheet = mTimesheet;
                        view.DialogResult = true;
                    }
                };
                cee.SaveTimesheetAsync(mTimesheet);
            }
        }
        public static void PopUpVesselError(List <BuildListVessel> errored)
        {
            DialogGUIBase[] options = new DialogGUIBase[2];
            options[0] = new DialogGUIButton("Understood", () => { });
            options[1] = new DialogGUIButton("Delete Vessels", () =>
            {
                foreach (BuildListVessel blv in errored)
                {
                    blv.RemoveFromBuildList();
                    Utilities.AddFunds(blv.GetTotalCost(), TransactionReasons.VesselRollout);
                    //remove any associated recon_rollout
                }
            });

            string txt        = "The following KCT vessels contain missing or invalid parts and have been quarantined. Either add the missing parts back into your game or delete the vessels. A file containing the ship names and missing parts has been added to your save folder.\n";
            string txtToWrite = "";

            foreach (BuildListVessel blv in errored)
            {
                txt        += blv.ShipName + "\n";
                txtToWrite += blv.ShipName + "\n";
                txtToWrite += string.Join("\n", blv.GetMissingParts());
                txtToWrite += "\n\n";
            }

            //make new file for missing ships
            string filename = KSPUtil.ApplicationRootPath + "/saves/" + HighLogic.SaveFolder + "/missingParts.txt";

            File.WriteAllText(filename, txtToWrite);

            //remove all rollout and recon items since they're invalid without the ships
            foreach (BuildListVessel blv in errored)
            {
                //remove any associated recon_rollout
                foreach (KSCItem ksc in KCTGameStates.KSCs)
                {
                    for (int i = 0; i < ksc.Recon_Rollout.Count; i++)
                    {
                        ReconRollout rr = ksc.Recon_Rollout[i];
                        if (rr.AssociatedID == blv.Id.ToString())
                        {
                            ksc.Recon_Rollout.Remove(rr);
                            i--;
                        }
                    }

                    for (int i = 0; i < ksc.AirlaunchPrep.Count; i++)
                    {
                        AirlaunchPrep ap = ksc.AirlaunchPrep[i];
                        if (ap.AssociatedID == blv.Id.ToString())
                        {
                            ksc.AirlaunchPrep.Remove(ap);
                            i--;
                        }
                    }
                }
            }

            var diag = new MultiOptionDialog("missingPartsPopup", txt, "Vessels Contain Missing Parts", null, options);

            PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), diag, false, HighLogic.UISkin);
        }
        private void RemoveMobilePlantComponentTypeProperty(NodeView nodeView)
        {
            string message = String.Format("Delete Component Type Property {0} ?", nodeView.Name);
            PopupDialog popupDialog = new PopupDialog(PopupDialogType.ConfirmDelete, message);
            popupDialog.Show();
            popupDialog.Closed +=
                (s, e) =>
                {
                    if (popupDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {
                        CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                        EventHandler<RemoveMobilePlantComponentTypePropertyCompletedEventArgs> deleteCompleted = null;
                        deleteCompleted = (s2, eventArgs) =>
                        {
                            string error = eventArgs.Result;

                            if (string.IsNullOrEmpty(error))
                            {
                                nodeView.Parent.Children.Remove(nodeView);
                                Utils.HideSpinner(nodeView);
                                nodeView.Parent.Sort();
                            }
                            else
                            {
                                var errorDialog = new PopupDialog(PopupDialogType.Error, error);
                                errorDialog.Show();
                            }

                            cmsWebServiceClient.RemoveMobilePlantComponentTypePropertyCompleted -= deleteCompleted;
                        };

                        cmsWebServiceClient.RemoveMobilePlantComponentTypePropertyCompleted += deleteCompleted;
                        cmsWebServiceClient.RemoveMobilePlantComponentTypePropertyAsync(nodeView.Id);
                    }
                };
        }
        /// <summary>
        ///   Called when [application launcher true].
        /// </summary>
        private void OnAppLauncherTrue()
        {
            const float q = 0.5f;
            const float w = 500f;
            const float h = 28f;
            const float v = 14f;

            DebugLog(m: "OnAppLauncherTrue()");

            OnAppLauncherFalse(); // make sure it's closed

            var components = new List <DialogGUIBase> {
                new DialogGUISpace(v: v)
            };
            var btm = new DialogGUIHorizontalLayout(new DialogGUIFlexibleSpace());


            if (!GameSettings.ADVANCED_TWEAKABLES)
            {
                components.Add(
                    item: new DialogGUIHorizontalLayout(new DialogGUILabel(message: "'Advanced Tweakables' needs to be enabled.\nClick the button below to enable it."))
                    );

                components.Add(
                    item: new DialogGUIHorizontalLayout(
                        new DialogGUIButton(
                            optionText: "Enable 'Advanced Tweakables'",
                            onSelected: () =>
                {
                    GameSettings.ADVANCED_TWEAKABLES = true;
                    GameSettings.SaveSettings();
                    OnAppLauncherFalse();
                    OnAppLauncherTrue();
                },
                            w: -1f,
                            h: h,
                            dismissOnSelect: false
                            ),
                        new DialogGUISpace(v: -1f)
                        )
                    );
                goto SPAWN; // dirty kludge, I know...
            }

            var top = new DialogGUIHorizontalLayout(
                new DialogGUISpace(v: v),
                new DialogGUIToggleButton(
                    set: Settings.Instance.ModEnabled,
                    lbel: "Enable Full AutoStrut",
                    selected: b =>
            {
                Settings.Instance.ModEnabled = b;
                OnAppLauncherFalse();
                OnAppLauncherTrue();
            },
                    w: -1f,
                    h: h
                    )
                );

            components.Add(item: top);

            if (!Settings.Instance.ModEnabled)
            {
                components.Add(
                    item: new DialogGUIHorizontalLayout(
                        new DialogGUIFlexibleSpace(),
                        new DialogGUILabel(message: "Full AutoStrut is currently disabled."),
                        new DialogGUIFlexibleSpace()
                        )
                    );
                components.Add(item: new DialogGUISpace(v: v));
                top.AddChild(child: new DialogGUISpace(v: v));
                goto SPAWN; // dirty kludge, I know...
            }

            top.AddChild(
                child: new DialogGUIToggleButton(
                    set: Settings.Instance.RigidAttachment,
                    lbel: "Use Rigid Attachment",
                    selected: b => Settings.Instance.RigidAttachment = b,
                    w: -1f,
                    h: h
                    )
                );

            _applyChildren = new DialogGUIToggleButton(
                set: Settings.Instance.ApplyChildren,
                lbel: "Re-Apply to child parts",
                selected: b => Settings.Instance.ApplyChildren = b,
                w: -1f,
                h: h
                );

            top.AddChild(child: _applyChildren);
            top.AddChild(child: new DialogGUISpace(v: v));

            components.Add(item: new DialogGUISpace(v: v));
            components.Add(
                item: new DialogGUIHorizontalLayout(new DialogGUIFlexibleSpace(), new DialogGUIBox(message: "AutoStrut", w: w, h: h), new DialogGUIFlexibleSpace())
                );

            components.Add(
                item: new DialogGUIHorizontalLayout(
                    new DialogGUISpace(v: v),
                    new DialogGUIToggleGroup(
                        new DialogGUIToggleButton(
                            set: Settings.Instance.AutoSelect == false && Settings.Instance.AutoStrutMode == Part.AutoStrutMode.Off,
                            lbel: "Off",
                            selected: b =>
            {
                if (!b)
                {
                    return;
                }
                Settings.Instance.AutoSelect    = false;
                Settings.Instance.AutoStrutMode = Part.AutoStrutMode.Off;
            },
                            w: -1f,
                            h: h
                            ),
                        new DialogGUIToggleButton(
                            set: Settings.Instance.AutoSelect == false && Settings.Instance.AutoStrutMode == Part.AutoStrutMode.Root,
                            lbel: "Root",
                            selected: b =>
            {
                if (!b)
                {
                    return;
                }
                Settings.Instance.AutoSelect    = false;
                Settings.Instance.AutoStrutMode = Part.AutoStrutMode.Root;
            },
                            w: -1f,
                            h: h
                            ),
                        new DialogGUIToggleButton(
                            set: Settings.Instance.AutoSelect == false && Settings.Instance.AutoStrutMode == Part.AutoStrutMode.Heaviest,
                            lbel: "Heaviest",
                            selected: b =>
            {
                if (!b)
                {
                    return;
                }
                Settings.Instance.AutoSelect    = false;
                Settings.Instance.AutoStrutMode = Part.AutoStrutMode.Heaviest;
            },
                            w: -1f,
                            h: h
                            ),
                        new DialogGUIToggleButton(
                            set: Settings.Instance.AutoSelect == false && Settings.Instance.AutoStrutMode == Part.AutoStrutMode.Grandparent,
                            lbel: "Grandparent",
                            selected: b =>
            {
                if (!b)
                {
                    return;
                }
                Settings.Instance.AutoSelect    = false;
                Settings.Instance.AutoStrutMode = Part.AutoStrutMode.Grandparent;
            },
                            w: -1f,
                            h: h
                            ),
                        new DialogGUIToggleButton(set: Settings.Instance.AutoSelect, lbel: "Automatic", selected: b => Settings.Instance.AutoSelect = b, w: -1f, h: h)
                        ),
                    new DialogGUISpace(v: v)
                    )
                );

            components.Add(item: new DialogGUISpace(v: v));

            components.Add(item: new DialogGUIHorizontalLayout(new DialogGUIBox(message: "Same Vessel Interaction", w: w, h: h)));
            components.Add(
                item: new DialogGUIHorizontalLayout(
                    new DialogGUISpace(v: v),
                    new DialogGUIToggleGroup(
                        new DialogGUIToggleButton(
                            set: Settings.Instance.AutomaticSameVesselInteraction == false && Settings.Instance.SameVesselInteraction == false,
                            lbel: "Off",
                            selected: b =>
            {
                if (!b)
                {
                    return;
                }
                Settings.Instance.AutomaticSameVesselInteraction = false;
                Settings.Instance.SameVesselInteraction          = false;
            },
                            w: -1F,
                            h: h
                            ),
                        new DialogGUIToggleButton(
                            set: Settings.Instance.AutomaticSameVesselInteraction == false && Settings.Instance.SameVesselInteraction,
                            lbel: "On",
                            selected: b =>
            {
                if (!b)
                {
                    return;
                }
                Settings.Instance.AutomaticSameVesselInteraction = false;
                Settings.Instance.SameVesselInteraction          = true;
            },
                            w: -1F,
                            h: h
                            ),
                        new DialogGUIToggleButton(
                            set: Settings.Instance.AutomaticSameVesselInteraction,
                            lbel: "Automatic",
                            selected: b =>
            {
                Settings.Instance.AutomaticSameVesselInteraction = b;
                Settings.Instance.SameVesselInteraction          = false;
            },
                            w: -1F,
                            h: h
                            )
                        ),
                    new DialogGUISpace(v: v)
                    )
                );


            components.Add(item: new DialogGUISpace(v: v));


            btm.AddChild(
                child: new DialogGUIButton(
                    optionText: "Apply to all",
                    onSelected: () => SetPartOptions(
                        p: EditorLogic.RootPart,
                        autoStrutMode: Settings.Instance.AutoStrutMode,
                        isRoboticHierarchy: EditorLogic.RootPart.IsRoboticCompatible(),
                        applyChildren: true
                        ),
                    EnabledCondition: null,
                    w: -1f,
                    h: h,
                    dismissOnSelect: false
                    )
                );

            btm.AddChild(child: new DialogGUISpace(v: v));
            btm.AddChild(
                child: new DialogGUIButton(
                    optionText: "Reset Settings",
                    onSelected: () =>
            {
                Settings.Instance.Reset();
                OnAppLauncherFalse();
                OnAppLauncherTrue();
            },
                    EnabledCondition: null,
                    w: -1f,
                    h: h,
                    dismissOnSelect: false
                    )
                );
            btm.AddChild(child: new DialogGUISpace(v: v));

SPAWN:      // dirty kludge, I know...
            btm.AddChild(
                child: new DialogGUIButton(optionText: "Close", onSelected: OnAppLauncherFalse, EnabledCondition: null, w: -1f, h: h, dismissOnSelect: false)
                );
            btm.AddChild(child: new DialogGUIFlexibleSpace());

            components.Add(item: btm);
            components.Add(item: new DialogGUISpace(v: v));

            _dialog = PopupDialog.SpawnPopupDialog(
                anchorMin: new Vector2(x: q, y: q),
                anchorMax: new Vector2(x: q, y: q),
                dialog: new MultiOptionDialog(
                    name: "FULL~AUTO~STRUT",
                    msg: string.Empty,
                    windowTitle: "Full AutoStrut v" + AssemblyVersion,
                    skin: HighLogic.UISkin,
                    rct: new Rect(x: Settings.Instance.PosX * GameSettings.UI_SCALE, y: Settings.Instance.PosY * GameSettings.UI_SCALE, width: w, height: -1f),
                    options: new DialogGUIVerticalLayout(list: components.ToArray())
                    ),
                persistAcrossScenes: false,
                skin: HighLogic.UISkin,
                isModal: false
                );
        }
        private void WarnAlarmLostOnComponentTypeChange()
        {
            if (SelectedType == null) return;

            var getAlarmPropertyValuesRequiredForComponentTypeTask = DatabaseLoader.GetAlarmPropertyValuesRequiredForComponentType(SelectedType.Id);

            var tasks = new List<Task> { getAlarmPropertyValuesRequiredForComponentTypeTask };

            Task.Factory.ContinueWhenAll(tasks.ToArray(), xx =>
            {
                CMS.UiFactory.StartNew(() =>
                {
                    List<int> newIds = (from g in getAlarmPropertyValuesRequiredForComponentTypeTask.Result select g.ControlSystemAlarmPropertyId).ToList();
                    List<int> oldIds = (from g in mClone.ControlSystemAlarmPropertyValues select g.ControlSystemAlarmPropertyId).ToList();

                    var dicarding = oldIds.Except(newIds).ToArray();

                    List<ControlSystemAlarmPropertyValue> discarding = (from x in mClone.ControlSystemAlarmPropertyValues where dicarding.Contains(x.ControlSystemAlarmPropertyId) select x).ToList();

                    if (discarding.Any())
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine("The following Alarms will be discarded.");
                        sb.AppendLine("");
                        foreach (ControlSystemAlarmPropertyValue pv in discarding)
                        {
                            sb.AppendLine(pv.ControlSystemAlarmProperty.FormattedName);
                        }

                        PopupDialog dlg = new PopupDialog(PopupDialogType.ConfirmMessage, sb.ToString(), "Confirm to Discard Alarms due to the Type Change", 500, 250);
                        dlg.Show();
                        dlg.Closed += (s2, e2) =>
                        {
                            if (dlg.DialogResult.HasValue && dlg.DialogResult.Value)
                            {
                                mControlSystemComponent.ControlSystemAlarmPropertyValues.Clear();

                                foreach (var propertyValue in getAlarmPropertyValuesRequiredForComponentTypeTask.Result)
                                {
                                    var match = (from x in mClone.ControlSystemAlarmPropertyValues where x.ControlSystemAlarmPropertyId == propertyValue.ControlSystemAlarmPropertyId select x).FirstOrDefault();

                                    if (match==null)
                                    {
                                        mControlSystemComponent.ControlSystemAlarmPropertyValues.Add(propertyValue);
                                    }
                                    else
                                    {
                                        mControlSystemComponent.ControlSystemAlarmPropertyValues.Add(match);
                                    }
                                }
                            }
                            else
                            {
                                mControlSystemComponent.ControlSystemComponentType = mClone.ControlSystemComponentType;
                                mControlSystemComponent.ControlSystemComponentTypeId = mClone.ControlSystemComponentTypeId;
                            }

                            RaisePropertyChanged("SelectedType");
                        };
                    }
                });

            });
        }
Exemple #42
0
        public tabs toolingTab()
        {
            MaybeUpdate();
            currentToolingType = null;
            GUILayout.BeginHorizontal();
            try {
                GUILayout.FlexibleSpace();
                GUILayout.Label("Tooling Types", HighLogic.Skin.label);
                GUILayout.FlexibleSpace();
            } finally {
                GUILayout.EndHorizontal();
            }
            int counter = 0;

            GUILayout.BeginHorizontal();
            try {
                foreach (string type in ToolingDatabase.toolings.Keys)
                {
                    if (counter % 3 == 0 && counter != 0)
                    {
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal();
                    }
                    counter++;
                    if (GUILayout.Button(type))
                    {
                        currentToolingType = type;
                    }
                }
            } finally {
                GUILayout.EndHorizontal();
            }

            if (untooledParts.Count > 0)
            {
                GUILayout.BeginHorizontal();
                try {
                    GUILayout.Label("Untooled Parts:", HighLogic.Skin.label, GUILayout.Width(312));
                    GUILayout.Label("Tooling cost", rightLabel, GUILayout.Width(72));
                    GUILayout.Label("Untooled", rightLabel, GUILayout.Width(72));
                    GUILayout.Label("Tooled", rightLabel, GUILayout.Width(72));
                } finally {
                    GUILayout.EndHorizontal();
                }
                untooledTypesScroll = GUILayout.BeginScrollView(untooledTypesScroll, GUILayout.Height(204), GUILayout.Width(572));
                try {
                    foreach (untooledPart uP in untooledParts)
                    {
                        GUILayout.BeginHorizontal();
                        try
                        {
                            GUILayout.Label(uP.name, boldLabel, GUILayout.Width(312));
                            GUILayout.Label(uP.toolingCost.ToString("N0") + "f", rightLabel, GUILayout.Width(72));
                            var untooledExtraCost = GetUntooledExtraCost(uP);
                            GUILayout.Label(uP.totalCost.ToString("N0") + "f", rightLabel, GUILayout.Width(72));
                            GUILayout.Label((uP.totalCost - untooledExtraCost).ToString("N0") + "f", rightLabel, GUILayout.Width(72));
                        }
                        finally {
                            GUILayout.EndHorizontal();
                        }
                    }
                } finally {
                    GUILayout.EndScrollView();
                }
                GUILayout.BeginHorizontal();
                try {
                    var allTooledCost = EditorLogic.fetch.ship.GetShipCosts(out _, out _) - untooledParts.Slinq().Select(p => GetUntooledExtraCost(p)).Sum();
                    GUILayout.Label("Total vessel cost if all parts are tooled: " + allTooledCost.ToString("N0"));
                } finally {
                    GUILayout.EndHorizontal();
                }
                GUILayout.BeginHorizontal();
                try {
                    if (GUILayout.Button("Tool All"))
                    {
                        var untooledParts = EditorLogic.fetch.ship.Parts.Slinq().SelectMany(p => p.FindModulesImplementing <ModuleTooling>().Slinq())
                                            .Where(mt => !mt.IsUnlocked())
                                            .ToList();

                        float totalToolingCost = ModuleTooling.PurchaseToolingBatch(untooledParts, isSimulation: true);
                        bool  canAfford        = Funding.Instance.Funds >= totalToolingCost;
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                     new Vector2(0.5f, 0.5f),
                                                     new MultiOptionDialog(
                                                         "ConfirmAllToolingsPurchase",
                                                         "Tooling for all untooled parts will cost " + totalToolingCost.ToString("N0") + " funds.",
                                                         "Tooling Purchase",
                                                         HighLogic.UISkin,
                                                         new Rect(0.5f, 0.5f, 150f, 60f),
                                                         new DialogGUIFlexibleSpace(),
                                                         new DialogGUIVerticalLayout(
                                                             new DialogGUIFlexibleSpace(),
                                                             new DialogGUIButton(canAfford ? "Purchase All Toolings" : "Can't Afford",
                                                                                 () =>
                        {
                            if (canAfford)
                            {
                                ModuleTooling.PurchaseToolingBatch(untooledParts);
                                untooledParts.ForEach(mt =>
                                {
                                    mt.Events["ToolingEvent"].guiActiveEditor = false;
                                });
                                GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
                            }
                        }, 140.0f, 30.0f, true),
                                                             new DialogGUIButton("Close", () => { }, 140.0f, 30.0f, true)
                                                             )),
                                                     false,
                                                     HighLogic.UISkin);
                    }
                } finally {
                    GUILayout.EndHorizontal();
                }
            }
            return(currentToolingType == null ? tabs.Tooling : tabs.ToolingType);
        }
        private void DeleteModel(NodeView nodeView)
        {
            var message = string.Format("Delete Model {0} ?", nodeView.Name);
            var popupDialog = new PopupDialog(PopupDialogType.ConfirmDelete, message);
            popupDialog.Show();
            popupDialog.Closed +=
                (s, e) =>
                {
                    if (popupDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {
                        var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                        EventHandler<DeleteModelCompletedEventArgs> deleteCompleted = null;
                        deleteCompleted = (s2, eventArgs) =>
                        {
                            var ds = eventArgs.Result;

                            if (!ds.HasErrors)
                            {
                                nodeView.Parent.Children.Remove(nodeView);
                            }
                            else
                            {
                                var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(ds.ServerErrorMessages));
                                errorDialog.Show();
                            }
                            cmsWebServiceClient.DeleteModelCompleted -= deleteCompleted;
                        };

                        cmsWebServiceClient.DeleteModelCompleted += deleteCompleted;
                        cmsWebServiceClient.DeleteModelAsync(nodeView.Id);
                    }
                };
        }
Exemple #44
0
        protected void Start()
        {
            try
            {
                // Log some information that might be of interest when debugging
                Utilities.Log(modName + " - KSPUtil.ApplicationRootPath = " + KSPUtil.ApplicationRootPath);
                Utilities.Log(modName + " - GameDatabase.Instance.PluginDataFolder = " + GameDatabase.Instance.PluginDataFolder);
                Utilities.Log(modName + " - Assembly.GetExecutingAssembly().Location = " + Assembly.GetExecutingAssembly().Location);
                Utilities.Log(modName + " - Using 64-bit? " + (IntPtr.Size == 8));

                // Search for this mod's DLL existing in the wrong location. This will also detect duplicate copies because only one can be in the right place.
                var assemblies       = AssemblyLoader.loadedAssemblies.Where(a => a.assembly.GetName().Name == Assembly.GetExecutingAssembly().GetName().Name).Where(a => a.url != expectedPath);
                var loadedAssemblies = assemblies as AssemblyLoader.LoadedAssembly[] ?? assemblies.ToArray();
                if (loadedAssemblies.Any())
                {
                    var    badPaths       = loadedAssemblies.Select(a => a.path).Select(p => Uri.UnescapeDataString(new Uri(Path.GetFullPath(KSPUtil.ApplicationRootPath)).MakeRelativeUri(new Uri(p)).ToString().Replace('/', Path.DirectorySeparatorChar)));
                    string badPathsString = String.Join("\n", badPaths.ToArray());
                    Utilities.Log(modName + " - Incorrectly installed, bad paths:\n" + badPathsString);
                    PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Incorrect " + modName + " Installation",
                                                 modName + " has been installed incorrectly and will not function properly. All files should be located in KSP/GameData/" + expectedPath +
                                                 ". Do not move any files from inside that folder.\n\nPlease Remove all old installations and invalid files, as follows.\n\nIncorrect path(s):\n" + badPathsString,
                                                 "OK", false, HighLogic.UISkin);
                }

                // Check for Raster Prop Monitor, If installed must also have Module Manager Installed
                if (AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.StartsWith("RasterPropMonitor")))
                {
                    if (!AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.StartsWith("ModuleManager") && a.url == ""))
                    {
                        Utilities.Log(modName + " - Missing or incorrectly installed RPM & ModuleManager.");
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Missing Module Manager",
                                                     modName + " requires the Module Manager mod in order to function properly with Raster Prop Monitor mod Installed.\n\nPlease download from http://forum.kerbalspaceprogram.com/threads/55219 and copy to the KSP/GameData/ directory.",
                                                     "OK", false, HighLogic.UISkin);
                    }
                }

                /*
                 * // Check for Module Manager
                 * if (!AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.StartsWith("ModuleManager") && a.url == ""))
                 * {
                 *  Utilities.Log("DeepFreeze - Missing or incorrectly installed ModuleManager.");
                 *  PopupDialog.SpawnPopupDialog("Missing Module Manager",
                 *      modName + " requires the Module Manager mod in order to function properly.\n\nPlease download from http://forum.kerbalspaceprogram.com/threads/55219 and copy to the KSP/GameData/ directory.",
                 *      "OK", false, HighLogic.Skin);
                 * }
                 */
                // Is AddonController installed? (It could potentially cause problems.)
                if (AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.StartsWith("AddonController")))
                {
                    Utilities.Log("AddonController is installed");
                }

                // Is Compatibility Popup Blocker installed? (It could potentially cause problems.)
                if (AssemblyLoader.loadedAssemblies.Any(a => a.assembly.GetName().Name.StartsWith("popBlock")))
                {
                    Utilities.Log("Compatibility Popup Blocker is installed");
                }

                //CleanupOldVersions();
            }
            catch (Exception ex)
            {
                Utilities.Log("DeepFreeze - Caught an exception:\n" + ex.Message + "\n" + ex.StackTrace);
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Incorrect " + modName + " Installation",
                                             "A very serious error has occurred while checking the installation of " + modName + ".\n\n" +
                                             "You need to\n" +
                                             "  (1) shut down KSP,\n" +
                                             "  (2) send a complete copy of the entire log file to the mod developer\n" +
                                             "  (3) completely delete and re-install " + modName,
                                             "OK", false, HighLogic.UISkin);
            }
        }
        private void EditControlSystemComponentTypeAlarmProperty(NodeView nodeView)
        {
            var dialog = new AddEditExistingControlSystemComponentAlarmPropertyDialog(nodeView.Id) { Title = "Edit ControlSystem Component Alarm Property" };

            dialog.Closed +=
                (s1, e1) =>
                {
                    if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
                    {
                        var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                        EventHandler<SaveControlSystemComponentTypeAlarmPropertyCompletedEventArgs> addCompleted = null;
                        addCompleted = (s2, eventArgs) =>
                        {
                            if (eventArgs.Result.HasErrors)
                            {
                                var popup = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(eventArgs.Result.ServerErrorMessages));
                                popup.Show();
                                return;
                            }

                            var componentTypeAlarmProperty = eventArgs.Result.EntityResult;
                            if (componentTypeAlarmProperty != null)
                            {
                                nodeView.Name = componentTypeAlarmProperty.ControlSystemAlarmProperty.Name;
                                nodeView.Description = componentTypeAlarmProperty.ControlSystemAlarmProperty.Description;
                                nodeView.SortField = componentTypeAlarmProperty.Ordinal.ToString();
                            }
                            cmsWebServiceClient.SaveControlSystemComponentTypeAlarmPropertyCompleted -= addCompleted;
                            nodeView.Parent.Sort();
                        };
                        cmsWebServiceClient.SaveControlSystemComponentTypeAlarmPropertyCompleted += addCompleted;
                        cmsWebServiceClient.SaveControlSystemComponentTypeAlarmPropertyAsync(dialog.ControlSystemComponentTypeAlarmProperty);
                    }
                };
            dialog.Show();
        }
 private void ShowGui()
 {
     if (settingsMenu == null)
     {
         InitValues();
         settingsMenu = PopupDialog.SpawnPopupDialog(
             new Vector2(0.5f, 0.5f),
             new Vector2(0.5f, 0.5f),
             new MultiOptionDialog(
                 "MASSettings-Config",
                 Localizer.GetStringByTag("#MAS_Settings_Caption"),
                 Localizer.GetStringByTag("#MAS_Settings_Title"),
                 HighLogic.UISkin,
                 new Rect(0.5f, 0.5f, 300.0f, 60.0f),
                 new DialogGUIFlexibleSpace(),
                 new DialogGUIVerticalLayout(
                     new DialogGUIHorizontalLayout(
                         new DialogGUIVerticalLayout(
                             new DialogGUILabel(Localizer.GetStringByTag("#MAS_Settings_General_Section"), true),
                             new DialogGUISpace(10.0f),
                             new DialogGUIToggle(verboseLogging, Localizer.GetStringByTag("#MAS_Settings_Verbose_Logging"), (bool newValue) => { verboseLogging = newValue; }),
                             new DialogGUISpace(5.0f),
                             new DialogGUILabel(delegate { return(Localizer.Format("#MAS_Settings_Lua_Update_Priority", luaUpdatePriority.ToString())); }, true),
                             new DialogGUISlider(delegate { return((float)luaUpdatePriority); }, 1.0f, 4.0f, true, 140.0f, 30.0f, (float newValue) => { luaUpdatePriority = (int)newValue; }),
                             new DialogGUISpace(5.0f),
                             new DialogGUILabel(delegate { return(Localizer.Format("#MAS_Settings_Camera_Texture_Size", (1 << cameraTextureScale).ToString())); }, true),
                             new DialogGUISlider(delegate { return((float)cameraTextureScale); }, 0.0f, 2.0f, true, 140.0f, 30.0f, (float newValue) => { cameraTextureScale = (int)newValue; }),
                             new DialogGUISpace(5.0f),
                             new DialogGUIFlexibleSpace()
                             ),
                         new DialogGUIVerticalLayout(
                             new DialogGUILabel(Localizer.GetStringByTag("#MAS_Settings_RadioNav_Section"), true),
                             new DialogGUISpace(10.0f),
                             new DialogGUILabel(delegate { return(Localizer.Format("#MAS_Settings_Radio_Propagation", generalPropagation.ToString("P0"))); }, true),
                             new DialogGUISlider(delegate { return(generalPropagation); }, 1.0f, 3.0f, false, 140.0f, 30.0f, (float newValue) => { generalPropagation = newValue; }),
                             new DialogGUISpace(5.0f),
                             new DialogGUILabel(delegate { return(Localizer.Format("#MAS_Settings_NDB_Propagation", NDBPropagation.ToString("P0"))); }, true),
                             new DialogGUISlider(delegate { return(NDBPropagation); }, 1.0f, 2.0f, false, 140.0f, 30.0f, (float newValue) => { NDBPropagation = newValue; }),
                             new DialogGUISpace(5.0f),
                             new DialogGUILabel(delegate { return(Localizer.Format("#MAS_Settings_VOR_Propagation", VORPropagation.ToString("P0"))); }, true),
                             new DialogGUISlider(delegate { return(VORPropagation); }, 1.0f, 2.0f, false, 140.0f, 30.0f, (float newValue) => { VORPropagation = newValue; }),
                             new DialogGUISpace(5.0f),
                             new DialogGUILabel(delegate { return(Localizer.Format("#MAS_Settings_DME_Propagation", DMEPropagation.ToString("P0"))); }, true),
                             new DialogGUISlider(delegate { return(DMEPropagation); }, 1.0f, 2.0f, false, 140.0f, 30.0f, (float newValue) => { DMEPropagation = newValue; }),
                             new DialogGUIFlexibleSpace()
                             )
                         ),
                     new DialogGUIHorizontalLayout(
                         new DialogGUIFlexibleSpace(),
                         new DialogGUIButton(Localizer.GetStringByTag("#autoLOC_174783"), // Cancel
                                             delegate
         {
             onAppLauncherHide();
             appLauncherButton.SetFalse(false);
         }, 140.0f, 30.0f, false),
                         new DialogGUIButton(Localizer.GetStringByTag("#autoLOC_174814"), // OK
                                             delegate
         {
             onAppLauncherHide();
             appLauncherButton.SetFalse(false);
             ApplyChanges();
         }, 140.0f, 30.0f, false)
                         )
                     )
                 ),
             false,
             HighLogic.UISkin);
     }
 }
        private void RemoveInterlockTypeProperty(NodeView nodeView)
        {
            var confirmDialog = new PopupDialog(PopupDialogType.ConfirmDelete, string.Format("Delete property '{0}'?", nodeView.Name));
            confirmDialog.Show();
            confirmDialog.Closed +=
                (s, e) =>
                {
                    if (confirmDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {
                        var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                        EventHandler<RemoveInterlockTypePropertyCompletedEventArgs> deleteCompleted = null;
                        deleteCompleted = (s2, eventArgs) =>
                        {
                            var error = eventArgs.Result;

                            if (string.IsNullOrEmpty(error))
                            {
                                nodeView.Parent.Children.Remove(nodeView);
                            }
                            else
                            {
                                var errorDialog = new PopupDialog(PopupDialogType.Error, error);
                                errorDialog.Show();
                            }

                            cmsWebServiceClient.RemoveInterlockTypePropertyCompleted -= deleteCompleted;
                        };

                        cmsWebServiceClient.RemoveInterlockTypePropertyCompleted += deleteCompleted;
                        cmsWebServiceClient.RemoveInterlockTypePropertyAsync(nodeView.Id);
                    }
                };
        }
Exemple #48
0
        /// <summary>
        /// This function will do one of two things: if the active vessel
        /// isn't an eva kerbal, it will choose a kerbal at random from
        /// the crew and send them on eva (unless the conditions outside
        /// would make it dangerous, in which case player will receive
        /// a dialog instead).
        ///
        /// On the other hand, if the active vessel is an eva kerbal, it
        /// will deploy the experiment itself.
        /// </summary>
        /// <returns></returns>
        public override bool Deploy()
        {
            if (!Available || !IsReadyOnboard)
            {
                Log.Error("Cannot deploy eva experiment {0}; Available = {1}, Onboard = {2}, experiment = {3}", Available, IsReadyOnboard, experiment.id);
                return(false);
            }

            if (FlightGlobals.ActiveVessel == null)
            {
                Log.Error("Deploy -- invalid active vessel");
                return(false);
            }


            // the current vessel IS NOT an eva'ing Kerbal, so
            // find a kerbal and dump him into space
            if (!FlightGlobals.ActiveVessel.isEVA)
            {
                // check conditions outside
                Log.Warning("Current static pressure: {0}", FlightGlobals.getStaticPressure());

                if (FlightGlobals.getStaticPressure() > Settings.Instance.EvaAtmospherePressureWarnThreshold)
                {
                    if (FlightGlobals.ActiveVessel.GetSrfVelocity().magnitude > Settings.Instance.EvaAtmosphereVelocityWarnThreshold)
                    {
                        Log.Debug("setting up dialog options to warn player about eva risk");

                        var options = new DialogOption[2];

                        options[0] = new DialogOption("Science is worth a little risk", new Callback(OnConfirmEva));
                        options[1] = new DialogOption("No, it would be a PR nightmare", null);

                        var dlg = new MultiOptionDialog("It looks dangerous out there. Are you sure you want to send someone out? They might lose their grip!", "Dangerous Condition Alert", Settings.Skin, options);


                        PopupDialog.SpawnPopupDialog(dlg, false, Settings.Skin);
                        return(true);
                    }
                }



                if (!ExpelCrewman())
                {
                    Log.Error("{0}.Deploy - Did not successfully send kerbal out the airlock.  Hatch might be blocked.", GetType().Name);
                    return(false);
                }

                return(true);
            }
            else
            {
                // The vessel is indeed a kerbalEva, so we can expect to find the
                // appropriate science module now
                var evas = FlightGlobals.ActiveVessel.FindPartModulesImplementing <ModuleScienceExperiment>();
                foreach (var exp in evas)
                {
                    if (!exp.Deployed && exp.experimentID == experiment.id)
                    {
                        exp.DeployExperiment();
                        break;
                    }
                }

                return(true);
            }
        }
        public void DeleteButtonHandler(object parameter)
        {
            List<IssueFile> selected = (from x in Attachments where x.Checked select x).ToList();

            if (selected.Count == 0)
            {
                return;
            }

            string message = string.Format("Delete selected Files? ({0})", selected.Count);
            var popupDialog = new PopupDialog(PopupDialogType.ConfirmDelete, message);
            popupDialog.Show();
            popupDialog.Closed +=
                (s2, e2) =>
                {
                    if (popupDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {
                        var todelete = new List<IssueFile>();
                        var cantDelete = new List<IssueFile>();
                        foreach (IssueFile attachment in selected)
                        {
                            IssueFile foo = (from x in mIssue.IssueFiles where x.Path == attachment.Path && x.Id == attachment.Id select x).FirstOrDefault();

                            if (CMS.EffectivePrivileges.AdminTab.CanDelete || CMS.EffectivePrivileges.IssueTab.CanDelete || attachment.UploadedById == CMS.User.Id)
                            {
                                todelete.Add(foo);

                            }
                            else
                            {
                                cantDelete.Add(attachment);
                            }
                        }

                        if (cantDelete.Any())
                        {
                            string deleteMessage = String.Format("You dont have permission to delete following items:{0}{1}",
                                Environment.NewLine,
                                string.Join(Environment.NewLine, cantDelete.Select(x => x.Filename).ToArray()));

                            var dialog = new PopupDialog(PopupDialogType.Warning, deleteMessage, "Can not remove");

                            dialog.Show();
                        }

                        //DELETE IS COMPLETE - Save Model
                        var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

                        //Update Modified By so the Revision history user is correct.
                        mIssue.ModifiedById = CMS.User.Id;

                        cmsWebServiceClient.DeleteIssueFilesCompleted += ((sender, args) =>
                        {
                            todelete.ForEach(x => mIssue.IssueFiles.Remove(x));
                            OnCollectionChanged();
                            EventAggregator.GetEvent<PrismEvents.RefreshIssueRevisionHistoryPrismEvent>().Publish(null);
                            RaisePropertyChanged("Attachments");
                        });
                        cmsWebServiceClient.DeleteIssueFilesAsync(todelete);

                    }
                };
        }
 //Exit Dialog implementation
 async Task ShowExitDialog()
 {
     await PopupDialog.ShowPopupDialog("Are you sure you don't want to keep playing?", "Yes, I am", () => ChangeScreen(typeof(MainMenu)), "No, let me play", null);
 }
        private void OkButtonHander(object parameter)
        {
            if (AreAllValid())
            {
                CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

                cmsWebServiceClient.AddIssueTypeSubTypeCompleted += (s, e) =>
                {
                    if (e.Result.HasErrors)
                    {
                        var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(e.Result.ServerErrorMessages));
                        errorDialog.Show();
                    }
                    else
                    {
                        View.IssueSubType = SelectedIssueSubType;
                        View.DialogResult = true;
                    }
                };
                cmsWebServiceClient.AddIssueTypeSubTypeAsync(mIssueType,SelectedIssueSubType);
            }
        }
Exemple #52
0
        private ReloadingDatabaseDialog(ModuleManager parent)
        {
            bool startedReload = false;

            this.parent = parent;

            UISkinDef skinDef           = HighLogic.UISkin;
            UIStyle   centeredTextStyle = new UIStyle()           // FIXME: There must be a smarter way to do that on Unity5, right?
            {
                name          = skinDef.label.name,
                normal        = skinDef.label.normal,
                highlight     = skinDef.label.highlight,
                disabled      = skinDef.label.disabled,
                font          = skinDef.label.font,
                fontSize      = skinDef.label.fontSize,
                fontStyle     = skinDef.label.fontStyle,
                wordWrap      = skinDef.label.wordWrap,
                richText      = skinDef.label.richText,
                alignment     = TextAnchor.UpperCenter,
                clipping      = skinDef.label.clipping,
                lineHeight    = skinDef.label.lineHeight,
                stretchHeight = skinDef.label.stretchHeight,
                stretchWidth  = skinDef.label.stretchWidth,
                fixedHeight   = skinDef.label.fixedHeight,
                fixedWidth    = skinDef.label.fixedWidth
            };

            float totalLoadWeight = GameDatabase.Instance.LoadWeight() + PartLoader.Instance.LoadWeight();

            PopupDialog reloadingDialog = PopupDialog.SpawnPopupDialog(
                new Vector2(0.5f, 0.5f),
                new Vector2(0.5f, 0.5f),
                new MultiOptionDialog(
                    "ModuleManagerReloading",
                    "",
                    "ModuleManager - Reloading Database",
                    skinDef,
                    new Rect(0.5f, 0.5f, 600f, 60f),
                    new DialogGUIFlexibleSpace(),
                    new DialogGUIVerticalLayout(
                        new DialogGUIFlexibleSpace(),
                        new DialogGUILabel(delegate()
            {
                float progressFraction;
                if (!startedReload)
                {
                    progressFraction = 0f;
                    startedReload    = true;
                }
                else if (!GameDatabase.Instance.IsReady() || !PostPatchLoader.Instance.IsReady())
                {
                    progressFraction  = GameDatabase.Instance.ProgressFraction() * GameDatabase.Instance.LoadWeight();
                    progressFraction /= totalLoadWeight;
                }
                else if (!PartLoader.Instance.IsReady())
                {
                    progressFraction  = GameDatabase.Instance.LoadWeight() + (PartLoader.Instance.ProgressFraction() * GameDatabase.Instance.LoadWeight());
                    progressFraction /= totalLoadWeight;
                }
                else
                {
                    progressFraction = 1f;
                }

                return($"Overall progress: {progressFraction:P0}");
            }, centeredTextStyle, expandW : true),
                        new DialogGUILabel(delegate()
            {
                if (!startedReload)
                {
                    return("Starting");
                }
                else if (!GameDatabase.Instance.IsReady())
                {
                    return(GameDatabase.Instance.ProgressTitle());
                }
                else if (!PostPatchLoader.Instance.IsReady())
                {
                    return(PostPatchLoader.Instance.ProgressTitle());
                }
                else if (!PartLoader.Instance.IsReady())
                {
                    return(PartLoader.Instance.ProgressTitle());
                }
                else
                {
                    return("");
                }
            }),
                        new DialogGUISpace(5f),
                        new DialogGUILabel(() => this.parent.patchRunner.Status)
                        )
                    ),
                false,
                skinDef);
        }
        private void MarkIssueAsRestrictedContent(QuickIssue quickIssue)
        {
            var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.MarkIssueAsRestrictedCompleted += (s, e) =>
            {
                if (e.Result)
                {
                    quickIssue.RestrictedContent = true;

                }
                else
                {
                    var dialog = new PopupDialog(PopupDialogType.Error,
                        "Only administrator or users in the distribution list can mark this issue as restricted.",
                        "Restricted Content Issue");
                    dialog.Show();
                }
            };

            cmsWebServiceClient.MarkIssueAsRestrictedAsync(quickIssue.Id, CMS.User.Id);
        }
Exemple #54
0
 public void CloseDialog(PopupDialog pop)
 {
     pop.Dismiss();
 }
Exemple #55
0
        private void OpenIssueTab(QuickIssue issue)
        {
            if (issue == null || !issue.IsActive)
            {
                return;
            }

            if (issue.RestrictedContent)
            {
                //Only allowed users can open restricted Issue
                var cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                cmsWebServiceClient.CanUserOpenRestrictedIssueCompleted += (s, e) =>
                {
                    if (e.Result)
                    {
                        OpenTab(issue);
                    }
                    else
                    {
                        var dialog = new PopupDialog(PopupDialogType.Error,
                            "Access is restricted due to issue content – please contact the System Administrator.",
                            "Restricted Content Issue");
                        dialog.Show();
                    }
                };
                cmsWebServiceClient.CanUserOpenRestrictedIssueAsync(issue.Id, CMS.User.Id);
            }
            else
            {
                OpenTab(issue);
            }
        }
Exemple #56
0
        /// <summary>
        /// Ask for permission from the user.
        /// </summary>
        private void AskForPermission()
        {
            PopupDialog dialog = PopupDialog.SpawnPopupDialog(dialogs["networkRequestPermission"], true, HighLogic.UISkin);

            dialog.OnDismiss = PostPermissionRequest;
        }
        private void OkButtonHandler(object parameter)
        {
            if (CanModify(parameter))
            {
                if (AreAllValid())
                {
                    CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);
                    cmsWebServiceClient.SaveControlSystemAlarmConsequenceCompleted +=
                        (s1, e1) =>
                        {
                            if (e1.Result.HasErrors)
                            {
                                var errorDialog = new PopupDialog(PopupDialogType.Error, Utils.DisplayErrorMessages(e1.Result.ServerErrorMessages));
                                errorDialog.Show();
                                return;
                            }

                            View.AlarmConsequence = e1.Result.EntityResult;
                            View.DialogResult = true;
                        };

                    cmsWebServiceClient.SaveControlSystemAlarmConsequenceAsync(AlarmConsequence);
                }
            }
        }
Exemple #58
0
        public void Start()
        {
            // Checkers are identified by the type name and version field name.
            FieldInfo[] fields =
                GetAllTypes()
                .Where(t => t.Name == "CompatibilityChecker")
                .Select(t => t.GetField("_version", BindingFlags.Static | BindingFlags.NonPublic))
                .Where(f => f != null)
                .Where(f => f.FieldType == typeof(int))
                .ToArray();

            // Let the latest version of the checker execute.
            if (_version != fields.Max(f => (int)f.GetValue(null)))
            {
                return;
            }

            Debug.Log(String.Format("[CompatibilityChecker] Running checker version {0} from '{1}'", _version, Assembly.GetExecutingAssembly().GetName().Name));

            // Other checkers will see this version and not run.
            // This accomplishes the same as an explicit "ran" flag with fewer moving parts.
            _version = int.MaxValue;

            // A mod is incompatible if its compatibility checker has an IsCompatible method which returns false.
            String[] incompatible =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsCompatible", Type.EmptyTypes))
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    // If a mod throws an exception from IsCompatible, it's not compatible.
                    Debug.LogWarning(String.Format("[CompatibilityChecker] Exception while invoking IsCompatible() from '{0}':\n\n{1}", m.DeclaringType.Assembly.GetName().Name, e));
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            // A mod is incompatible with Unity if its compatibility checker has an IsUnityCompatible method which returns false.
            String[] incompatibleUnity =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsUnityCompatible", Type.EmptyTypes))
                .Where(m => m != null)  // Mods without IsUnityCompatible() are assumed to be compatible.
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    // If a mod throws an exception from IsUnityCompatible, it's not compatible.
                    Debug.LogWarning(String.Format("[CompatibilityChecker] Exception while invoking IsUnityCompatible() from '{0}':\n\n{1}", m.DeclaringType.Assembly.GetName().Name, e));
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            Array.Sort(incompatible);
            Array.Sort(incompatibleUnity);

            String message = String.Empty;

            if ((incompatible.Length > 0) || (incompatibleUnity.Length > 0))
            {
                message += ((message == String.Empty) ? "Some" : "\n\nAdditionally, some") + " installed mods may be incompatible with this version of Kerbal Space Program. Features may be broken or disabled. Please check for updates to the listed mods.";

                if (incompatible.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods detected: " + String.Join(", ", incompatible));
                    message += String.Format("\n\nThese mods are incompatible with KSP {0}.{1}.{2}:\n\n", Versioning.version_major, Versioning.version_minor, Versioning.Revision);
                    message += String.Join("\n", incompatible);
                }

                if (incompatibleUnity.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods (Unity) detected: " + String.Join(", ", incompatibleUnity));
                    message += String.Format("\n\nThese mods are incompatible with Unity {0}:\n\n", Application.unityVersion);
                    message += String.Join("\n", incompatibleUnity);
                }
            }

            if ((incompatible.Length > 0) || (incompatibleUnity.Length > 0))
            {
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Incompatible Mods Detected", message, "OK", true, HighLogic.UISkin);
            }
        }
        private void DeleteInstrumentEquipmentButtonHandler(object parameter)
        {
            var selected = (from x in mIssue.IssueRelatedInstruments where x.Checked select x).ToList();
            if (selected.Count==0)
            {
                return;
            }

            string message = string.Format("Remove link to selected Instruments? ({0})", selected.Count);
            PopupDialog popupDialog = new PopupDialog(PopupDialogType.RemoveLinkConfirm, message);
            popupDialog.Show();
            popupDialog.Closed +=
                (s2, e2) =>
                {
                    if (popupDialog.PopupDialogResult == PopupDialogResult.Yes)
                    {

                        selected.ForEach(x => mIssue.IssueRelatedInstruments.Remove(x));

                        RaiseChangeEvent();
                        RaisePropertyChanged("IssueRelatedInstruments");
                        OnCollectionChanged();
                    }
                };
        }
        public void Show(Part part)
        {
            this.part = part;

            DismissDialog();

            const string TITLE                  = "Precise Editor - Part Edition Window";
            const string MESSAGE                = "";
            const int    MAXLENGTH              = 14;
            const float  LABEL_WIDTH            = 80;
            const float  FIELD_LABEL_WIDTH      = 100f;
            const float  TRANSFORM_SPACER_WIDTH = 15f;

            Vector3    position      = part.transform.position;
            Vector3    localPosition = part.transform.localPosition;
            Quaternion rotation      = part.transform.rotation;
            Quaternion localRotation = part.transform.localRotation;

            DialogGUILabel     labelPartName         = new DialogGUILabel("Part Name", LABEL_WIDTH, LINE_HEIGHT);
            DialogGUILabel     labelPartNameValue    = new DialogGUILabel(delegate { return(this.GetPartName()); }, 250, LINE_HEIGHT);
            DialogGUILabel     labelAxisLeftSpacer   = new DialogGUILabel("", 140f, LINE_HEIGHT);
            DialogGUILabel     labelAxisCenterSpacer = new DialogGUILabel("", 115f, LINE_HEIGHT);
            DialogGUILabel     labelX                 = new DialogGUILabel("X", LINE_HEIGHT, LINE_HEIGHT);
            DialogGUILabel     labelY                 = new DialogGUILabel("Y", LINE_HEIGHT, LINE_HEIGHT);
            DialogGUILabel     labelZ                 = new DialogGUILabel("Z", LINE_HEIGHT, LINE_HEIGHT);
            DialogGUILabel     labelPosition          = new DialogGUILabel("Position", LABEL_WIDTH, LINE_HEIGHT);
            DialogGUILabel     labelLocalPosition     = new DialogGUILabel("Local Position", LABEL_WIDTH, LINE_HEIGHT);
            DialogGUILabel     labelRotation          = new DialogGUILabel("Rotation", LABEL_WIDTH, LINE_HEIGHT);
            DialogGUILabel     labelLocalRotation     = new DialogGUILabel("Local Rotation", LABEL_WIDTH, LINE_HEIGHT);
            DialogGUILabel     labelDeltaPosition     = new DialogGUILabel("-/+ Position", LABEL_WIDTH, LINE_HEIGHT);
            DialogGUILabel     labelDeltaAngle        = new DialogGUILabel("-/+ Angle", LABEL_WIDTH, LINE_HEIGHT);
            DialogGUILabel     labelTransformSpacer   = new DialogGUILabel("", TRANSFORM_SPACER_WIDTH, LINE_HEIGHT);
            DialogGUILabel     labelCloseButtonSpacer = new DialogGUILabel("", 185f, LINE_HEIGHT);
            DialogGUITextInput inputPositionX         = new DialogGUITextInput(position.x.ToString(FORMAT_POSITION), false, MAXLENGTH, delegate(string value) { return(this.SetPosition(0, value, Space.World)); }, delegate { return(this.GetPosition(0, Space.World)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputPositionY         = new DialogGUITextInput(position.y.ToString(FORMAT_POSITION), false, MAXLENGTH, delegate(string value) { return(this.SetPosition(1, value, Space.World)); }, delegate { return(this.GetPosition(1, Space.World)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputPositionZ         = new DialogGUITextInput(position.z.ToString(FORMAT_POSITION), false, MAXLENGTH, delegate(string value) { return(this.SetPosition(2, value, Space.World)); }, delegate { return(this.GetPosition(2, Space.World)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputLocalPositionX    = new DialogGUITextInput(localPosition.x.ToString(FORMAT_POSITION), false, MAXLENGTH, delegate(string value) { return(this.SetPosition(0, value, Space.Self)); }, delegate { return(this.GetPosition(0, Space.Self)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputLocalPositionY    = new DialogGUITextInput(localPosition.y.ToString(FORMAT_POSITION), false, MAXLENGTH, delegate(string value) { return(this.SetPosition(1, value, Space.Self)); }, delegate { return(this.GetPosition(1, Space.Self)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputLocalPositionZ    = new DialogGUITextInput(localPosition.z.ToString(FORMAT_POSITION), false, MAXLENGTH, delegate(string value) { return(this.SetPosition(2, value, Space.Self)); }, delegate { return(this.GetPosition(2, Space.Self)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputRotationX         = new DialogGUITextInput(rotation.eulerAngles.x.ToString(FORMAT_ANGLE), false, MAXLENGTH, delegate(string value) { return(this.SetRotation(0, value, Space.World)); }, delegate { return(this.GetRotation(0, Space.World)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputRotationY         = new DialogGUITextInput(rotation.eulerAngles.y.ToString(FORMAT_ANGLE), false, MAXLENGTH, delegate(string value) { return(this.SetRotation(1, value, Space.World)); }, delegate { return(this.GetRotation(1, Space.World)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputRotationZ         = new DialogGUITextInput(rotation.eulerAngles.z.ToString(FORMAT_ANGLE), false, MAXLENGTH, delegate(string value) { return(this.SetRotation(2, value, Space.World)); }, delegate { return(this.GetRotation(2, Space.World)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputLocalRotationX    = new DialogGUITextInput(localRotation.eulerAngles.x.ToString(FORMAT_ANGLE), false, MAXLENGTH, delegate(string value) { return(this.SetRotation(0, value, Space.Self)); }, delegate { return(this.GetRotation(0, Space.Self)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputLocalRotationY    = new DialogGUITextInput(localRotation.eulerAngles.y.ToString(FORMAT_ANGLE), false, MAXLENGTH, delegate(string value) { return(this.SetRotation(1, value, Space.Self)); }, delegate { return(this.GetRotation(1, Space.Self)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputLocalRotationZ    = new DialogGUITextInput(localRotation.eulerAngles.z.ToString(FORMAT_ANGLE), false, MAXLENGTH, delegate(string value) { return(this.SetRotation(2, value, Space.Self)); }, delegate { return(this.GetRotation(2, Space.Self)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputDeltaPosition     = new DialogGUITextInput(this.deltaPosition.ToString(FORMAT_POSITION), false, MAXLENGTH, delegate(string value) { return(this.SetDeltaPosition(value)); }, delegate { return(this.deltaPosition.ToString(FORMAT_POSITION)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputDeltaRotation     = new DialogGUITextInput(this.deltaRotation.ToString(FORMAT_POSITION), false, MAXLENGTH, delegate(string value) { return(this.SetDeltaRotation(value)); }, delegate { return(this.deltaRotation.ToString(FORMAT_POSITION)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);

            DialogGUIButton buttonPosXMinus    = new DialogGUIButton("-", delegate { this.Translate(0, true, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonPosXPlus     = new DialogGUIButton("+", delegate { this.Translate(0, false, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonPosYMinus    = new DialogGUIButton("-", delegate { this.Translate(1, true, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonPosYPlus     = new DialogGUIButton("+", delegate { this.Translate(1, false, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonPosZMinus    = new DialogGUIButton("-", delegate { this.Translate(2, true, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonPosZPlus     = new DialogGUIButton("+", delegate { this.Translate(2, false, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocPosXMinus = new DialogGUIButton("-", delegate { this.Translate(0, true, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocPosXPlus  = new DialogGUIButton("+", delegate { this.Translate(0, false, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocPosYMinus = new DialogGUIButton("-", delegate { this.Translate(1, true, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocPosYPlus  = new DialogGUIButton("+", delegate { this.Translate(1, false, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocPosZMinus = new DialogGUIButton("-", delegate { this.Translate(2, true, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocPosZPlus  = new DialogGUIButton("+", delegate { this.Translate(2, false, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonRotXMinus    = new DialogGUIButton("-", delegate { this.Rotate(0, true, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonRotXPlus     = new DialogGUIButton("+", delegate { this.Rotate(0, false, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonRotYMinus    = new DialogGUIButton("-", delegate { this.Rotate(1, true, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonRotYPlus     = new DialogGUIButton("+", delegate { this.Rotate(1, false, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonRotZMinus    = new DialogGUIButton("-", delegate { this.Rotate(2, true, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonRotZPlus     = new DialogGUIButton("+", delegate { this.Rotate(2, false, Space.World); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocRotXMinus = new DialogGUIButton("-", delegate { this.Rotate(0, true, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocRotXPlus  = new DialogGUIButton("+", delegate { this.Rotate(0, false, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocRotYMinus = new DialogGUIButton("-", delegate { this.Rotate(1, true, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocRotYPlus  = new DialogGUIButton("+", delegate { this.Rotate(1, false, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocRotZMinus = new DialogGUIButton("-", delegate { this.Rotate(2, true, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonLocRotZPlus  = new DialogGUIButton("+", delegate { this.Rotate(2, false, Space.Self); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton buttonClose        = new DialogGUIButton("Close Window", delegate { SaveWindowPosition(); }, 140f, LINE_HEIGHT, true);

            List <DialogGUIBase> dialogGUIBaseList = new List <DialogGUIBase> {
                new DialogGUIHorizontalLayout(labelPartName, labelPartNameValue),
                new DialogGUIHorizontalLayout(labelAxisLeftSpacer, labelX, labelAxisCenterSpacer, labelY, labelAxisCenterSpacer, labelZ),
                new DialogGUIHorizontalLayout(labelPosition, buttonPosXMinus, inputPositionX, buttonPosXPlus, labelTransformSpacer, buttonPosYMinus, inputPositionY, buttonPosYPlus, labelTransformSpacer, buttonPosZMinus, inputPositionZ, buttonPosZPlus),
                new DialogGUIHorizontalLayout(labelLocalPosition, buttonLocPosXMinus, inputLocalPositionX, buttonLocPosXPlus, labelTransformSpacer, buttonLocPosYMinus, inputLocalPositionY, buttonLocPosYPlus, labelTransformSpacer, buttonLocPosZMinus, inputLocalPositionZ, buttonLocPosZPlus),
                new DialogGUIHorizontalLayout(labelRotation, buttonRotXMinus, inputRotationX, buttonRotXPlus, labelTransformSpacer, buttonRotYMinus, inputRotationY, buttonRotYPlus, labelTransformSpacer, buttonRotZMinus, inputRotationZ, buttonRotZPlus),
                new DialogGUIHorizontalLayout(labelLocalRotation, buttonLocRotXMinus, inputLocalRotationX, buttonLocRotXPlus, labelTransformSpacer, buttonLocRotYMinus, inputLocalRotationY, buttonLocRotYPlus, labelTransformSpacer, buttonLocRotZMinus, inputLocalRotationZ, buttonLocRotZPlus),
                new DialogGUIHorizontalLayout(labelDeltaPosition, inputDeltaPosition, labelTransformSpacer, labelDeltaAngle, inputDeltaRotation)
            };

            List <DialogGUITextInput> partModuleInputList = new List <DialogGUITextInput>();

            foreach (PartModule partModule in part.Modules)
            {
                if (TweakablePartModules.IsTweakablePartModule(partModule))
                {
                    string[] fieldNames = TweakablePartModules.GetTweakableFieldNames(partModule);
                    string[] labels     = TweakablePartModules.GetTweakableFieldLabels(partModule);

                    int fieldIndex = 0;
                    foreach (string fieldName in fieldNames)
                    {
                        string             label      = labels[fieldIndex];
                        DialogGUILabel     labelField = new DialogGUILabel(label, FIELD_LABEL_WIDTH, LINE_HEIGHT);
                        string             txt        = TweakablePartModules.GetPartModuleFieldValue(partModule, fieldName);
                        DialogGUITextInput inputField = new DialogGUITextInput(txt, false, MAXLENGTH,
                                                                               delegate(string value) { return(TweakablePartModules.SetPartFieldValue(part, partModule, fieldName, value)); },
                                                                               delegate { return(TweakablePartModules.GetPartModuleFieldValue(partModule, fieldName)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
                        dialogGUIBaseList.Add(new DialogGUIHorizontalLayout(labelField, inputField));
                        partModuleInputList.Add(inputField);
                        fieldIndex++;
                    }
                }
            }

            dialogGUIBaseList.Add(new DialogGUIFlexibleSpace());
            dialogGUIBaseList.Add(new DialogGUIHorizontalLayout(labelCloseButtonSpacer, buttonClose));

            MultiOptionDialog dialog = new MultiOptionDialog("partEditionDialog", MESSAGE, TITLE, HighLogic.UISkin, this.dialogRect, new DialogGUIFlexibleSpace(),
                                                             new DialogGUIVerticalLayout(dialogGUIBaseList.ToArray()));

            this.popupDialog           = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin, false);
            this.popupDialog.OnDismiss = this.SaveWindowPosition;
            this.popupDialog.onDestroy.AddListener(this.OnPopupDialogDestroy);

            TMP_InputField tmp_InputPositionX      = inputPositionX.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputPositionY      = inputPositionY.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputPositionZ      = inputPositionZ.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputLocalPositionX = inputLocalPositionX.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputLocalPositionY = inputLocalPositionY.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputLocalPositionZ = inputLocalPositionZ.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputRotationX      = inputRotationX.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputRotationY      = inputRotationY.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputRotationZ      = inputRotationZ.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputLocalRotationX = inputLocalRotationX.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputLocalRotationY = inputLocalRotationY.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputLocalRotationZ = inputLocalRotationZ.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputDeltaPosition  = inputDeltaPosition.uiItem.GetComponent <TMP_InputField>();
            TMP_InputField tmp_InputDeltaRotation  = inputDeltaRotation.uiItem.GetComponent <TMP_InputField>();

            tmp_InputPositionX.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputPositionX.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputPositionY.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputPositionY.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputPositionZ.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputPositionZ.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));

            tmp_InputLocalPositionX.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputLocalPositionX.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputLocalPositionY.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputLocalPositionY.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputLocalPositionZ.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputLocalPositionZ.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));

            tmp_InputRotationX.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputRotationX.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputRotationY.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputRotationY.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputRotationZ.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputRotationZ.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));

            tmp_InputLocalRotationX.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputLocalRotationX.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputLocalRotationY.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputLocalRotationY.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputLocalRotationZ.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputLocalRotationZ.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));

            tmp_InputDeltaPosition.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputDeltaPosition.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            tmp_InputDeltaRotation.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
            tmp_InputDeltaRotation.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));

            foreach (DialogGUITextInput partModuleInput in partModuleInputList)
            {
                TMP_InputField tmp_InputField = partModuleInput.uiItem.GetComponent <TMP_InputField>();
                tmp_InputField.onSelect.AddListener(new UnityAction <string>(this.OnSelectTextInput));
                tmp_InputField.onDeselect.AddListener(new UnityAction <string>(this.OnDeselectTextInput));
            }
        }