summaryrefslogtreecommitdiffstats
path: root/stone_soup/crawl-ref/source/stash.cc
blob: dbdfef440df1210442b8b9046a6782b9b3052cf3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
220
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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
382
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
/*
 *  File:       stash.cc
 *  Summary:    Classes tracking player stashes
 *  Written by: Darshan Shaligram
 */

#include "AppHdr.h"
#include "chardump.h"
#include "clua.h"
#include "describe.h"
#include "itemname.h"
#include "itemprop.h"
#include "files.h"
#include "invent.h"
#include "items.h"
#include "Kills.h"
#include "libutil.h"
#include "menu.h"
#include "shopping.h"
#include "spl-book.h"
#include "stash.h"
#include "stuff.h"
#include "tags.h"
#include "travel.h"

#include <cctype>
#include <cstdio>
#include <fstream>
#include <algorithm>

#ifdef STASH_TRACKING

#define ST_MAJOR_VER ((unsigned char) 4)
#define ST_MINOR_VER ((unsigned char) 4)

#define LUA_SEARCH_ANNOTATE "ch_stash_search_annotate_item"
#define LUA_DUMP_ANNOTATE   "ch_stash_dump_annotate_item"
#define LUA_VIEW_ANNOTATE   "ch_stash_view_annotate_item"

std::string short_place_name(level_id id)
{
    return short_place_name(
            get_packed_place(id.branch, id.depth, LEVEL_DUNGEON));
}

std::string userdef_annotate_item(const char *s, const item_def *item,
                                  bool exclusive)
{
#ifdef CLUA_BINDINGS
    if (exclusive)
        lua_set_exclusive_item(item);
    std::string ann;
    clua.callfn(s, "u>s", item, &ann);
    if (exclusive)
        lua_set_exclusive_item(NULL);
    return (ann);
    
#else
    return ("");
#endif
}

std::string stash_annotate_item(const char *s,
                                const item_def *item,
                                bool exclusive = false)
{
    std::string text = userdef_annotate_item(s, item, exclusive);
    if ( (item->base_type == OBJ_BOOKS &&
            item_type_known(*item) &&
            item->sub_type != BOOK_MANUAL &&
            item->sub_type != BOOK_DESTRUCTION)
         || count_staff_spells(*item, true) > 1 )
    {
        formatted_string fs;
        item_def dup = *item;
        spellbook_contents( dup, 
                item->base_type == OBJ_BOOKS? 
                    RBOOK_READ_SPELL
                  : RBOOK_USE_STAFF, 
                &fs );
        text += EOL;
        text += fs.tostring(2, -2);
    }
    return text;
}

bool is_stash(int x, int y)
{
    LevelStashes *ls = stashes.find_current_level();
    if (ls)
    {
        Stash *s = ls->find_stash(x, y);
        return s && s->enabled;
    }
    return false;
}

void describe_stash(int x, int y)
{
    LevelStashes *ls = stashes.find_current_level();
    if (ls)
    {
        Stash *s = ls->find_stash(x, y);
        if (s)
        {
            std::string desc = "[Stash: " 
                       + s->description() + "]";
            mpr(desc.c_str());
        }
    }
}

static void fully_identify_item(item_def *item)
{
    if (!item || !is_valid_item(*item))
        return;

    set_ident_flags( *item, ISFLAG_IDENT_MASK );
    if (item->base_type != OBJ_WEAPONS)
        set_ident_type( item->base_type, 
                        item->sub_type, 
                        ID_KNOWN_TYPE );
}

static void save_item(FILE *file, const item_def &item)
{
    writeByte(file, item.base_type);
    writeByte(file, item.sub_type);
    writeShort(file, item.plus);
    writeShort(file, item.plus2);
    writeLong(file, item.special);
    writeShort(file, item.quantity);
    writeByte(file, item.colour);
    writeLong(file, item.flags);
}

static void load_item(FILE *file, item_def &item)
{
    item.base_type  = readByte(file);
    item.sub_type   = readByte(file);
    item.plus       = readShort(file);
    item.plus2      = readShort(file);
    item.special    = readLong(file);
    item.quantity   = readShort(file);
    item.colour     = readByte(file);
    item.flags      = readLong(file);
}

bool Stash::aggressive_verify = true;
std::vector<item_def> Stash::filters;

Stash::Stash(int xp, int yp) : enabled(true), items()
{
    // First, fix what square we're interested in
    if (xp == -1)
    {
        xp = you.x_pos;
        yp = you.y_pos;
    }
    x = (unsigned char) xp;
    y = (unsigned char) yp;
    abspos = GXM * (int) y + x;

    update();
}

bool Stash::are_items_same(const item_def &a, const item_def &b)
{
    return a.base_type == b.base_type &&
           a.sub_type == b.sub_type &&
           a.plus == b.plus &&
           a.plus2 == b.plus2 &&
           a.special == b.special &&
           a.colour == b.colour &&
           a.flags == b.flags &&
           a.quantity == b.quantity;
}

