public bool IsValidJobTarget(Thing dummy, Pawn pawn)
        {
            if (pawn == null || dummy == null)
            {
                return(false);
            }
            ThingWithComps primary = pawn.equipment.Primary;

            if (!IsDummyUsable(dummy))
            {
                return(false);
            }
            if (HugsLibUtility.HasDesignation(dummy, CombatTrainingDefOf.TrainCombatDesignation))
            {
                return(true);
            }
            if (HugsLibUtility.HasDesignation(dummy, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly))
            {
                if (primary == null)
                {
                    return(true);
                }
                return(primary.def.IsMeleeWeapon);
            }
            if (HugsLibUtility.HasDesignation(dummy, CombatTrainingDefOf.TrainCombatDesignationRangedOnly))
            {
                if (primary == null)
                {
                    return(false);
                }
                return(primary.def.IsRangedWeapon);
            }
            return(false);
        }
Пример #2
0
 /*
  * Gives the given thing the TrainCombatDesignation
  */
 public override void DesignateThing(Thing t)
 {
     if (t != null)
     {
         HugsLibUtility.ToggleDesignation(t, this.defOf, true);
     }
 }
Пример #3
0
        public static bool Execute()
        {
            string logfile = HugsLibUtility.TryGetLogFilePath();

            if (logfile.NullOrEmpty() || !File.Exists(logfile))
            {
                HugsLibController.Logger.ReportException(new FileNotFoundException("Log file path is unknown or log file does not exist. Path:" + logfile));
                return(false);
            }
            var platform = PlatformUtility.GetCurrentPlatform();

            switch (platform)
            {
            case PlatformType.Linux:
                return(Shell.StartProcess(new Shell.ShellCommand {
                    FileName = logfile
                }));

            case PlatformType.MacOSX:
                return(Shell.StartProcess(new Shell.ShellCommand {
                    FileName = "open", Args = logfile
                }));

            case PlatformType.Windows:
                return(Shell.StartProcess(new Shell.ShellCommand {
                    FileName = logfile
                }));

            default:
                HugsLibController.Logger.ReportException(new Shell.UnsupportedPlatformException("ShellOpenLog"));
                return(false);
            }
        }
Пример #4
0
        public ThingWithComps GetNearestTrainingWeapon(Thing currentWeapon)
        {
            ThingWithComps result = null;

            if (currentWeapon?.def.IsMeleeWeapon ?? false)
            {
                result = GetNearestTrainingWeaponMelee();
            }
            if (currentWeapon != null && !currentWeapon.def.IsMeleeWeapon)
            {
                result = GetNearestTrainingWeaponRanged();
            }
            if (currentWeapon == null && !HugsLibUtility.HasDesignation(base.TargetThingA, CombatTrainingDefOf.TrainCombatDesignation))
            {
                if (HugsLibUtility.HasDesignation(base.TargetThingA, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly))
                {
                    result = GetNearestTrainingWeaponMelee();
                }
                else if (HugsLibUtility.HasDesignation(base.TargetThingA, CombatTrainingDefOf.TrainCombatDesignationRangedOnly))
                {
                    result = GetNearestTrainingWeaponRanged();
                }
            }
            if (currentWeapon == null && HugsLibUtility.HasDesignation(base.TargetThingA, CombatTrainingDefOf.TrainCombatDesignation))
            {
                ThingRequest req = ThingRequest.ForGroup(ThingRequestGroup.Weapon);
                result = (ThingWithComps)GenClosest.RegionwiseBFSWorker(base.TargetA.Thing.Position, pawn.Map, req, PathEndMode.OnCell, TraverseParms.For(pawn), (Thing x) => CombatTrainingDefOf.TrainingWeapons.DescendantThingDefs.Contains(x.def) && pawn.CanReserve(x), null, 0, 12, 50f, out int _, RegionType.Set_Passable, ignoreEntirelyForbiddenRegions: true);
            }
            return(result);
        }
