DialogPrimeTrade.cs 16.2 KB
Newer Older
1
2
3
4
5
#region License

// This file was created by TwistedSoul @ TheCodeCache.net
// You are free to inspect the mod but may not modify or redistribute without my express permission.
// However! If you would like to contribute to GWP please feel free to drop me a message.
6
// Glitterworld Prime, DialogPrimeTrade.cs, Created 2018-07-22
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;

namespace Glitterworld_Prime
{
    public class DialogPrimeTrade : Dialog_Trade
    {
22
        #region Fields
23
24
25
26
27
28
29
30
31
32

        private Tradeable _cachedCurrencyTradeable;
        private List<Tradeable> _cachedTradeables;
        private ThingCategoryDef _filter;

        private bool _filterOnlyColonyItems;
        private bool _filterSettingLastFrame;
        private Vector2 _scrollPosition = Vector2.zero;
        private TransferableSorterDef _sorter1;
        private TransferableSorterDef _sorter2;
33
        private string _textFilter = "";
34
35
36
37
38
39
40

        #endregion

        #region ctor

        public DialogPrimeTrade(Pawn playerNegotiator, ITrader trader) : base(playerNegotiator, trader)
        {
41
42
            TradeSession.SetupWith(trader, playerNegotiator, false);
            closeOnCancel = true;
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
            forcePause = true;
            absorbInputAroundWindow = true;
            soundAppear = SoundDefOf.CommsWindow_Open;
            soundClose = SoundDefOf.CommsWindow_Close;
            if (!(trader is Pawn)) soundAmbient = SoundDefOf.RadioComms_Ambience;
            _sorter1 = TransferableSorterDefOf.Category;
            _sorter2 = TransferableSorterDefOf.MarketValue;

            // This has been set to food to reduce lag when the Window opens.
            _filter = ThingCategoryDefOf.Foods;
        }

        #endregion

        #region Properties

        public override Vector2 InitialSize => new Vector2(1024f, UI.screenHeight);

        private int Tile => TradeSession.playerNegotiator.Tile;

        private float TopAreaHeight
        {
            get
            {
67
                var num = 65f;
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
                return num;
            }
        }

        #endregion

        #region  Methods