void Stash::filter(const std::string &str)
{
    std::string base = str;

    base.erase(base.find_last_not_of(" \n\t") + 1);
    base.erase(0, base.find_first_not_of(" \n\t"));

    unsigned char subc = 255;
    std::string::size_type cpos = base.find(":", 0);
    if (cpos != std::string::npos)
    {
        std::string subs = base.substr(cpos + 1);
        subc = atoi(subs.c_str());

        base = base.substr(0, cpos);
    }

    unsigned char basec = atoi(base.c_str());
    filter(basec, subc);
}

void Stash::filter(unsigned char base, unsigned char sub)
{
    item_def item;
    item.base_type = base;
    item.sub_type  = sub;

    filters.push_back(item);
}

bool Stash::is_filtered(const item_def &item)
{
    for (int i = 0, count = filters.size(); i < count; ++i)
    {
        const item_def &filter = filters[i];
        if (item.base_type == filter.base_type &&
                (filter.sub_type == 255 ||
                 item.sub_type == filter.sub_type))
            return true;
    }
    return false;
}

void Stash::update()
{
    int objl = igrd[x][y];
    // If this is your position, you know what's on this square
    if (x == you.x_pos && y == you.y_pos)
    {
        // Zap existing items
        items.clear();

        // Now, grab all items on that square and fill our vector
        while (objl != NON_ITEM)
        {
            if (!is_filtered(mitm[objl]))
                items.push_back(mitm[objl]);
            objl = mitm[objl].link;
        }

        verified = true;
    }
    // If this is not your position, the only thing we can do is verify that
    // what the player sees on the square is the first item in this vector.
    else
    {
        if (objl == NON_ITEM)
        {
            items.clear();
            verified = true;
            return ;
        }

        // There's something on this square. Take a squint at it.
        item_def &item = mitm[objl];

        if (item.link == NON_ITEM) items.clear();

        // We knew of nothing on this square, so we'll assume this is the 
        // only item here, but mark it as unverified unless we can see nothing
        // under the item.
        if (items.size() == 0)
        {
            if (!is_filtered(item))
                items.push_back(item);
            verified = (item.link == NON_ITEM);
            return ;
        }

        // There's more than one item in this pile. As long as the top item is
        // not filtered, we can check to see if it matches what we think the
        // top item is.

        if (is_filtered(item)) return;

        item_def &first = items[0];
        // Compare these items
        if (!are_items_same(first, item))
        {
            if (aggressive_verify)
            {
                // See if 'item' matches any of the items we have. If it does,
                // we'll just make that the first item and leave 'verified'
                // unchanged.

                // Start from 1 because we've already checked items[0]
                for (int i = 1, count = items.size(); i < count; ++i)
                {
                    if (are_items_same(items[i], item))
                    {
                        // Found it. Swap it to the front of the vector.
                        item_def temp   = items[i];
                        items[i]        = items[0];
                        items[0]        = temp;

                        // We don't set verified to true. If this stash was
                        // already unverified, it remains so.
                        return;
                    }
                }
            }

            // If this is unverified, forget last item on stack. This isn't
            // terribly clever, but it prevents the vector swelling forever.
            if (!verified) items.pop_back();

            // Items are different. We'll put this item in the front of our 
            // vector, and mark this as unverified
            items.insert(items.begin(), item);
            verified = false;
        }
    }
}

// Returns the item name for a given item, with any appropriate
// stash-tracking pre/suffixes.
std::string Stash::stash_item_name(const item_def &item)
{
    char buf[ITEMNAME_SIZE];
    
    if (item.base_type == OBJ_GOLD)
        snprintf(buf, sizeof buf, "%d gold piece%s", item.quantity, 
                    (item.quantity > 1? "s" : ""));
    else
        item_name(item, DESC_NOCAP_A, buf, false);

    return buf;
}

class StashMenu : public Menu
{
public:
    StashMenu() : Menu(MF_SINGLESELECT), can_travel(false) { }
public:
    bool can_travel;
protected:
    void draw_title();
    bool process_key(int key);
};

void StashMenu::draw_title()
{
    if (title)
    {
        gotoxy(1, 1);
        textcolor(title->colour);
        cprintf(title->text.c_str());
        if (title->quantity)
            cprintf(", %d item%s", title->quantity, 
                                   title->quantity == 1? "" : "s");
        cprintf(")");
        if (can_travel)
            cprintf("  [ENTER - travel]");
    }
}

bool StashMenu::process_key(int key)
{
    if (key == CK_ENTER)
    {
        // Travel activates.
        lastch = 1;
        return false;
    }
    return Menu::process_key(key);
}

static void stash_menu_fixup(MenuEntry *me)
{
    const item_def *item = static_cast<const item_def *>( me->data );
    if (item->base_type == OBJ_GOLD)
    {
        me->quantity = 0;
        me->colour   = DARKGREY;
    }
}

bool Stash::show_menu(const std::string &prefix, bool can_travel) const
{
    StashMenu menu;

    MenuEntry *mtitle = new MenuEntry("  Stash (" + prefix);
    menu.can_travel = can_travel;
    mtitle->colour   = WHITE;
    mtitle->quantity = items.size();
    menu.set_title(mtitle);

    populate_item_menu(&menu, items, stash_menu_fixup);
    std::vector<MenuEntry*> sel;
    while (true)
    {
        sel = menu.show();
        if (menu.getkey() == 1)
            return true;
        
        if (sel.size() != 1)
            break;

        const item_def *item = 
                static_cast<const item_def *>( sel[0]->data );
        describe_item(*item);
    }
    return false;
}