Пример #5
0
 public bool IsJobPossible()
 {
     if (!IsDummyUsable())
     {
         return(false);
     }
     if (LearningSaturated())
     {
         return(false);
     }
     if (HugsLibUtility.HasDesignation(TargetThingA, CombatTrainingDefOf.TrainCombatDesignation))
     {
         return(true);
     }
     if (pawn.equipment.Primary == null)
     {
         return(HugsLibUtility.HasDesignation(TargetThingA, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly));
     }
     if (HugsLibUtility.HasDesignation(TargetThingA, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly))
     {
         return(pawn.equipment.Primary.def.IsMeleeWeapon);
     }
     if (HugsLibUtility.HasDesignation(TargetThingA, CombatTrainingDefOf.TrainCombatDesignationRangedOnly))
     {
         return(pawn.equipment.Primary.def.IsRangedWeapon);
     }
     return(false);
 }
Пример #6
0
        private static void InvokeCallbackList(List <WindowInjectionManager.DrawInjectedContents> callbacks, Window _this, Rect inRect)
        {
            List <WindowInjectionManager.DrawInjectedContents> faultyCallbacks = null;

            for (int i = 0; i < callbacks.Count; i++)
            {
                try {
                    callbacks[i](_this, inRect);
                } catch (Exception e) {
                    HugsLibController.Logger.Error("Injected window callback ({0}) caused an exception and was removed. Exception was: {1}",
                                                   HugsLibUtility.DescribeDelegate(callbacks[0]), e);
                    if (WindowInjectionManager.RemoveErroringCallbacks || !Prefs.DevMode)
                    {
                        if (faultyCallbacks == null)
                        {
                            faultyCallbacks = new List <WindowInjectionManager.DrawInjectedContents>();
                        }
                        faultyCallbacks.Add(callbacks[i]);
                    }
                }
            }
            if (faultyCallbacks != null)
            {
                callbacks.RemoveAll(c => faultyCallbacks.Contains(c));
            }
        }
Пример #7
0
 public override AcceptanceReport CanDesignateThing(Thing t)
 {
     if (t != null && IsCombatDummy(t) && !HugsLibUtility.HasDesignation(t, defOf))
     {
         return(true);
     }
     return(false);
 }
Пример #8
0
        public static void ProcessNewTypes()
        {
            try {
                // get all types from all loaded assemblies
                var allTypes = new List <Type>();
                foreach (var assembly in HugsLibUtility.GetAllActiveAssemblies())
                {
                    try {
                        allTypes.AddRange(assembly.GetTypes());
                    } catch {
                        // just in case
                    }
                }

                // get all types and members marked with IDetectableAttribute attributes
                var thingsWithAttributes = new List <AttributePair>();
                foreach (var type in allTypes)
                {
                    try {
                        // skip types that were already processed
                        if (seenTypes.Contains(type))
                        {
                            continue;
                        }
                        seenTypes.Add(type);
                        // add type if attributed
                        var typeAttr = TryGetFirstRelevantAttribute(type);
                        if (typeAttr != null)
                        {
                            thingsWithAttributes.Add(new AttributePair(type, typeAttr));
                        }
                        // get attributed members from type
                        var members = type.GetMembers(HugsLibUtility.AllBindingFlags);
                        foreach (var member in members)
                        {
                            var memberAttr = TryGetFirstRelevantAttribute(member);
                            if (memberAttr != null)
                            {
                                thingsWithAttributes.Add(new AttributePair(member, memberAttr));
                            }
                        }
                    } catch {
                        // just in case
                    }
                }
                // find and validate new handlers
                var candidateAttributeHandlers = thingsWithAttributes.Where(pair => pair.attribute is DetectableAttributeHandler).ToList();
                ValidateAttributeHandlers(candidateAttributeHandlers);
                knownHandlers.AddRange(candidateAttributeHandlers);
                // make handler lookup for faster processing
                var handlersLookup = PrepareHandlerLookup(knownHandlers);
                // process all attributes
                CallHandlersForAttributes(thingsWithAttributes, handlersLookup);
            } catch (Exception e) {
                HugsLibController.Logger.ReportException(e);
            }
        }