        public override void DoWindowContents(Rect inRect)
        {
            TradeSession.deal.UpdateCurrencyCount();

            // This code draws the two sort button and assigns the callback for the dropdown menus when they've been clicked.
            DoTransferableSorters(
                delegate(TransferableSorterDef x)
                {
                    _sorter1 = x;
                    CacheTradeables();
                }, delegate(TransferableSorterDef x)
                {
                    _sorter2 = x;
                    CacheTradeables();
                }, delegate(ThingCategoryDef x)
                {
                    _filter = x;
                    CacheTradeables();
                });

            // Define width of trade window
            var num = inRect.width - 590f;

            // Define the Header rectangle
            var rect = new Rect(num, 0f, inRect.width - num, TopAreaHeight);
            GUI.BeginGroup(rect);

            Text.Font = GameFont.Medium;
            Text.Anchor = TextAnchor.UpperLeft;

            // Draw trader name
            var rect3 = new Rect(rect.width / 2f, 0f, rect.width / 2f, rect.height);
            Text.Anchor = TextAnchor.UpperRight;
            var text = TradeSession.trader.TraderName;
            if (Text.CalcSize(text).x > rect3.width)
            {
                Text.Font = GameFont.Small;
                text = text.Truncate(rect3.width, null);
            }

            Widgets.Label(rect3, text);

            // Negotiator
            Text.Font = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;
            var rect4 = new Rect(0f, 27f, rect.width / 2f, rect.height / 2f);
            Widgets.Label(rect4, "Negotiator".Translate() + ": " + TradeSession.playerNegotiator.LabelShort);

            // Trader description
            Text.Anchor = TextAnchor.UpperRight;
            var rect5 = new Rect(rect.width / 2f, 27f, rect.width / 2f, rect.height / 2f);
            Widgets.Label(rect5, TradeSession.trader.TraderKind.LabelCap);

            // Trade hints / explanation
            Text.Anchor = TextAnchor.UpperLeft;
            GUI.color = new Color(1f, 1f, 1f, 0.6f);
            Text.Font = GameFont.Tiny;
            var rect6 = new Rect(rect.width / 2f - 100f - 30f, 0f, 200f, rect.height);
            Text.Anchor = TextAnchor.LowerCenter;
            Widgets.Label(rect6, "PositiveBuysNegativeSells".Translate());
            Text.Anchor = TextAnchor.UpperLeft;
            GUI.color = Color.white;
            GUI.EndGroup();

            // Draw currency row
            var num2 = 0f;
            if (_cachedCurrencyTradeable != null)
            {
                var num3 = inRect.width - 16f;
                var rect8 = new Rect(0f, TopAreaHeight, num3, 30f);
                TradeUI.DrawTradeableRow(rect8, _cachedCurrencyTradeable, 1);
                GUI.color = Color.gray;
                Widgets.DrawLineHorizontal(0f, TopAreaHeight + 30f - 1f, num3);
                GUI.color = Color.white;
                num2 = 30f;
            }

            // Define the tradeable subwindow.
            var mainRect = new Rect(0f, TopAreaHeight + num2, inRect.width,
                inRect.height - TopAreaHeight - 38f - num2 - 20f);

            // Draw the tradables
            FillMainRect(mainRect);

            // Draw, Reset, Accept and Cancel buttons
            var rect9 = new Rect(inRect.width / 2f - AcceptButtonSize.x / 2f, inRect.height - 55f, AcceptButtonSize.x,
                AcceptButtonSize.y);
            if (Widgets.ButtonText(rect9, "AcceptButton".Translate(), true, false, true))
            {
                Action action = delegate
                {
                    bool flag;

                    var tracker = Utilities.GetMapComponent(TradeSession.playerNegotiator.Map).OrderTracker;

                    if (TradeSession.deal.TryExecute(out flag))
                    {
                        if (flag)
                        {
                            var orderSuccess = tracker.TryPlaceOrder((TraderPrime) TradeSession.trader);

                            // Were we able to place the order?
                            if (orderSuccess)
                            {
                                // Yes, Plav a sound and record the trade deal for the pawn.
                                SoundDefOf.ExecuteTrade.PlayOneShotOnCamera(null);
                                var pawn = TradeSession.trader as Pawn;
                                if (pawn != null)
                                    TaleRecorder.RecordTale(TaleDefOf.TradedWith, TradeSession.playerNegotiator, pawn);
                            }
                            // If not then the refund was already issued and the error displayed.

                            // Close the dialog.
                            Close(false);
                        }
                        else
                        {
                            LogWriter.WriteErrorMessage(
                                "Error processing order, RimWorld couldn't complete the trade.");
                        }

                        Event.current.Use();
                        Close();
                    }
                };
                if (TradeSession.deal.DoesTraderHaveEnoughSilver())
                {
                    action();
                }
                else
                {
                    FlashSilver();
                    SoundDefOf.ClickReject.PlayOneShotOnCamera(null);
                    Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("ConfirmTraderShortFunds".Translate(),
                        action, false, null));
                }

                Event.current.Use();
            }

            var rect10 = new Rect(rect9.x - 10f - OtherBottomButtonSize.x, rect9.y, OtherBottomButtonSize.x,
                OtherBottomButtonSize.y);
            if (Widgets.ButtonText(rect10, "ResetButton".Translate(), true, false, true))
            {
220
                SoundDefOf.Tick_Low.PlayOneShotOnCamera(null);
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
                TradeSession.deal.Reset();
                Utilities.SetTradablesPrice();
                CacheTradeables();
                Event.current.Use();
            }

            var rect11 = new Rect(rect9.xMax + 10f, rect9.y, OtherBottomButtonSize.x, OtherBottomButtonSize.y);
            if (Widgets.ButtonText(rect11, "CancelButton".Translate(), true, false, true))
            {
                Close(true);
                Event.current.Use();
            }