std::string Stash::description() const
{
    if (!enabled || items.empty())
        return ("");

    const item_def &item = items[0];
    std::string desc = stash_item_name(item);
    
    size_t sz = items.size();
    if (sz > 1)
    {
        char additionals[50];
        snprintf(additionals, sizeof additionals, " (+%lu)", (unsigned long) (sz - 1));
        desc += additionals;
    }
    return (desc);
}

bool Stash::matches_search(const std::string &prefix,
                           const base_pattern &search,
                           stash_search_result &res) const
{
    if (!enabled || items.empty()) return false;

    for (unsigned i = 0; i < items.size(); ++i)
    {
        const item_def &item = items[i];
        std::string s = stash_item_name(item);
        std::string ann = stash_annotate_item(
                    LUA_SEARCH_ANNOTATE, &item);
        if (search.matches(prefix + " " + ann + s))
        {
            if (!res.count++)
                res.match = s;
            res.matches += item.quantity;
            continue;
        }

        if (is_dumpable_artifact(item, Options.verbose_dump))
        {
            std::string desc = munge_description(get_item_description(item, 
                                                          Options.verbose_dump,
                                                          true ));
            if (search.matches(desc))
            {
                if (!res.count++)
                    res.match = s;
                res.matches += item.quantity;
            }
        }
    }
    if (res.matches)
    {
        res.stash = this;
        res.pos.x = x;
        res.pos.y = y;
    }

    return !!res.matches;
}

void Stash::write(std::ostream &os, 
                  int refx, int refy, 
                  std::string place,
                  bool identify) 
    const
{
    if (!enabled || (items.size() == 0 && verified)) return;
    os << "(" << ((int) x - refx) << ", " << ((int) y - refy)
       << (place.length()? ", " + place : "")
       << ")"
       << std::endl;
    
    char buf[ITEMNAME_SIZE];
    for (int i = 0; i < (int) items.size(); ++i)
    {
        item_def item = items[i];

        if (identify)
            fully_identify_item(&item);

        std::string s = stash_item_name(item);
        strncpy(buf, s.c_str(), sizeof buf);

        std::string ann = userdef_annotate_item(
                LUA_DUMP_ANNOTATE, &item);

        if (!ann.empty())
        {
            trim_string(ann);
            ann = " " + ann;
        }

        os << "  " << buf
           << (!ann.empty()? ann : std::string())
           << (!verified && (items.size() > 1 || i)? " (still there?)" : "")
           << std::endl;

        if (is_dumpable_artifact(item, Options.verbose_dump))
        {
            std::string desc = munge_description(get_item_description(item, 
                                                          Options.verbose_dump,
                                                          true ));
            // Kill leading and trailing whitespace
            desc.erase(desc.find_last_not_of(" \n\t") + 1);
            desc.erase(0, desc.find_first_not_of(" \n\t"));
            // If string is not-empty, pad out to a neat indent
            if (desc.length())
            {
                // Walk backwards and prepend indenting spaces to \n characters
                for (int j = desc.length() - 1; j >= 0; --j)
                    if (desc[j] == '\n')
                        desc.insert(j + 1, " ");
                os << "    " << desc << std::endl;
            }
        }
    }

    if (items.size() <= 1 && !verified)
        os << "  (unseen)" << std::endl;
}

void Stash::save(FILE *file) const
{
    // How many items on this square?
    writeShort(file, (short) items.size());

    writeByte(file, x);
    writeByte(file, y);

    // Note: Enabled save value is inverted logic, so that it defaults to true
    writeByte(file, 
        (unsigned char) ((verified? 1 : 0) | (!enabled? 2 : 0)) );

    // And dump the items individually. We don't bother saving fields we're
    // not interested in (and don't anticipate being interested in).
    for (unsigned i = 0; i < items.size(); ++i)
        save_item(file, items[i]);
}

void Stash::load(FILE *file)
{
    // How many items?
    int count = readShort(file);

    x = readByte(file);
    y = readByte(file);

    unsigned char flags = readByte(file);
    verified = (flags & 1) != 0;

    // Note: Enabled save value is inverted so it defaults to true.
    enabled  = (flags & 2) == 0;

    abspos = GXM * (int) y + x;

    // Zap out item vector, in case it's in use (however unlikely)
    items.clear();
    // Read in the items
    for (int i = 0; i < count; ++i)
    {
        item_def item;
        load_item(file, item);

        items.push_back(item);
    }
}

std::ostream &operator << (std::ostream &os, const Stash &s)
{
    s.write(os);
    return os;
}

ShopInfo::ShopInfo(int xp, int yp) : x(xp), y(yp), name(), shoptype(-1),
                                     visited(false), items()
{
    // Most of our initialization will be done externally; this class is really
    // a mildly glorified struct.
    const shop_struct *sh = get_shop(x, y);
    if (sh)
        shoptype = sh->type;
}