Пример #9
0
        public override void DesignateThing(Thing t)
        {
            bool flag = !this.CanDesignateThing(t).Accepted;

            if (!flag)
            {
                HugsLibUtility.ToggleDesignation(t, AllowToolReleaseDefOf.ReleaseDesignation, true);
            }
        }
        public static void DrawModSettingsButton(Listing_Standard listing)
        {
            var prevColor = GUI.color;

            GUI.color = ButtonColor;
            if (listing.ButtonText("HugsLib_settings_btn".Translate()))
            {
                HugsLibUtility.OpenModSettingsDialog();
            }
            GUI.color = prevColor;
        }
Пример #11
0
        public void BeginUpload()
        {
            if (!PublisherIsReady())
            {
                return;
            }
            Status       = PublisherStatus.Uploading;
            ErrorMessage = null;
            userAborted  = false;

            var collatedData = PrepareLogData();

#if TEST_MOCK_UPLOAD
            HugsLibController.Logger.Message(collatedData);
            HugsLibUtility.CopyToClipboard(collatedData);
            MockUpload();
            return;
#endif

            if (collatedData == null)
            {
                ErrorMessage = "Failed to collect data";
                Status       = PublisherStatus.Error;
                return;
            }
            Action <Exception> onRequestFailed = ex => {
                if (userAborted)
                {
                    return;
                }
                OnRequestError(ex.Message);
                HugsLibController.Logger.Warning("Exception during log publishing (gist creation): " + ex);
            };
            try {
                collatedData = CleanForJSON(collatedData);
                var payload = string.Format(GistPayloadJson, GistDescription, OutputLogFilename, collatedData);
                activeRequest = new UnityWebRequest(GistApiUrl, UnityWebRequest.kHttpVerbPOST);
                activeRequest.SetRequestHeader("Authorization", "token " + GitHubAuthToken);
                activeRequest.SetRequestHeader("User-Agent", RequestUserAgent);
                activeRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(payload))
                {
                    contentType = "application/json"
                };
                activeRequest.downloadHandler = new DownloadHandlerBuffer();
                HugsLibUtility.AwaitUnityWebResponse(activeRequest, OnUploadComplete, onRequestFailed, HttpStatusCode.Created);
            } catch (Exception e) {
                onRequestFailed(e);
            }
        }
 public override void PostMapInit()
 {
     if (HugsLibUtility.HasDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignation))
     {
         trainingType = TrainingTypes.Any;
     }
     else if (HugsLibUtility.HasDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly))
     {
         trainingType = TrainingTypes.Melee;
     }
     else if (HugsLibUtility.HasDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignationRangedOnly))
     {
         trainingType = TrainingTypes.Ranged;
     }
 }
Пример #13
0
        public static void OnGUI()
        {
            if (Event.current.type != EventType.KeyDown)
            {
                return;
            }
            var useEvent = false;

            if (HugsLibKeyBindings.PublishLogs.JustPressed && HugsLibUtility.ControlIsHeld)
            {
                if (HugsLibUtility.AltIsHeld)
                {
                    HugsLibController.Instance.LogUploader.CopyToClipboard();
                }
                else
                {
                    HugsLibController.Instance.LogUploader.ShowPublishPrompt();
                }
                useEvent = true;
            }
            if (HugsLibKeyBindings.OpenLogFile.JustPressed)
            {
                ShellOpenLog.Execute();
                useEvent = true;
            }
            if (HugsLibKeyBindings.RestartRimworld.JustPressed)
            {
                GenCommandLine.Restart();
                useEvent = true;
            }
            if (HugsLibKeyBindings.HLOpenModSettings.JustPressed)
            {
                HugsLibUtility.OpenModSettingsDialog();
                useEvent = true;
            }
            if (HugsLibKeyBindings.HLOpenUpdateNews.JustPressed)
            {
                HugsLibController.Instance.UpdateFeatures.TryShowDialog(true);
                useEvent = true;
            }
            if (useEvent)
            {
                Event.current.Use();
            }
        }
