Exemplo n.º 1
0
        public IEnumerable <string> FileDestinations(CkanModule module, string filePath)
        {
            var ksp = new KSP("/", "dummy", null, false);

            return(ModuleInstaller
                   .FindInstallableFiles(module, filePath, ksp)
                   .Where(f => !f.source.IsDirectory)
                   .Select(f => ksp.ToRelativeGameDir(f.destination)));
        }
Exemplo n.º 2
0
 private static string FindDownloadsPath(KSP gameInst)
 {
     foreach (string p in downloadPaths) {
         if (!string.IsNullOrEmpty(p) && Directory.Exists(p)) {
             return p;
         }
     }
     return gameInst.GameDir();
 }
Exemplo n.º 3
0
        public static int HandleCommandLine(string[] args, string[] options)
        {
            var version = KSP.GetInstalledVersion();
            var path    = KSP.RootPath;

            Console.WriteLine("Running KSP version {0} installed at {1}",
                              version, path);
            return(0);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Parses the object.
        /// </summary>
        /// <returns>The object.</returns>
        /// <param name="reader">Reader.</param>
        private object readObject(KSP.IO.TextReader reader)
        {
            object obj = null;

            // Get the name of the class an create an instance
            String n = nextLine (reader);
            obj = readObject (reader, n);

            return obj;
        }
        public static void SaveSettings(ref KSP.IO.PluginConfiguration config)
        {
            config.SetValue("unitsSettingsWindowPos", UnitsSettingsWindowPos);

            PressureUnits.SaveToConfig(ref config);
            TemperatureUnits.SaveToConfig(ref config);
            ForceUnits.SaveToConfig(ref config);
            IspUnits.SaveToConfig(ref config);
            TSFCUnits.SaveToConfig(ref config);
        }
        public static void LoadSettings(ref KSP.IO.PluginConfiguration config)
        {
            UnitsSettingsWindowPos = config.GetValue("unitsSettingsWindowPos", new Rect());

            PressureUnits = GUIUnits.UnitsFromConfig<GUIUnits.Pressure>(ref config, GUIUnits.Pressure.kPa);
            TemperatureUnits = GUIUnits.UnitsFromConfig<GUIUnits.Temperature>(ref config, GUIUnits.Temperature.kelvin);
            ForceUnits = GUIUnits.UnitsFromConfig<GUIUnits.Force>(ref config, GUIUnits.Force.kN);
            IspUnits = GUIUnits.UnitsFromConfig<GUIUnits.Isp>(ref config, GUIUnits.Isp.s);
            TSFCUnits = GUIUnits.UnitsFromConfig<GUIUnits.TSFC>(ref config, GUIUnits.TSFC.kg__kgf_h);
        }
Exemplo n.º 7
0
 /// <summary>
 /// Return the name of an instance of the game.
 /// It's not in an object because it's the key of the main dictionary holding them.
 /// </summary>
 /// <param name="manager">KSP manager object containing the instances</param>
 /// <param name="ksp">Game instance to look up</param>
 /// <returns>
 /// Name of the instance
 /// </returns>
 public static string InstallName(KSPManager manager, KSP ksp)
 {
     foreach (var kvp in manager.Instances)
     {
         if (kvp.Value == ksp)
         {
             return(kvp.Key);
         }
     }
     return(null);
 }
Exemplo n.º 8
0
 /// <summary>
 /// Reads the next single line, that is not a comment and that is relevant ("not {")
 /// </summary>
 /// <returns>The line.</returns>
 /// <param name="reader">Reader.</param>
 private String nextLine(KSP.IO.TextReader reader)
 {
     String str = reader.ReadLine ();
     if(str != null) {
         str = str.Trim();
     }
     while(str != null && (str.Length == 0 || str.Equals("{") || str[0] == '#')) {
         str = reader.ReadLine();
         if(str != null) {
             str = str.Trim();
         }
     }
     return str;
 }
Exemplo n.º 9
0
        private bool SelectInstall()
        {
            KSP prevInst = manager.CurrentInstance;

            LaunchSubScreen(new KSPListScreen(manager));
            // Abort if same instance as before
            if (!prevInst.Equals(manager.CurrentInstance))
            {
                plan.Reset();
                registry = RegistryManager.Instance(manager.CurrentInstance).registry;
                RefreshList();
            }
            return(true);
        }
 public static void LoadSettings(ref KSP.IO.PluginConfiguration config)
 {
     ShowAmbientTemp = config.GetValue("showAmbientTemp", true);
     ShowAmbientPressure = config.GetValue("showAmbientPressure", true);
     ShowRecoveryTemp = config.GetValue("showRecoveryTemp", true);
     ShowRecoveryPressure = config.GetValue("showRecoveryPressure", true);
     ShowInletPercent = config.GetValue("showInletPercent", true);
     ShowTPR = config.GetValue("showTPR", true);
     ShowInletPressureRatio = config.GetValue("showInletPressureRatio", true);
     ShowThrust = config.GetValue("showThrust", true);
     ShowTWR = config.GetValue("showTWR", true);
     ShowTDR = config.GetValue("showTDR", true);
     ShowIsp = config.GetValue("showIsp", true);
     ShowTSFC = config.GetValue("showTSFC", true);
 }
        public static void SaveSettings(ref KSP.IO.PluginConfiguration config)
        {
            config.SetValue("settingsWindowPos", SettingsWindowPos);

            config.SetValue("showAmbientTemp", ShowAmbientTemp);
            config.SetValue("showAmbientPressure", ShowAmbientPressure);
            config.SetValue("showRecoveryTemp", ShowRecoveryTemp);
            config.SetValue("showRecoveryPressure", ShowRecoveryPressure);
            config.SetValue("showInletPercent", ShowInletPercent);
            config.SetValue("showTPR", ShowTPR);
            config.SetValue("showInletPressureRatio", ShowInletPressureRatio);
            config.SetValue("showThrust", ShowThrust);
            config.SetValue("showTWR", ShowTWR);
            config.SetValue("showTDR", ShowTDR);
            config.SetValue("showIsp", ShowIsp);
            config.SetValue("showTSFC", ShowTSFC);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Show the splash screen and wait for a key press.
        /// </summary>
        public bool Run()
        {
            // If there's a default instance, try to get the lock for it.
            KSP ksp = manager.CurrentInstance ?? manager.GetPreferredInstance();

            if (ksp != null && !KSPListScreen.TryGetInstance(ksp, () => Draw(false)))
            {
                Console.ResetColor();
                Console.Clear();
                Console.CursorVisible = true;
                return(false);
            }
            // Draw screen with press any key
            Draw(true);
            // Wait for a key
            Console.ReadKey(true);
            return(true);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates a copy of the provided argument, or a known-good KSP install if passed null.
        /// Use .KSP to access the KSP object itself.
        /// </summary>
        public DisposableKSP(string directory_to_clone = null, string registry_file = null)
        {
            directory_to_clone = directory_to_clone ?? good_ksp;
            disposable_dir     = TestData.NewTempDir();
            TestData.CopyDirectory(directory_to_clone, disposable_dir);

            // If we've been given a registry file, then copy it into position before
            // creating our KSP object.

            if (registry_file != null)
            {
                string registry_dir  = Path.Combine(disposable_dir, "CFAN");
                string registry_path = Path.Combine(registry_dir, "registry.json");
                Directory.CreateDirectory(registry_dir);
                File.Copy(registry_file, registry_path, true);
            }

            KSP = new KSP(disposable_dir, NullUser.User);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Let the user choose some zip files, then import them to the mod cache.
        /// </summary>
        /// <param name="gameInst">Game instance to import into</param>
        /// <param name="cp">Change plan object for marking things to be installed</param>
        public static void ImportDownloads(KSP gameInst, ChangePlan cp)
        {
            ConsoleFileMultiSelectDialog cfmsd = new ConsoleFileMultiSelectDialog(
                "Import Downloads",
                FindDownloadsPath(gameInst),
                "*.zip",
                "Import"
            );
            HashSet<FileInfo> files = cfmsd.Run();

            if (files.Count > 0) {
                ProgressScreen  ps   = new ProgressScreen("Importing Downloads", "Calculating...");
                ModuleInstaller inst = ModuleInstaller.GetInstance(gameInst, ps);
                ps.Run(() => inst.ImportFiles(files, ps,
                    (CkanModule mod) => cp.Install.Add(mod)));
                // Don't let the installer re-use old screen references
                inst.User = null;
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Return whether the path is valid
 /// </summary>
 protected bool pathValid()
 {
     if (Platform.IsMac)
     {
         // Handle default path dragged-and-dropped onto Mac's Terminal
         path.Value = path.Value.Replace("Kerbal\\ Space\\ Program", "Kerbal Space Program");
     }
     if (!KSP.IsKspDir(path.Value))
     {
         // Complain about non-KSP path
         RaiseError("Path does not correspond to a KSP folder!");
         SetFocus(path);
         return(false);
     }
     else
     {
         return(true);
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a copy of the provided argument, or a known-good KSP install if passed null.
        /// Use .KSP to access the KSP object itself.
        /// </summary>
        public DisposableKSP(string directoryToClone = null, string registryFile = null)
        {
            directoryToClone = directoryToClone ?? _goodKsp;
            _disposableDir   = TestData.NewTempDir();
            TestData.CopyDirectory(directoryToClone, _disposableDir);

            // If we've been given a registry file, then copy it into position before
            // creating our KSP object.

            if (registryFile != null)
            {
                var registryDir  = Path.Combine(_disposableDir, "CKAN");
                var registryPath = Path.Combine(registryDir, "registry.json");
                Directory.CreateDirectory(registryDir);
                File.Copy(registryFile, registryPath, true);
            }

            KSP = new KSP(_disposableDir, NullUser.User);
        }
Exemplo n.º 17
0
        public bool IsInstalled(KSP ksp, out string identifier, out UnmanagedModuleVersion version)
        {
            identifier = Identifier;
            version    = null;

            var directoryPath = Path.Combine(ksp.GameData(), "SquadExpansion", "MakingHistory");

            if (Directory.Exists(directoryPath))
            {
                var readmeFilePath = Path.Combine(directoryPath, "readme.txt");

                if (File.Exists(readmeFilePath))
                {
                    foreach (var line in File.ReadAllLines(readmeFilePath))
                    {
                        var match = VersionPattern.Match(line);

                        if (match.Success)
                        {
                            var versionStr = match.Groups["version"].Value;

                            if (CanonicalVersions.ContainsKey(versionStr))
                            {
                                versionStr = CanonicalVersions[versionStr];
                            }

                            version = new UnmanagedModuleVersion(versionStr);
                            break;
                        }
                    }
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 18
0
        internal static NetFileCache FindCache(CmdLineOptions options, KSPManager ksp_manager, IUser user)
        {
            if (options.CacheDir != null)
            {
                log.InfoFormat("Using user-supplied cache at {0}", options.CacheDir);
                return new NetFileCache(options.CacheDir);
            }

            try
            {
                KSP ksp = ksp_manager.GetPreferredInstance();
                log.InfoFormat("Using CKAN cache at {0}",ksp.Cache.GetCachePath());
                return ksp.Cache;
            }
            catch
            {
                // Meh, can't find KSP. 'Scool, bro.
            }

            string tempdir = Path.GetTempPath();
            log.InfoFormat("Using tempdir for cache: {0}", tempdir);

            return new NetFileCache(tempdir);
        }
Exemplo n.º 19
0
        private void writeVesselUpdateToFile(KSP.IO.FileStream out_stream, Vessel vessel)
        {
            if (!vessel || !vessel.mainBody)
                return;

            //Create a KLFVesselUpdate from the vessel data
            KLFVesselUpdate update = new KLFVesselUpdate();

            update.vesselName = vessel.vesselName;
            update.ownerName = playerName;
            update.id = vessel.id;

            Vector3 pos = vessel.mainBody.transform.InverseTransformPoint(vessel.GetWorldPos3D());
            Vector3 dir = vessel.mainBody.transform.InverseTransformDirection(vessel.transform.up);
            Vector3 vel = vessel.mainBody.transform.InverseTransformDirection(vessel.GetObtVelocity());

            for (int i = 0; i < 3; i++)
            {
                update.localPosition[i] = pos[i];
                update.localDirection[i] = dir[i];
                update.localVelocity[i] = vel[i];
            }

            update.situation = vessel.situation;

            if (vessel == FlightGlobals.ActiveVessel)
                update.state = Vessel.State.ACTIVE;
            else if (vessel.isCommandable)
                update.state = Vessel.State.INACTIVE;
            else
                update.state = Vessel.State.DEAD;

            update.timeScale = Planetarium.TimeScale;
            update.bodyName = vessel.mainBody.bodyName;

            //Serialize the update
            byte[] update_bytes = KSP.IO.IOUtils.SerializeToBinary(update);

            //Write the length of the serialized to the stream
            writeIntToStream(out_stream, update_bytes.Length);

            //Write the serialized update to the stream
            out_stream.Write(update_bytes, 0, update_bytes.Length);
        }
Exemplo n.º 20
0
 private IEnumerable <InstallableFile> GetFilesBySuffix(CkanModule module, ZipFile zip, string suffix, KSP ksp = null)
 {
     return(ModuleInstaller
            .FindInstallableFiles(module, zip, ksp)
            .Where(instF => instF.source.Name.EndsWith(suffix,
                                                       StringComparison.InvariantCultureIgnoreCase)));
 }
Exemplo n.º 21
0
 public IEnumerable <InstallableFile> GetCrafts(CkanModule module, ZipFile zip, KSP ksp)
 {
     return(GetFilesBySuffix(module, zip, ".craft", ksp));
 }
Exemplo n.º 22
0
 public void RebuildAstronautComplex(KSP.UI.CrewListItem.ButtonTypes type, KSP.UI.CrewListItem cic)
 {
     StartCoroutine(CallbackUtil.DelayedCallback(1, BuildAstronautComplex));
 }
        protected GroupContainer CreateGroupItem(GroupContainer groupContainer, int indent = 0, KSP.UI.UIListItem previous = null)
        {
            MCListItem mcListItem = UnityEngine.Object.Instantiate<MCListItem>(MissionControl.Instance.PrfbMissionListItem);
            mcListItem.container.Data = groupContainer;
            groupContainer.mcListItem = mcListItem;

            // Set up the list item with the group details
            if (groupContainer.agent != null)
            {
                mcListItem.logoSprite.texture = groupContainer.agent.LogoScaled;
            }
            mcListItem.difficulty.gameObject.SetActive(false);

            // Force to the default state
            mcListItem.GetComponent<Image>().sprite = groupUnexpandedInactive;

            // Add the list item to the UI, and add indent
            if (previous == null)
            {
                MissionControl.Instance.scrollListContracts.AddItem(mcListItem.container, true);

                groupContainer.listItemTransform = mcListItem.transform;
                SetIndent(mcListItem, indent);
            }
            else
            {
                InsertIntoList(groupContainer, indent, previous);
            }

            // Create as unexpanded
            if (indent != 0)
            {
                mcListItem.gameObject.SetActive(false);
            }

            // Set the callbacks
            mcListItem.radioButton.onFalseBtn.AddListener(new UnityAction<UIRadioButton, UIRadioButton.CallType, PointerEventData>(OnDeselectGroup));
            mcListItem.radioButton.onTrueBtn.AddListener(new UnityAction<UIRadioButton, UIRadioButton.CallType, PointerEventData>(OnSelectGroup));

            bool hasChildren = false;

            // Add any child groups
            if (groupContainer.group != null)
            {
                foreach (ContractGroup child in ContractGroup.AllGroups.Where(g => g != null && g.parent == groupContainer.group && ContractType.AllValidContractTypes.Any(ct => g.BelongsToGroup(ct))).
                    OrderBy(g => GroupContainer.OrderKey(g)))
                {
                    hasChildren = true;
                    GroupContainer childContainer = new GroupContainer(child);
                    childContainer.parent = groupContainer;
                    groupContainer.childGroups.Add(CreateGroupItem(childContainer, indent + 1));
                }
            }

            // Add contracts
            Container lastContainer = groupContainer;
            foreach (ContractContainer contractContainer in GetContracts(groupContainer).OrderBy(c => c.OrderKey))
            {
                contractContainer.parent = groupContainer;
                groupContainer.childContracts.Add(contractContainer);

                hasChildren = true;
                CreateContractItem(contractContainer, indent + 1, previous != null ? lastContainer.mcListItem.container : null);
                lastContainer = contractContainer;
            }

            // Remove groups with nothing underneath them
            if (!hasChildren)
            {
                MissionControl.Instance.scrollListContracts.RemoveItem(mcListItem.container, true);
            }

            // Get the main text object
            GameObject textObject = mcListItem.title.gameObject;
            RectTransform textRect = textObject.GetComponent<RectTransform>();

            // Make non-static modifications
            SetupGroupItem(groupContainer);

            // Adjust the main text up a little
            textRect.anchoredPosition = new Vector2(textRect.anchoredPosition.x, textRect.anchoredPosition.y + 6);

            return groupContainer;
        }
Exemplo n.º 24
0
 private Int32 readIntFromStream(KSP.IO.FileStream stream)
 {
     byte[] bytes = new byte[4];
     stream.Read(bytes, 0, 4);
     return KMPCommon.intFromBytes(bytes);
 }
Exemplo n.º 25
0
 private string StatusSymbol(KSP k)
 {
     return(k.Name == manager.AutoStartInstance
         ? defaultMark
         : " ");
 }
Exemplo n.º 26
0
 private Int32 ReadIntFromStream(KSP.IO.FileStream stream)
 {
     byte[] bytes = new byte[4];
     stream.Read(bytes, 0, 4);
     return KLFCommon.BytesToInt(bytes);
 }
Exemplo n.º 27
0
 public PartDiff( KSP.Install install, KSP.SaveGame saveGame )
 {
     install_ = install;
     saveGame_ = saveGame;
 }
Exemplo n.º 28
0
 public void Dispose()
 {
     KSP.Dispose();
     KSP = null; // In case .Dispose() was called manually.
     Directory.Delete(disposable_dir, true);
 }
        protected void CreateContractItem(ContractContainer cc, int indent = 0, KSP.UI.UIListItem previous = null)
        {
            // Set up list item
            MCListItem mcListItem = UnityEngine.Object.Instantiate<MCListItem>(MissionControl.Instance.PrfbMissionListItem);
            mcListItem.logoSprite.gameObject.SetActive(false);
            mcListItem.container.Data = cc;
            cc.mcListItem = mcListItem;
            cc.indent = indent;

            // Set up the radio button to the custom sprites for contracts
            UIRadioButton radioButton = mcListItem.GetComponent<UIRadioButton>();
            radioButton.stateTrue.normal = radioButton.stateTrue.highlight = radioButton.stateTrue.pressed = radioButton.stateTrue.disabled = itemEnabled;
            radioButton.stateFalse.normal = radioButton.stateFalse.highlight = radioButton.stateFalse.pressed = radioButton.stateFalse.disabled = itemDisabled;
            mcListItem.GetComponent<Image>().sprite = itemDisabled;

            // Fix up the position/sizing of the text element
            GameObject textObject = mcListItem.gameObject.GetChild("Text");
            RectTransform textRect = textObject.GetComponent<RectTransform>();
            textRect.anchoredPosition = new Vector2(textRect.anchoredPosition.x - 60, textRect.anchoredPosition.y);
            textRect.sizeDelta = new Vector2(textRect.sizeDelta.x + 60 - 20, textRect.sizeDelta.y);

            // Set up the difficulty/prestige stars
            mcListItem.difficulty.states[0].sprite = prestigeSprites[0];
            mcListItem.difficulty.states[1].sprite = prestigeSprites[1];
            mcListItem.difficulty.states[2].sprite = prestigeSprites[2];

            // Create an icon to show the status
            GameObject statusImage = new GameObject("StatusImage");
            cc.statusRect = statusImage.AddComponent<RectTransform>();
            cc.statusRect.anchoredPosition = new Vector2(16.0f, 0f);
            cc.statusRect.anchorMin = new Vector2(0, 0.5f);
            cc.statusRect.anchorMax = new Vector2(0, 0.5f);
            cc.statusRect.sizeDelta = new Vector2(10f, 10f);
            statusImage.AddComponent<CanvasRenderer>();
            cc.statusImage = statusImage.AddComponent<UIStateImage>();
            cc.statusImage.states = itemStatusStates;
            cc.statusImage.image = statusImage.AddComponent<Image>();
            statusImage.transform.SetParent(mcListItem.transform);

            // Finalize difficulty UI
            RectTransform diffRect = mcListItem.difficulty.GetComponent<RectTransform>();
            diffRect.anchoredPosition = new Vector2(-20.5f, -12.5f);
            diffRect.sizeDelta = new Vector2(35, 11);

            // Set the callbacks
            mcListItem.radioButton.onFalseBtn.AddListener(new UnityAction<UIRadioButton, UIRadioButton.CallType, PointerEventData>(OnDeselectContract));
            mcListItem.radioButton.onTrueBtn.AddListener(new UnityAction<UIRadioButton, UIRadioButton.CallType, PointerEventData>(OnSelectContract));

            // Do other setup
            SetupContractItem(cc);

            // Add the list item to the UI, and add indent
            if (previous == null)
            {
                MissionControl.Instance.scrollListContracts.AddItem(mcListItem.container, true);

                cc.listItemTransform = mcListItem.transform;
                SetIndent(mcListItem, indent);
            }
            else
            {
                InsertIntoList(cc, indent, previous);
            }

            // Create as unexpanded
            if (indent != 0)
            {
                mcListItem.gameObject.SetActive(false);
            }
        }
Exemplo n.º 30
0
 private void changeKerbalIcon(KSP.UI.CrewListItem cic)
 {
     if((object)cic.GetCrewRef() == null) {
         return;
     }
     FlightLog.Entry flight = cic.GetCrewRef().flightLog.Entries.FirstOrDefault(e => e.type == KerbalRenamer.Instance.cultureDescriptor);
     if((object)flight != null) {
         FieldInfo fi = typeof(KSP.UI.CrewListItem).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(c => c.FieldType == typeof(RawImage));
         RawImage foo = (RawImage) fi.GetValue(cic);
         Culture culture = KerbalRenamer.Instance.getCultureByName(flight.target);
         if((object)culture != null) {
             foo.texture = (Texture) GameDatabase.Instance.GetTexture("KerbalRenamer/Icons/" + culture.cultureName, false);
         }
     }
 }
Exemplo n.º 31
0
 public void RebuildCrewAssignmentDialogue(KSP.UI.CrewListItem.ButtonTypes type, KSP.UI.CrewListItem cic)
 {
     StartCoroutine(CallbackUtil.DelayedCallback(1, BuildCrewAssignmentDialogue));
 }
Exemplo n.º 32
0
 private void SetInstanceKeysTo(int instanceIndex, string name, KSP ksp)
 {
     SetRegistryValue(@"KSPInstanceName_" + instanceIndex, name);
     SetRegistryValue(@"KSPInstancePath_" + instanceIndex, ksp.GameDir());
 }
Exemplo n.º 33
0
        private void writeObject(KSP.IO.TextWriter writer, object obj)
        {
            Type t = obj.GetType ();
            writer.WriteLine (t.Name);
            writer.WriteLine ("{");
            foreach (FieldInfo info in t.GetFields()) {
                object o = info.GetValue(obj);

                if(o == null) {
                    continue;
                }

                if (info.FieldType.Equals (typeof(Enum))) {
                    writer.WriteLine ("    " + info.Name + " = " + info.GetValue(obj));
                }

                if(info.FieldType.Equals(typeof(String))) {
                    writer.WriteLine("    " + info.Name + " = " + info.GetValue(obj));
                }

                if(info.FieldType.Equals(typeof(float))) {
                    writer.WriteLine("    " + info.Name + " = " + info.GetValue(obj));
                }

                if(info.FieldType.Equals(typeof(double))) {
                    writer.WriteLine("    " + info.Name + " = " + info.GetValue(obj));
                }

                if(info.FieldType.Equals(typeof(int))) {
                    writer.WriteLine("    " + info.Name + " = " + info.GetValue(obj));
                }

                if(info.FieldType.Equals(typeof(bool))) {
                    writer.WriteLine("    " + info.Name + " = " + info.GetValue(obj));
                }

                if (o.GetType().GetInterface("IList") != null) {
                    IList ilist = (IList)o;

                    foreach(object v in ilist) {
                        writeObject(writer, v);
                    }
                }
            }
            writer.WriteLine ("}");
        }
Exemplo n.º 34
0
        /// <summary>
        /// Initialize the Screen
        /// </summary>
        /// <param name="mgr">KSP manager containing the instances</param>
        /// <param name="k">Instance to edit</param>
        public KSPEditScreen(KSPManager mgr, KSP k)
            : base(mgr, k.Name, k.GameDir())
        {
            ksp = k;
            try {
                // If we can't parse the registry, just leave the repo list blank
                registry = RegistryManager.Instance(ksp).registry;
            } catch { }

            // Show the repositories if we can
            if (registry != null)
            {
                // Need to edit a copy of the list so it doesn't save on cancel
                repoEditList = new SortedDictionary <string, Repository>();
                foreach (var kvp in registry.Repositories)
                {
                    repoEditList.Add(kvp.Key, new Repository(
                                         kvp.Value.name,
                                         kvp.Value.uri.ToString(),
                                         kvp.Value.priority
                                         ));
                }

                // Also edit copy of the compatible versions
                compatEditList = new List <KspVersion>(ksp.GetCompatibleVersions());

                // I'm not a huge fan of this layout, but I think it's better than just a label
                AddObject(new ConsoleDoubleFrame(
                              1, repoFrameTop, -1, compatFrameBottom, compatFrameTop,
                              () => $"Mod List Sources",
                              () => $"Additional Compatible Versions",
                              () => ConsoleTheme.Current.LabelFg
                              ));

                repoList = new ConsoleListBox <Repository>(
                    3, repoListTop, -3, repoListBottom,
                    new List <Repository>(repoEditList.Values),
                    new List <ConsoleListBoxColumn <Repository> >()
                {
                    new ConsoleListBoxColumn <Repository>()
                    {
                        Header   = "Index",
                        Renderer = r => r.priority.ToString(),
                        Width    = 7
                    }, new ConsoleListBoxColumn <Repository>()
                    {
                        Header   = "Name",
                        Renderer = r => r.name,
                        Width    = 16
                    }, new ConsoleListBoxColumn <Repository>()
                    {
                        Header   = "URL",
                        Renderer = r => r.uri.ToString(),
                        Width    = 50
                    }
                },
                    1, 0, ListSortDirection.Ascending
                    );
                AddObject(repoList);
                repoList.AddTip("A", "Add");
                repoList.AddBinding(Keys.A, (object sender) => {
                    LaunchSubScreen(new RepoAddScreen(repoEditList));
                    repoList.SetData(new List <Repository>(repoEditList.Values));
                    return(true);
                });
                repoList.AddTip("R", "Remove");
                repoList.AddBinding(Keys.R, (object sender) => {
                    int oldPrio = repoList.Selection.priority;
                    repoEditList.Remove(repoList.Selection.name);
                    // Reshuffle the priorities to fill
                    foreach (Repository r in repoEditList.Values)
                    {
                        if (r.priority > oldPrio)
                        {
                            --r.priority;
                        }
                    }
                    repoList.SetData(new List <Repository>(repoEditList.Values));
                    return(true);
                });
                repoList.AddTip("E", "Edit");
                repoList.AddBinding(Keys.E, (object sender) => {
                    LaunchSubScreen(new RepoEditScreen(repoEditList, repoList.Selection));
                    repoList.SetData(new List <Repository>(repoEditList.Values));
                    return(true);
                });
                repoList.AddTip("-", "Up");
                repoList.AddBinding(Keys.Minus, (object sender) => {
                    if (repoList.Selection.priority > 0)
                    {
                        Repository prev = SortedDictFind(repoEditList,
                                                         r => r.priority == repoList.Selection.priority - 1);
                        if (prev != null)
                        {
                            ++prev.priority;
                        }
                        --repoList.Selection.priority;
                        repoList.SetData(new List <Repository>(repoEditList.Values));
                    }
                    return(true);
                });
                repoList.AddTip("+", "Down");
                repoList.AddBinding(Keys.Plus, (object sender) => {
                    Repository next = SortedDictFind(repoEditList,
                                                     r => r.priority == repoList.Selection.priority + 1);
                    if (next != null)
                    {
                        --next.priority;
                    }
                    ++repoList.Selection.priority;
                    repoList.SetData(new List <Repository>(repoEditList.Values));
                    return(true);
                });

                compatList = new ConsoleListBox <KspVersion>(
                    3, compatListTop, -3, compatListBottom,
                    compatEditList,
                    new List <ConsoleListBoxColumn <KspVersion> >()
                {
                    new ConsoleListBoxColumn <KspVersion>()
                    {
                        Header   = "Version",
                        Width    = 10,
                        Renderer = v => v.ToString(),
                        Comparer = (a, b) => a.CompareTo(b)
                    }
                },
                    0, 0, ListSortDirection.Descending
                    );
                AddObject(compatList);

                compatList.AddTip("A", "Add");
                compatList.AddBinding(Keys.A, (object sender) => {
                    CompatibleVersionDialog vd = new CompatibleVersionDialog();
                    KspVersion newVersion      = vd.Run();
                    DrawBackground();
                    if (newVersion != null && !compatEditList.Contains(newVersion))
                    {
                        compatEditList.Add(newVersion);
                        compatList.SetData(compatEditList);
                    }
                    return(true);
                });
                compatList.AddTip("R", "Remove", () => compatList.Selection != null);
                compatList.AddBinding(Keys.R, (object sender) => {
                    compatEditList.Remove(compatList.Selection);
                    compatList.SetData(compatEditList);
                    return(true);
                });
            }
            else
            {
                // Notify the user that the registry doesn't parse
                AddObject(new ConsoleLabel(
                              1, repoFrameTop, -1,
                              () => $"Failed to extract mod list sources from {ksp.Name}."
                              ));
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// Import a list of files into the download cache, with progress bar and
        /// interactive prompts for installation and deletion.
        /// </summary>
        /// <param name="gameInst">Game instance to install into</param>
        /// <param name="files">Set of files to import</param>
        /// <param name="user">Object for user interaction</param>
        /// <param name="inst">Module installer object</param>
        /// <param name="installMod">Function to call to mark a mod for installation</param>
        public static void ImportFiles(KSP gameInst, HashSet <FileInfo> files,
                                       IUser user, ModuleInstaller inst, Action <string> installMod)
        {
            Registry         registry    = RegistryManager.Instance(gameInst).registry;
            HashSet <string> installable = new HashSet <string>();
            List <FileInfo>  deletable   = new List <FileInfo>();
            // Get the mapping of known hashes to modules
            Dictionary <string, List <CkanModule> > index = registry.GetSha1Index();
            int i = 0;

            foreach (FileInfo f in files)
            {
                int percent = i * 100 / files.Count;
                user.RaiseProgress($"Importing {f.Name}... ({percent}%)", percent);
                // Calc SHA-1 sum
                string sha1 = GetFileHashSha1(f.FullName);
                // Find SHA-1 sum in registry (potentially multiple)
                if (index.ContainsKey(sha1))
                {
                    deletable.Add(f);
                    List <CkanModule> matches = index[sha1];
                    foreach (CkanModule mod in matches)
                    {
                        if (mod.IsCompatibleKSP(gameInst.VersionCriteria()))
                        {
                            installable.Add(mod.identifier);
                        }
                        if (inst.Cache.IsCachedZip(mod.download))
                        {
                            user.RaiseMessage("Already cached: {0}", f.Name);
                        }
                        else
                        {
                            user.RaiseMessage($"Importing {mod.identifier} {Formatting.StripEpoch(mod.version)}...");
                            inst.Cache.Store(mod.download, f.FullName);
                        }
                    }
                }
                else
                {
                    user.RaiseMessage("Not found in index: {0}", f.Name);
                }
                ++i;
            }
            if (installable.Count > 0 && user.RaiseYesNoDialog($"Install {installable.Count} compatible imported mods?"))
            {
                // Install the imported mods
                foreach (string identifier in installable)
                {
                    installMod(identifier);
                }
            }
            if (user.RaiseYesNoDialog($"Import complete. Delete {deletable.Count} old files?"))
            {
                // Delete old files
                foreach (FileInfo f in deletable)
                {
                    f.Delete();
                }
            }
        }
Exemplo n.º 36
0
        public void onEditorVesselLoad(ShipConstruct ship, KSP.UI.Screens.CraftBrowserDialog.LoadType type)
        {
            Utils.Log("Editor: Vessel LOAD, recalculate all parts");
            if (!HighLogic.LoadedSceneIsEditor) { return; }

            RecalculateEditorShip(ship);
        }
Exemplo n.º 37
0
        private object readObject(KSP.IO.TextReader reader, String name)
        {
            Type t = Type.GetType (NamespacePrefix + name);
            object obj = Activator.CreateInstance (t);

            String n;
            // now parse the lines and put them into the dictionary.
            // if there is another object inside, parse it and invoke "add"
            while ((n = nextLine(reader)) != null && !n.Equals("}")) {
                if(n.IndexOf('=') != -1) {
                    string[] parts = n.Split('=');
                    string vname = parts[0].Trim();
                    string value = n.Substring(n.IndexOf('=') + 1).Trim().Replace("\\n", "\n");

                    ReflectionTools.setValue(vname, value, obj);
                } else {
                    object inner = readObject(reader, n);
                    t.GetMethod("add", new Type[] {inner.GetType()}).Invoke(obj, new object[] {inner});
                }
            }
            return obj;
        }
Exemplo n.º 38
0
 private void writeIntToStream(KSP.IO.FileStream stream, Int32 val)
 {
     stream.Write(KMPCommon.intToBytes(val), 0, 4);
 }
        protected void InsertIntoList(Container container, int indent, KSP.UI.UIListItem previous)
        {
            // Ugly bit of reflection to add to the internals of the list - otherwise the list refresh will mess up the indenting
            int index = MissionControl.Instance.scrollListContracts.GetIndex(previous);
            UIList<KSP.UI.UIListItem> childUIList = (UIList<KSP.UI.UIListItem>)childUIListField.GetValue(MissionControl.Instance.scrollListContracts);
            List<UIListData<KSP.UI.UIListItem>> listData = (List<UIListData<KSP.UI.UIListItem>>)listDataField.GetValue(childUIList);
            listData.Insert(index + 1, new UIListData<KSP.UI.UIListItem>((KSP.UI.UIListItem)null, container.mcListItem.container));
            container.mcListItem.container.transform.SetParent(childUIList.listAnchor);
            container.mcListItem.container.transform.localPosition = new Vector3(container.mcListItem.container.transform.localPosition.x, container.mcListItem.container.transform.localPosition.y, 0.0f);

            container.listItemTransform = container.mcListItem.transform;
            SetIndent(container.mcListItem, indent);

            for (int i = 0; i < listData.Count; i++)
            {
                ((Container)listData[i].listItem.Data).listItemTransform.SetSiblingIndex(i);
            }
        }