ShopInfo::ShopId::ShopId(int stype) : shoptype(stype), id()
{
    shop_init_id_type( shoptype, id );
}

ShopInfo::ShopId::~ShopId()
{
    shop_uninit_id_type( shoptype, id );
}

void ShopInfo::add_item(const item_def &sitem, unsigned price)
{
    shop_item it;
    it.item  = sitem;
    it.price = price;
    items.push_back(it);
}

std::string ShopInfo::shop_item_name(const shop_item &si) const
{
    char shopitem[ITEMNAME_SIZE * 2];
    std::string itemname = Stash::stash_item_name(si.item);
    snprintf(shopitem, sizeof shopitem, "%s (%u gold)", 
            itemname.c_str(), si.price);
    return shopitem;   
}

std::string ShopInfo::shop_item_desc(const shop_item &si) const
{
    std::string desc;
    if (is_dumpable_artifact(si.item, Options.verbose_dump))
    {
        desc = munge_description(get_item_description(si.item, 
                    Options.verbose_dump,
                    true));

        // trim leading whitespace
        std::string::size_type notwhite = desc.find_first_not_of(" \t\n");
        desc.erase(0, notwhite);

        // trim trailing whitespace
        notwhite = desc.find_last_not_of(" \t\n"); 
        desc.erase(notwhite + 1);
        
        // Walk backwards and prepend indenting spaces to \n characters
        for (int i = desc.length() - 1; i >= 0; --i)
            if (desc[i] == '\n')
                desc.insert(i + 1, " ");
    }
    return desc;
}

void ShopInfo::describe_shop_item(const shop_item &si) const
{
    describe_item( si.item );
}

bool ShopInfo::show_menu(const std::string &place,
                         bool can_travel) const
{
    ShopId id(shoptype);
    StashMenu menu;

    MenuEntry *mtitle = new MenuEntry("  " + name + " (" + place);
    menu.can_travel = can_travel;
    mtitle->colour   = WHITE;
    mtitle->quantity = items.size();
    menu.set_title(mtitle);

    menu_letter hotkey;
    if (items.empty())
    {
        MenuEntry *me = new MenuEntry(
                visited? "  (Shop is empty)" : "  (Shop contents are unknown)",
                MEL_ITEM,
                0,
                0);
        me->colour = DARKGREY;
        menu.add_entry(me);
    }
    else
    {
        for (int i = 0, count = items.size(); i < count; ++i)
        {
            MenuEntry *me = new MenuEntry(shop_item_name(items[i]),
                                          MEL_ITEM,
                                          1,
                                          hotkey++);
            me->data = const_cast<shop_item *>( &items[i] );
            menu.add_entry(me);
        }
    }

    std::vector<MenuEntry*> sel;
    while (true)
    {
        sel = menu.show();
        if (menu.getkey() == 1)
            return true;
        
        if (sel.size() != 1)
            break;

        const shop_item *item = 
                static_cast<const shop_item *>( sel[0]->data );
        describe_shop_item(*item);
    }
    return false;
}

std::string ShopInfo::description() const
{
    return (name);
}

bool ShopInfo::matches_search(const std::string &prefix,  
                              const base_pattern &search, 
                              stash_search_result &res) const
{
    if (items.empty() && visited) return false;

    ShopId id(shoptype);
    bool match = false;

    for (unsigned i = 0; i < items.size(); ++i)
    {
        std::string name = shop_item_name(items[i]);
        std::string ann = stash_annotate_item(
                    LUA_SEARCH_ANNOTATE, &items[i].item, true);
        
        bool thismatch = false;
        if (search.matches(prefix + " " + ann + name))
            thismatch = true;
        else
        {
            std::string desc = shop_item_desc(items[i]);
            if (search.matches(desc))
                thismatch = true;
        }

        if (thismatch)
        {
            if (!res.count++)
                res.match = name;
            res.matches++;
        }
    }

    if (!res.matches)
    {
        std::string shoptitle = prefix + " {shop} " + name;
        if (!visited && items.empty())
            shoptitle += "*";
        if (search.matches(shoptitle))
        {
            match = true;
            res.match = name;
        }
    }

    if (match || res.matches)
    {
        res.shop = this;
        res.pos.x = x;
        res.pos.y = y;
    }
    
    return match || res.matches;
}

void ShopInfo::write(std::ostream &os, bool identify) const
{
    ShopId id(shoptype);

    os << "[Shop] " << name << std::endl;
    if (items.size() > 0)
    {
        for (unsigned i = 0; i < items.size(); ++i)
        {
            shop_item item = items[i];

            if (identify)
                fully_identify_item(&item.item);

            os << "  " << shop_item_name(item) << std::endl;
            std::string desc = shop_item_desc(item);
            if (desc.length() > 0)
                os << "    " << desc << std::endl;
        }
    }
    else if (visited)
        os << "  (Shop is empty)" << std::endl;
    else
        os << "  (Shop contents are unknown)" << std::endl;
}