Пример #14
0
        private string GetLogFileContents()
        {
            var filePath = HugsLibUtility.TryGetLogFilePath();

            if (filePath.NullOrEmpty() || !File.Exists(filePath))
            {
                throw new FileNotFoundException("Log file not found:" + filePath);
            }
            var tempPath = Path.GetTempFileName();

            File.Delete(tempPath);
            // we need to copy the log file since the original is already opened for writing by Unity
            File.Copy(filePath, tempPath);
            var fileContents = File.ReadAllText(tempPath);

            File.Delete(tempPath);
            return("Log file contents:\n" + fileContents);
        }
 public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false)
 {
     if (pawn.story.WorkTagIsDisabled(WorkTags.Violent))
     {
         JobFailReason.Is(null, "IsIncapableOfViolence".Translate());
         return(false);
     }
     if (!t.IsForbidden(pawn))
     {
         LocalTargetInfo target = t;
         if (pawn.CanReserve(target, 1, -1, null, forced))
         {
             ThingWithComps startingEquippedWeapon = pawn.equipment.Primary;
             if (startingEquippedWeapon == null)
             {
                 if (HugsLibUtility.HasDesignation(t, CombatTrainingDefOf.TrainCombatDesignation) ||
                     HugsLibUtility.HasDesignation(t, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly) ||
                     HugsLibUtility.HasDesignation(t, CombatTrainingDefOf.TrainCombatDesignationRangedOnly))
                 {
                     return(true);
                 }
             }
             else if (startingEquippedWeapon.def.IsMeleeWeapon)
             {
                 if (HugsLibUtility.HasDesignation(t, CombatTrainingDefOf.TrainCombatDesignation) ||
                     HugsLibUtility.HasDesignation(t, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly))
                 {
                     return(true);
                 }
             }
             else
             {
                 if (HugsLibUtility.HasDesignation(t, CombatTrainingDefOf.TrainCombatDesignation) ||
                     HugsLibUtility.HasDesignation(t, CombatTrainingDefOf.TrainCombatDesignationRangedOnly))
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
Пример #16
0
        public static void ExportConfigViaReflection(SimpleSidearms mod)
        {
            ModSettingsPack pack = HugsLibController.SettingsManager.GetModSettings(mod.ModIdentifier);

            if (pack == null)
            {
                return;
            }
            XElement root = new XElement("root");

            pack.CallByReflection("WriteXml", root);
            //should only have one
            Log.Message("Exporting current config!");
            StringBuilder builder = new StringBuilder();

            foreach (XElement child in root.Elements())
            {
                builder.AppendLine(child.ToString());
            }
            HugsLibUtility.CopyToClipboard(builder.ToString());
        }
        public void determineDesignation()
        {
            HugsLibUtility.ToggleDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignation, false);
            HugsLibUtility.ToggleDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly, false);
            HugsLibUtility.ToggleDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignationRangedOnly, false);
            switch (trainingType)
            {
            case TrainingTypes.None:
                break;

            case TrainingTypes.Melee:
                HugsLibUtility.ToggleDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignationMeleeOnly, true);
                break;

            case TrainingTypes.Ranged:
                HugsLibUtility.ToggleDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignationRangedOnly, true);
                break;

            case TrainingTypes.Any:
                HugsLibUtility.ToggleDesignation((Thing)this, CombatTrainingDefOf.TrainCombatDesignation, true);
                break;
            }
        }
Пример #18
0
        private void BeginUrlShortening()
        {
            Status = PublisherStatus.Shortening;

            Action <Exception> onRequestFailed = ex => {
                if (userAborted)
                {
                    return;
                }
                Status = PublisherStatus.Done;
                HugsLibController.Logger.Warning("Exception during log publishing (url shortening): " + ex);
            };

            try {
                var formData = new Dictionary <string, string> {
                    { "url", ResultUrl }
                };
                activeRequest = UnityWebRequest.Post(ShortenerUrl, formData);
                activeRequest.SetRequestHeader("User-Agent", RequestUserAgent);
                HugsLibUtility.AwaitUnityWebResponse(activeRequest, OnUrlShorteningComplete, onRequestFailed, HttpStatusCode.Created);
            } catch (Exception e) {
                onRequestFailed(e);
            }
        }
Пример #19
0
 public override string ToString()
 {
     return($"[{nameof(Label)}:{Label.ToStringSafe()}, {nameof(Action)}:{HugsLibUtility.DescribeDelegate(Action)}]");
 }
 private static void CopyMessage(LogMessage logMessage)
 {
     HugsLibUtility.CopyToClipboard(logMessage.text + "\n" + logMessage.StackTrace);
 }