            if (_filterOnlyColonyItems != _filterSettingLastFrame)
            {
                _filterSettingLastFrame = _filterOnlyColonyItems;
                CacheTradeables();
                Event.current.Use();
            }
        }

        public override void PostOpen()
        {
            Utilities.SetTradablesPrice();
            CacheTradeables();
        }

        private void CacheTradeables()
        {
250
            // Get Silver
251
252
253
            _cachedCurrencyTradeable = (from x in TradeSession.deal.AllTradeables
                where x.IsCurrency
                select x).FirstOrDefault();
254
255
256
257
258
259
260
261
262

#if DEBUG
            foreach (var tr in TradeSession.deal.AllTradeables)
                LogWriter.WriteMessage(
                    $"Item {tr.AnyThing.GetInnerIfMinified().def} is minified: {tr.AnyThing.def.Minifiable}, " +
                    $"Belongs in Categories {string.Join(", ", tr.AnyThing.GetInnerIfMinified().def.thingCategories.Select(t => t.ToString()).ToArray())} ");
#endif


263
264
            _cachedTradeables = (from tr in TradeSession.deal.AllTradeables
                    where !tr.IsCurrency
265
266
                    where !tr.Label.NullOrEmpty() &&
                          tr.Label.ToLowerInvariant().Contains(_textFilter.ToLowerInvariant())
267
268
                    where _filter.DescendantThingDefs.Contains(tr.FirstThingColony?.GetInnerIfMinified().def) ||
                          !_filterOnlyColonyItems &&
269
270
                          _filter.DescendantThingDefs.Contains(tr.FirstThingTrader?.GetInnerIfMinified().def)
                    orderby tr.ThingDef.defName descending
271
                    select tr).ThenBy(tr => tr, _sorter1.Comparer).ThenBy(tr => tr, _sorter2.Comparer)
272
                .ThenBy(TransferableUIUtility.DefaultListOrderPriority).ThenBy(tr => tr.ThingDef.label)
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
                .ThenBy(
                    delegate(Tradeable tr)
                    {
                        QualityCategory result;
                        if (tr.AnyThing.TryGetQuality(out result)) return (int) result;
                        return -1;
                    }).ThenBy(tr => tr.AnyThing.HitPoints).ToList();
        }

        private void DoTransferableSorters(Action<TransferableSorterDef> sorter1Setter,
            Action<TransferableSorterDef> sorter2Setter, Action<ThingCategoryDef> filterSetter)
        {
            var position = new Rect(0f, 0f, 690f, 27f);
            GUI.BeginGroup(position);

            // Add sort by label
            Text.Font = GameFont.Tiny;
            var rect = new Rect(0f, 0f, 60f, 27f);
            Text.Anchor = TextAnchor.MiddleLeft;
            Widgets.Label(rect, "SortBy".Translate());

            // Add sort drop down menu button
            Text.Anchor = TextAnchor.UpperLeft;
            var rect2 = new Rect(rect.xMax + 10f, 0f, 130f, 27f);
            if (Widgets.ButtonText(rect2, _sorter1.LabelCap, true, false, true))
                OpenSorterChangeFloatMenu(sorter1Setter);

            // Add secondadry sort drop down menu button
            var rect3 = new Rect(rect2.xMax + 10f, 0f, 130f, 27f);
            if (Widgets.ButtonText(rect3, _sorter2.LabelCap, true, false, true))
                OpenSorterChangeFloatMenu(sorter2Setter);

            // Add filter by label
            Text.Font = GameFont.Tiny;
            var rect4 = new Rect(rect3.xMax + 10f, 0f, 60f, 27f);
            Text.Anchor = TextAnchor.MiddleLeft;
            Widgets.Label(rect4, "Filter");

            // Add filter drop down menu button
            Text.Anchor = TextAnchor.UpperLeft;
            var rect5 = new Rect(rect4.xMax + 10f, 0f, 130f, 27f);

            if (Widgets.ButtonText(rect5, _filter.LabelCap, true, false, true)) OpenFilterChangeFloatMenu(filterSetter);

            // Add "Colony Items" checkbox
            Text.Font = GameFont.Tiny;
            //Rect rect6 = new Rect(rect5.xMax + 10f, 0f, 60f, 27f);
            //Text.Anchor = TextAnchor.MiddleLeft;
            //Widgets.Label(rect4, "My Items");

            // Add "Colony Items" checkbox
            Text.Anchor = TextAnchor.UpperLeft;
            var rect6 = new Rect(rect5.xMax + 10f, 0f, 130f, 24f);

            Widgets.CheckboxLabeled(rect6, "Own items only", ref _filterOnlyColonyItems, false);

            GUI.EndGroup();
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351

            position = new Rect(0f, 34f, 345f, 27f);

            GUI.BeginGroup(position);
            // Add text search label
            Text.Font = GameFont.Tiny;
            var rect7 = new Rect(0f, 0f, 60f, 27f);
            Text.Anchor = TextAnchor.MiddleLeft;
            Widgets.Label(rect7, "Search");

            // Add text field.
            var rect8 = new Rect(rect7.xMax + 10f, 0, 270f, 27f);
            var newText = Widgets.TextField(rect8, _textFilter);

            // Update tradables if the text has changed.
            if (newText != _textFilter)
            {
                _textFilter = newText;
                CacheTradeables();
            }

            GUI.EndGroup();
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
        }