void ShopInfo::save(FILE *file) const
{
    writeShort(file, shoptype);

    int mangledx = (short) x;
    if (!visited)
        mangledx |= 1024;
    writeShort(file, mangledx);
    writeShort(file, (short) y);

    writeShort(file, (short) items.size());

    writeString(file, name);

    for (unsigned i = 0; i < items.size(); ++i)
    {
        save_item(file, items[i].item);
        writeShort(file, (short) items[i].price );
    }
}

void ShopInfo::load(FILE *file)
{
    shoptype = readShort(file);

    x = readShort(file);
    visited = !(x & 1024);
    x &= 0xFF;

    y = readShort(file);

    int itemcount = readShort(file);

    name = readString(file);
    for (int i = 0; i < itemcount; ++i)
    {
        shop_item item;
        load_item(file, item.item);
        item.price = (unsigned) readShort(file);
        items.push_back(item);
    }
}

std::ostream &operator << (std::ostream &os, const ShopInfo &s)
{
    s.write(os);
    return os;
}

LevelStashes::LevelStashes()
{
    branch = you.where_are_you;
    depth  = you.your_level;
}

bool LevelStashes::operator < (const LevelStashes &lev) const
{
    return branch < lev.branch || (branch == lev.branch && depth < lev.depth);
}

bool LevelStashes::isBelowPlayer() const
{
    return branch > you.where_are_you 
        || (branch == you.where_are_you && depth > you.your_level);
}

Stash *LevelStashes::find_stash(int x, int y)
{
    if (x == -1 || y == -1)
    {
        x = you.x_pos;
        y = you.y_pos;
    }
    const int abspos = (GXM * y) + x;
    c_stashes::iterator st = stashes.find(abspos);
    return (st == stashes.end()? NULL : &st->second);
}

const ShopInfo *LevelStashes::find_shop(int x, int y) const
{
    for (unsigned i = 0; i < shops.size(); ++i)
    {
        if (shops[i].isAt(x, y))
            return (&shops[i]);
    }
    return (NULL);
}

ShopInfo &LevelStashes::get_shop(int x, int y)
{
    for (unsigned i = 0; i < shops.size(); ++i)
    {
        if (shops[i].isAt(x, y))
            return shops[i];
    }
    ShopInfo si(x, y);
    si.set_name(shop_name(x, y));
    shops.push_back(si);
    return get_shop(x, y);
}

// Updates the stash at (x,y). Returns true if there was a stash at (x,y), false
// otherwise.
bool LevelStashes::update_stash(int x, int y)
{
    Stash *s = find_stash(x, y);
    if (s)
    {
        s->update();
        if (s->empty())
            kill_stash(*s);
        return true;
    }
    return false;
}

// Removes a Stash from the level.
void LevelStashes::kill_stash(const Stash &s)
{
    stashes.erase(s.abs_pos());
}

void LevelStashes::no_stash(int x, int y)
{
    Stash *s = find_stash(x, y);
    bool en = false;
    if (s)
    {
        en = s->enabled = !s->enabled;
        s->update();
        if (s->empty())
            kill_stash(*s);
    }
    else
    {
        Stash newStash(x, y);
        newStash.enabled = false;

        stashes[ newStash.abs_pos() ] = newStash;
    }

    mpr(en? "I'll no longer ignore what I see on this square."
        : "Ok, I'll ignore what I see on this square.");
}

void LevelStashes::add_stash(int x, int y)
{
    Stash *s = find_stash(x, y);
    if (s)
    {
        s->update();
        if (s->empty())
            kill_stash(*s);
    }
    else
    {
        Stash newStash(x, y);
        if (!newStash.empty())
            stashes[ newStash.abs_pos() ] = newStash;
    }
}

bool LevelStashes::isCurrent() const
{
    return branch == you.where_are_you && depth == you.your_level;
}

bool LevelStashes::in_hell() const
{
    return branch >= BRANCH_DIS 
            && branch <= BRANCH_THE_PIT
            && branch != BRANCH_VESTIBULE_OF_HELL;
}

bool LevelStashes::in_branch(int branchid) const
{
    return branch == branchid;
}


std::string LevelStashes::level_name() const
{
    int curr_subdungeon_level = subdungeon_depth( branch, depth );
    return (branch_level_name(branch, curr_subdungeon_level));
}

std::string LevelStashes::short_level_name() const
{
    return (short_place_name(
            get_packed_place( branch, 
                subdungeon_depth( branch, depth ),
                LEVEL_DUNGEON ) ));
}

int LevelStashes::count_stashes() const
{
    int rawcount = stashes.size();
    if (!rawcount)
        return (0);

    for (c_stashes::const_iterator iter = stashes.begin(); 
            iter != stashes.end(); iter++)
    {
        if (!iter->second.enabled)
            --rawcount;
    }
    return rawcount;
}

void LevelStashes::get_matching_stashes(
        const base_pattern &search,
        std::vector<stash_search_result> &results)
    const
{
    level_id clid(branch, subdungeon_depth(branch, depth));
    std::string lplace = "{" + short_place_name(clid) + "}";
    for (c_stashes::const_iterator iter = stashes.begin();
            iter != stashes.end(); iter++)
    {
        if (iter->second.enabled)
        {
            stash_search_result res;
            if (iter->second.matches_search(lplace, search, res))
            {
                res.level = clid;
                results.push_back(res);
            }
        }
    }

    for (unsigned i = 0; i < shops.size(); ++i)
    {
        stash_search_result res;
        if (shops[i].matches_search(lplace, search, res))
        {
            res.level = clid;
            results.push_back(res);
        }
    }
}