Пример #21
0
 public void CopyToClipboard()
 {
     HugsLibUtility.CopyToClipboard(PrepareLogData());
 }
Пример #22
0
        public override void DoWindowContents(Rect inRect)
        {
            Text.Font = GameFont.Medium;
            var titleRect = new Rect(inRect.x, inRect.y, inRect.width, 40);

            Widgets.Label(titleRect, "HugsLib_logs_publisherTitle".Translate());
            Text.Font = GameFont.Small;
            var labelEntry      = statusMessages[publisher.Status];
            var statusLabelText = labelEntry.requiresEllipsis ? labelEntry.labelKey.Translate(GenText.MarchingEllipsis(Time.realtimeSinceStartup)) : labelEntry.labelKey.Translate();

            if (publisher.Status == LogPublisher.PublisherStatus.Error)
            {
                statusLabelText = String.Format(statusLabelText, publisher.ErrorMessage);
            }
            var statusLabelRect = new Rect(inRect.x, inRect.y + titleRect.height, inRect.width, StatusLabelHeight);

            Widgets.Label(statusLabelRect, statusLabelText);
            if (publisher.Status == LogPublisher.PublisherStatus.Done)
            {
                var urlAreaRect = new Rect(inRect.x, statusLabelRect.y + statusLabelRect.height, inRect.width, CopyButtonSize.y);
                GUI.DrawTexture(urlAreaRect, UrlBackgroundTex);
                var urlLabelRect = new Rect(urlAreaRect.x, urlAreaRect.y, urlAreaRect.width - CopyButtonSize.x, urlAreaRect.height);
                Text.Font = GameFont.Medium;
                var prevAnchor = Text.Anchor;
                Text.Anchor = TextAnchor.MiddleCenter;
                var croppedResultUrl = publisher.ResultUrl;
                if (croppedResultUrl.Length > MaxResultUrlLength)
                {
                    // crop the url in case shortening has failed and the original url is displayed
                    croppedResultUrl = croppedResultUrl.Substring(0, MaxResultUrlLength) + "...";
                }
                Widgets.Label(urlLabelRect, croppedResultUrl);
                Text.Anchor = prevAnchor;
                Text.Font   = GameFont.Small;
                var copyBtnRect = new Rect(inRect.width - CopyButtonSize.x, urlAreaRect.y, CopyButtonSize.x, CopyButtonSize.y);
                if (Widgets.ButtonText(copyBtnRect, "HugsLib_logs_copy".Translate()))
                {
                    HugsLibUtility.CopyToClipboard(publisher.ResultUrl);
                }
            }
            var bottomLeftBtnRect = new Rect(inRect.x, inRect.height - ControlButtonSize.y, ControlButtonSize.x, ControlButtonSize.y);

            if (publisher.Status == LogPublisher.PublisherStatus.Error)
            {
                if (Widgets.ButtonText(bottomLeftBtnRect, "HugsLib_logs_retryBtn".Translate()))
                {
                    publisher.BeginUpload();
                }
            }
            else if (publisher.Status == LogPublisher.PublisherStatus.Done)
            {
                if (Widgets.ButtonText(bottomLeftBtnRect, "HugsLib_logs_browseBtn".Translate()))
                {
                    Application.OpenURL(publisher.ResultUrl);
                }
            }
            var bottomRightBtnRect = new Rect(inRect.width - ControlButtonSize.x, inRect.height - ControlButtonSize.y, ControlButtonSize.x, ControlButtonSize.y);

            if (publisher.Status == LogPublisher.PublisherStatus.Uploading)
            {
                if (Widgets.ButtonText(bottomRightBtnRect, "HugsLib_logs_abortBtn".Translate()))
                {
                    publisher.AbortUpload();
                }
            }
            else
            {
                if (Widgets.ButtonText(bottomRightBtnRect, "CloseButton".Translate()))
                {
                    Close();
                }
            }
        }
Пример #23
0
 public void CopyToClipboard()
 {
     UpdateCustomOptionsUsage();
     HugsLibUtility.CopyToClipboard(PrepareLogData());
 }