        private void FillMainRect(Rect mainRect)
        {
            Text.Font = GameFont.Small;
            var height = 6f + _cachedTradeables.Count * 30f;
            var viewRect = new Rect(0f, 0f, mainRect.width - 16f, height);
            Widgets.BeginScrollView(mainRect, ref _scrollPosition, viewRect, true);
            var num = 6f;
            var num2 = _scrollPosition.y - 30f;
            var num3 = _scrollPosition.y + mainRect.height;
            var num4 = 0;
            for (var i = 0; i < _cachedTradeables.Count; i++)
            {
                if (num > num2 && num < num3)
                {
                    var rect = new Rect(0f, num, viewRect.width, 30f);
                    var countToTransfer = _cachedTradeables[i].CountToTransfer;
                    TradeUI.DrawTradeableRow(rect, _cachedTradeables[i], num4);
                }

                num += 30f;
                num4++;
            }

            Widgets.EndScrollView();
        }

        private void DrawDiscount(Rect rect)
        {
382
            GUI.DrawTexture(rect, GlitterWorldAssets.TextureTradeDiscount);
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
        }

        private void OpenFilterChangeFloatMenu(Action<ThingCategoryDef> filterSetter)
        {
            var list = new List<FloatMenuOption>();

            // Enumerate list of ThingCategoryDef and add to menu options.
            var allDefsListForReading = DefDatabase<ThingCategoryDef>.AllDefsListForReading;
            for (var i = 0; i < allDefsListForReading.Count; i++)
            {
                var def = allDefsListForReading[i];

                // We'll never deal with corpses so don't show them.
                if (!def.LabelCap.ToLower().Contains("corpse"))
                    list.Add(new FloatMenuOption(def.LabelCap, delegate { filterSetter(def); },
                        MenuOptionPriority.Default, null, null, 0f, null, null));
            }

            Find.WindowStack.Add(new FloatMenu(list));
        }

        private void OpenSorterChangeFloatMenu(Action<TransferableSorterDef> sorterSetter)
        {
            var list = new List<FloatMenuOption>();
            var allDefsListForReading = DefDatabase<TransferableSorterDef>.AllDefsListForReading;
            for (var i = 0; i < allDefsListForReading.Count; i++)
            {
                var def = allDefsListForReading[i];
                list.Add(new FloatMenuOption(def.LabelCap, delegate { sorterSetter(def); }, MenuOptionPriority.Default,
                    null, null, 0f, null, null));
            }

            Find.WindowStack.Add(new FloatMenu(list));
        }

        public override void Close(bool doCloseSound = true)
        {
            Utilities.GetMapComponent(TradeSession.playerNegotiator.Map).ResetTradeShip();
            base.Close(doCloseSound);
        }

        #endregion
    }
426
}