void LevelStashes::write(std::ostream &os, bool identify) const
{
    if (visible_stash_count() == 0) return ;
    os << level_name() << std::endl;

    for (unsigned i = 0; i < shops.size(); ++i)
    {
        shops[i].write(os, identify);
    }

    if (stashes.size())
    {
        const Stash &s = stashes.begin()->second;
        int refx = s.getX(), refy = s.getY();
        std::string level_name = short_level_name();
        for (c_stashes::const_iterator iter = stashes.begin(); 
                iter != stashes.end(); iter++)
        {
            iter->second.write(os, refx, refy, level_name, identify);
        }
    }
    os << std::endl;
}

void LevelStashes::save(FILE *file) const
{
    // How many stashes on this level?
    writeShort(file, (short) stashes.size());

    writeByte(file, branch);
    writeShort(file, (short) depth);

    // And write the individual stashes
    for (c_stashes::const_iterator iter = stashes.begin(); 
            iter != stashes.end(); iter++)
        iter->second.save(file);

    writeShort(file, (short) shops.size());
    for (unsigned i = 0; i < shops.size(); ++i)
        shops[i].save(file);
}

void LevelStashes::load(FILE *file)
{
    int size = readShort(file);

    branch = readByte(file);
    depth  = readShort(file);

    stashes.clear();
    for (int i = 0; i < size; ++i)
    {
        Stash s;
        s.load(file);
        if (!s.empty())
            stashes[ s.abs_pos() ] = s;
    }

    shops.clear();
    int shopc = readShort(file);
    for (int i = 0; i < shopc; ++i)
    {
        ShopInfo si(0, 0);
        si.load(file);
        shops.push_back(si);
    }
}

std::ostream &operator << (std::ostream &os, const LevelStashes &ls)
{
    ls.write(os);
    return os;
}

LevelStashes &StashTracker::get_current_level()
{
    std::vector<LevelStashes>::iterator iter = levels.begin();
    for ( ; iter != levels.end() && !iter->isBelowPlayer(); iter++)
    {
        if (iter->isCurrent()) return *iter;
    }
    if (iter == levels.end())
        levels.push_back(LevelStashes());
    else
        levels.insert(iter, LevelStashes());
    return get_current_level();
}

LevelStashes *StashTracker::find_current_level()
{
    std::vector<LevelStashes>::iterator iter = levels.begin();
    for ( ; iter != levels.end() && !iter->isBelowPlayer(); iter++)
    {
        if (iter->isCurrent()) return &*iter;
    }
    return NULL;
}


bool StashTracker::update_stash(int x, int y)
{
    LevelStashes *lev = find_current_level();
    if (lev)
    {
        bool res = lev->update_stash(x, y);
        if (!lev->stash_count())
            remove_level(*lev);
        return res;
    }
    return false;
}

void StashTracker::remove_level(const LevelStashes &ls)
{
    std::vector<LevelStashes>::iterator iter = levels.begin();
    for ( ; iter != levels.end(); ++iter)
    {
        if (&ls == &*iter)
        {
            levels.erase(iter);
            break ;
        }
    }
}

void StashTracker::no_stash(int x, int y)
{
    if (is_level_untrackable())
        return ;
    LevelStashes &current = get_current_level();
    current.no_stash(x, y);
    if (!current.stash_count())
        remove_level(current);
}

void StashTracker::add_stash(int x, int y, bool verbose)
{
    if (is_level_untrackable())
        return ;
    LevelStashes &current = get_current_level();
    current.add_stash(x, y);

    if (verbose)
    {
        Stash *s = current.find_stash(x, y);
        if (s && s->enabled)
            mpr("Added stash.");
    }
    
    if (!current.stash_count())
        remove_level(current);
}

void StashTracker::dump(const char *filename, bool identify) const
{
    std::ofstream outf(filename);
    if (outf)
    {
        write(outf, identify);
        outf.close();
    }
}

void StashTracker::write(std::ostream &os, bool identify) const
{
    os << you.your_name << std::endl << std::endl;
    if (!levels.size())
        os << "  You have no stashes." << std::endl;
    else
    {
        std::vector<LevelStashes>::const_iterator iter = levels.begin();
        for ( ; iter != levels.end(); iter++)
        {
            iter->write(os, identify);
        }
    }
}

void StashTracker::save(FILE *file) const
{
    // Write version info first - major + minor
    writeByte(file, ST_MAJOR_VER);
    writeByte(file, ST_MINOR_VER);

    // How many levels have we?
    writeShort(file, (short) levels.size());

    // And ask each level to write itself to the tag
    std::vector<LevelStashes>::const_iterator iter = levels.begin();
    for ( ; iter != levels.end(); iter++)
        iter->save(file);
}

void StashTracker::load(FILE *file)
{
    // Check version. Compatibility isn't important, since stash-tracking
    // is non-critical.
    unsigned char major = readByte(file),
                  minor = readByte(file);
    if (major != ST_MAJOR_VER || minor != ST_MINOR_VER) return ;

    int count = readShort(file);

    levels.clear();
    for (int i = 0; i < count; ++i)
    {
        LevelStashes st;
        st.load(file);
        if (st.stash_count()) levels.push_back(st);
    }
}

void StashTracker::update_visible_stashes(
                                    StashTracker::stash_update_mode mode)
{
    if (is_level_untrackable())
        return ;

    LevelStashes *lev = find_current_level();
    for (int cy = 1; cy <= 17; ++cy)
    {
        for (int cx = 9; cx <= 25; ++cx)
        {
            int x = you.x_pos + cx - 17, y = you.y_pos + cy - 9;
            if (x < 0 || x >= GXM || y < 0 || y >= GYM)
                continue;
            
            if (!env.show[cx - 8][cy] && !(cx == 17 && cy == 9))
                continue;

            if ((!lev || !lev->update_stash(x, y))
                    && mode == ST_AGGRESSIVE 
                    && igrd[x][y] != NON_ITEM)
            {
                if (!lev)
                    lev = &get_current_level();
                lev->add_stash(x, y);
            }

            if (grd[x][y] == DNGN_ENTER_SHOP)
                get_shop(x, y);
        }
    }

    if (lev && !lev->stash_count())
        remove_level(*lev);
}

#define SEARCH_SPAM_THRESHOLD 400
static std::string lastsearch;
static input_history search_history(15);

void StashTracker::search_stashes()
{
    char prompt[200];
    if (lastsearch.length())
        snprintf(prompt, sizeof prompt,
                "Search your stashes for what item [Enter for \"%s\"]?",
                lastsearch.c_str());
    else
        snprintf(prompt, sizeof prompt,
                "Search your stashes for what item?");
    
    mpr(prompt, MSGCH_PROMPT);
    // Push the cursor down to the next line.
    mpr("", MSGCH_PROMPT);

    char buf[400];
    bool validline = cancelable_get_line(buf, sizeof buf, 80, &search_history);
    mesclr();
    if (!validline || (!*buf && !lastsearch.length()))
        return;

    std::string csearch = *buf? buf : lastsearch;
    std::vector<stash_search_result> results;

    base_pattern *search = NULL;

    text_pattern tpat( csearch, true );
    search = &tpat;

#ifdef CLUA_BINDINGS
    lua_text_pattern ltpat( csearch );
    
    if (lua_text_pattern::is_lua_pattern(csearch))
        search = &ltpat;
#endif

    if (!search->valid())
    {
        mpr("Your search expression is invalid.", MSGCH_PLAIN);
        return ;
    }

    lastsearch = csearch;
    
    get_matching_stashes(*search, results);

    if (results.empty())
    {
        mpr("That item is not present in any of your stashes.",
                MSGCH_PLAIN);
        return;
    }

    if (results.size() > SEARCH_SPAM_THRESHOLD)
    {
        mpr("Too many matches; use a more specific search.", MSGCH_PLAIN);
        return ;
    }

    display_search_results(results);
}

void StashTracker::get_matching_stashes(
        const base_pattern &search,
        std::vector<stash_search_result> &results)
    const
{
    std::vector<LevelStashes>::const_iterator iter = levels.begin();
    for ( ; iter != levels.end(); iter++)
    {
        iter->get_matching_stashes(search, results);
        if (results.size() > SEARCH_SPAM_THRESHOLD)
            return;
    }

    level_id curr = level_id::get_current_level_id();
    for (unsigned i = 0; i < results.size(); ++i)
    {
        results[i].player_distance = level_distance(curr, results[i].level);
    }

    // Sort stashes so that closer stashes come first and stashes on the same
    // levels with more items come first.
    std::sort(results.begin(), results.end());
}

class StashSearchMenu : public Menu
{
public:
    StashSearchMenu() : Menu(), can_travel(true), meta_key(0) { }

public:
    bool can_travel;
    int meta_key;

protected:
    bool process_key(int key);
    void draw_title();
};

void StashSearchMenu::draw_title()
{
    if (title)
    {
        gotoxy(1, 1);
        textcolor(title->colour);
        cprintf("  %d %s%s", title->quantity, title->text.c_str(), 
                           title->quantity > 1? "es" : "");

        if (meta_key)
            draw_title_suffix(" (x - examine stash)", false);
        else
            draw_title_suffix(" (x - go to stash; ? - examine stash)", false);
    }
}

bool StashSearchMenu::process_key(int key)
{
    if (key == '?')
    {
        if (sel)
            sel->clear();
        meta_key  = !meta_key;
        update_title();
        return true;
    }
    
    return Menu::process_key(key);
}

void StashTracker::display_search_results(
        std::vector<stash_search_result> &results)
{
    if (results.empty())
        return;
    
    bool travelable = can_travel_interlevel();

    StashSearchMenu stashmenu;
    stashmenu.can_travel = travelable;
    std::string title = "matching stash";

    MenuEntry *mtitle = new MenuEntry(title);
    mtitle->colour   = WHITE;
    // Abuse of the quantity field.
    mtitle->quantity = results.size();
    stashmenu.set_title(mtitle);

    menu_letter hotkey;
    for (unsigned i = 0; i < results.size(); ++i, ++hotkey)
    {
        stash_search_result &res = results[i];
        char matchtitle[ITEMNAME_SIZE];
        std::string place = short_place_name(res.level);
        if (res.matches > 1 && res.count > 1)
        {
            snprintf(matchtitle, sizeof matchtitle,
                    "[%s] %s (%d)",
                    place.c_str(),
                    res.match.c_str(),
                    res.matches);
        }
        else
        {
            snprintf(matchtitle, sizeof matchtitle,
                    "[%s] %s",
                    place.c_str(),
                    res.match.c_str());
        }
        std::string mename = matchtitle;
        
        MenuEntry *me = new MenuEntry(mename, MEL_ITEM, 1, hotkey);
        me->data = &res;
        if (res.shop && !res.shop->is_visited())
            me->colour = CYAN;
        stashmenu.add_entry(me);
    }

    stashmenu.set_flags( MF_SINGLESELECT );

    std::vector<MenuEntry*> sel;
    while (true)
    {
        sel = stashmenu.show();

        if (sel.size() == 1 && stashmenu.meta_key)
        {
            stash_search_result *res = 
                static_cast<stash_search_result *>(sel[0]->data);

            bool dotravel = false;
            if (res->shop)
            {
                dotravel = res->shop->show_menu(short_place_name(res->level),
                                                 travelable);
            }
            else if (res->stash)
            {
                dotravel = res->stash->show_menu(short_place_name(res->level),
                                                 travelable);
            }

            if (dotravel && travelable)
            {
                redraw_screen();
                level_pos lp;
                lp.id  = res->level;
                lp.pos = res->pos;
                start_translevel_travel(lp);
                return ;
            }
            continue;
        }
        break;
    }

    redraw_screen();
    if (travelable && sel.size() == 1 && !stashmenu.meta_key)
    {
        const stash_search_result *res = 
                static_cast<stash_search_result *>(sel[0]->data);
        level_pos lp;
        lp.id  = res->level;
        lp.pos = res->pos;
        start_translevel_travel(lp);
        return ;
    }

}

// Global
StashTracker stashes;

#endif

std::string branch_level_name(unsigned char branch, int sub_depth)
{
    int ltype = sub_depth == 0xFF? branch : 0;
    if (ltype == LEVEL_PANDEMONIUM)
        return ("Pandemonium");
    else if (ltype == LEVEL_ABYSS)
        return ("The Abyss");
    else if (ltype == LEVEL_LABYRINTH)
        return ("A Labyrinth");
    else
    {
        char buf[200];
        const char *s = NULL;
        *buf = 0;
        // level_type == LEVEL_DUNGEON
        if (branch != BRANCH_VESTIBULE_OF_HELL
                && branch != BRANCH_ECUMENICAL_TEMPLE
                && branch != BRANCH_HALL_OF_BLADES)
            snprintf(buf, sizeof buf, "Level %d", sub_depth);

        switch (branch)
        {
        case BRANCH_MAIN_DUNGEON:
            s = " of the Dungeon";
            break;
        case BRANCH_DIS:
            s = " of Dis";
            break;
        case BRANCH_GEHENNA:
            s = " of Gehenna";
            break;
        case BRANCH_VESTIBULE_OF_HELL:
            s = "The Vestibule of Hell";
            break;
        case BRANCH_COCYTUS:
            s = " of Cocytus";
            break;
        case BRANCH_TARTARUS:
            s = " of Tartarus";
            break;
        case BRANCH_INFERNO:
            s = " of the Inferno";
            break;
        case BRANCH_THE_PIT:
            s = " of the Pit";
            break;
        case BRANCH_ORCISH_MINES:
            s = " of the Orcish Mines";
            break;
        case BRANCH_HIVE:
            s = " of the Hive";
            break;
        case BRANCH_LAIR:
            s = " of the Lair";
            break;
        case BRANCH_SLIME_PITS:
            s = " of the Slime Pits";
            break;
        case BRANCH_VAULTS:
            s = " of the Vaults";
            break;
        case BRANCH_CRYPT:
            s = " of the Crypt";
            break;
        case BRANCH_HALL_OF_BLADES:
            s = "The Hall of Blades";
            break;
        case BRANCH_HALL_OF_ZOT:
            s = " of the Realm of Zot";
            break;
        case BRANCH_ECUMENICAL_TEMPLE:
            s = "The Ecumenical Temple";
            break;
        case BRANCH_SNAKE_PIT:
            s = " of the Snake Pit";
            break;
        case BRANCH_ELVEN_HALLS:
            s = " of the Elven Halls";
            break;
        case BRANCH_TOMB:
            s = " of the Tomb";
            break;
        case BRANCH_SWAMP:
            s = " of the Swamp";
            break;
        }
        if (s)
            strncat(buf, s, sizeof(buf) - 1);
        return (buf);
    }
}

std::string branch_level_name(unsigned short packed_place)
{
    return branch_level_name(packed_place >> 8, packed_place & 0xFF);
}