-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSACharacterWindowController.m
More file actions
3151 lines (2684 loc) · 134 KB
/
DSACharacterWindowController.m
File metadata and controls
3151 lines (2684 loc) · 134 KB
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
/*
Project: DSA-SpielHelfer
Copyright (C) 2024 Free Software Foundation
Author: Sebastian Reitenbach
Created: 2024-09-07 23:41:00 +0200 by sebastia
This application is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This application is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/
#import <objc/message.h>
#import <objc/runtime.h>
#import "DSACharacterWindowController.h"
#import "DSACharacterDocument.h"
#import "DSACharacter.h"
#import "DSATalent.h"
#import "DSASpell.h"
#import "DSALiturgy.h"
#import "NSFlippedView.h"
#import "DSACharacterViewModel.h"
#import "DSACharacterStatusView.h"
#import "DSARightAlignedStringTransformer.h"
#import "DSAInventorySlotView.h"
#import "DSAActionResult.h"
#import "DSARegenerationResult.h"
#import "Utils.h"
#import "DSAIllness.h"
#import "DSAPoison.h"
@implementation LevelObserverInfo
@end
@implementation DSACharacterWindowController
// don't do anything here
// we don't want the window loaded on application start
- (DSACharacterWindowController *)init
{
NSLog(@"DSACharacterWindowController: init called");
self = [super init];
if (self)
{
_observedKeyPaths = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions:NSPointerFunctionsStrongMemory];
}
return self;
}
- (void)dealloc {
//NSLog(@"DSACharacterWindowController dealloc called!");
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self closeAllAuxiliaryWindows];
[[self window] close];
//NSLog(@"DSACharacterWindowController: dealloc: removing observers");
for (id object in self.observedKeyPaths) {
//NSLog(@"DSACharacterWindowController: dealloc: remove observer for object: %@", object);
NSSet<NSString *> *keyPaths = [self.observedKeyPaths objectForKey:object];
//NSLog(@"DSACharacterWindowController: dealloc: remove observer for keyPaths %@", keyPaths);
for (NSString *keyPath in keyPaths) {
//NSLog(@"DSACharacterWindowController: dealloc: remove observer for keyPath %@", keyPath);
@try {
[object removeObserver:self forKeyPath:keyPath];
} @catch (NSException *exception) {
NSLog(@"DSACharacterWindowController dealloc: Exception removing observer: %@", exception);
}
}
}
for (LevelObserverInfo *info in self.levelObserverInfos) {
[info.observedObject removeObserver:self forKeyPath:info.keyPath context:(__bridge void *)info];
}
//NSLog(@"DSACharacterWindowController: dealloc: here at the end of dealloc");
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
document.windowControllersCreated = NO;
//NSLog(@"DSACharacterWindowController: dealloc: here at the VERY end of dealloc: %@", [NSNumber numberWithBool: document.windowControllersCreated]);
}
- (NSString *)windowNibName {
return @"DSACharacter"; // Replace with your actual nib name
}
- (DSACharacterWindowController *)initWithWindowNibName:(NSString *)nibNameOrNil
{
NSLog(@"DSACharacterWindowController initWithWindowNibName %@", nibNameOrNil);
self = [super initWithWindowNibName:nibNameOrNil];
NSLog(@"DSACharacterWindowController initWithWindowNibName self: %@", self);
if (self)
{
NSLog(@"DSACharacterWindowController initialized with nib: %@", nibNameOrNil);
self.spellItemFieldMap = [NSMutableDictionary dictionary];
_observedKeyPaths = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions:NSPointerFunctionsStrongMemory];
// _observedKeyPaths = [NSMutableDictionary dictionary];
}
else
{
NSLog(@"DSACharacterWindowController had trouble initializing");
}
NSLog(@"DSACharacterWindowController initWithWindowNibName before returning self");
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
NSLog(@"DSACharacterWindowController awakeFromNib manageTempEnergiesPanel delegate: %@", [self.manageTempEnergiesPanel delegate]);
NSLog(@"DSACharacterWindowController awakeFromNib illnessPanel delegate: %@", [self.illnessPanel delegate]);
// Add similar NSLogs for other auxiliary windows.
}
- (void)windowDidLoad
{
[super windowDidLoad];
// Perform additional setup after loading the window
NSLog(@"DSACharacterWindowController: windowDidLoad called");
// central KVO observers
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
DSACharacter *model = (DSACharacter *)document.model;
// Register the value transformer
//NSLog(@"HERE IN WINDOW DID LOAD THE MODEL: %@", model);
[NSValueTransformer setValueTransformer:[[DSARightAlignedStringTransformer alloc] init]
forName:@"RightAlignedStringTransformer"];
// Register for DSAInventoryChangedNotification specific to this document's model
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleInventoryUpdate)
name:@"DSAInventoryChangedNotification"
object:model];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleLogsMessage:)
name:@"DSACharacterEventLog"
object:model];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleCharacterStateChange:)
name:@"DSACharacterStateChange"
object:model];
// Log the window
if (!self.window) {
NSLog(@"Error: No window found for DSACharacterWindowController!");
return;
}
NSLog(@"Window: %@", self.window);
// Log the content view
NSView *contentView = (NSView *)self.window.contentView;
if (!contentView) {
NSLog(@"Error: No content view found!");
// Set a default content view if missing
contentView = [[NSView alloc] initWithFrame:self.window.frame];
[self.window setContentView:contentView];
NSLog(@"Content view has been set manually.");
} else {
NSLog(@"Window content view: %@", contentView);
}
NSLog(@"DSACharacterWindowController: before populateBasicsTab");
[self populateBasicsTab];
NSLog(@"DSACharacterWindowController: before populateFightingTalentsTab");
[self populateFightingTalentsTab];
NSLog(@"DSACharacterWindowController: before populateGeneralTalentsTab");
[self populateGeneralTalentsTab];
NSLog(@"DSACharacterWindowController: before populateProfessionsTab");
[self populateProfessionsTab];
NSLog(@"DSACharacterWindowController: before populateMagicTalentsTab");
[self populateMagicTalentsTab];
NSLog(@"DSACharacterWindowController: before populateSpecialTalentsTab");
[self populateSpecialTalentsTab];
NSLog(@"DSACharacterWindowController: before populateBiographyTab");
[self populateBiographyTab];
NSLog(@"DSACharacterWindowController: before handleAdventurePointsChange");
[self handleAdventurePointsChange];
NSLog(@"DSACharacterWindowController: after handleAdventurePointsChange");
}
- (void)closeAllAuxiliaryWindows {
unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);
NSLog(@"DSACharacterWindowController closeAllAuxiliaryWindows called");
for (unsigned int i = 0; i < propertyCount; i++) {
const char *propertyName = property_getName(properties[i]);
NSString *name = [NSString stringWithUTF8String:propertyName];
//NSLog(@"checking %@", name);
id propertyValue = [self valueForKey:name];
if ([propertyValue isKindOfClass:[NSWindow class]]) {
NSPanel *panel = (NSPanel *)propertyValue;
NSLog(@"checking panel: %@", panel);
if (panel.isVisible) {
NSLog(@"closing visible panel: %@", panel);
[panel close];
}
}
}
free(properties);
}
- (BOOL)windowShouldClose:(NSWindow *)sender
{
// Simply return YES to close the window without further checks.
NSLog(@"DSACharacterWindowController windowShouldClose called!");
return YES;
}
- (void)windowWillClose:(NSNotification *)notification {
NSWindow *closingWindow = notification.object;
DSACharacterDocument *doc = (DSACharacterDocument *)self.document;
NSLog(@"DSACharacterWindowController willCloseWindow called, closing window: %@", closingWindow);
if ([doc isMainWindow:closingWindow]) {
NSLog(@"Main window is closing. Closing all auxiliary windows.");
[self closeAllAuxiliaryWindows];
}
}
// for the name fields
- (void)addObserverForObject:(id)object keyPath:(NSString *)keyPath {
[object addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL];
NSMutableSet<NSString *> *keyPaths = [self.observedKeyPaths objectForKey:object];
if (!keyPaths) {
keyPaths = [NSMutableSet set];
[self.observedKeyPaths setObject:keyPaths forKey:object];
}
[keyPaths addObject:keyPath];
}
// for the values
- (void)addObserverForObject:(NSObject *)object
keyPath:(NSString *)keyPath
textField:(NSTextField *)field
baseLevel:(NSInteger)baseLevel
{
LevelObserverInfo *info = [[LevelObserverInfo alloc] init];
info.textField = field;
info.baseLevel = baseLevel;
info.observedObject = object;
info.keyPath = keyPath;
[object addObserver:self
forKeyPath:keyPath
options:NSKeyValueObservingOptionNew
context:(__bridge void *)info];
if (!self.levelObserverInfos) {
self.levelObserverInfos = [NSMutableArray array];
}
[self.levelObserverInfos addObject:info];
}
// just for debugging purposes...
- (void)logViewHierarchy:(NSView *)view level:(NSInteger)level {
NSString *indentation = [@"" stringByPaddingToLength:level * 2 withString:@" " startingAtIndex:0];
NSLog(@"%@%@ %@", indentation, view.className, NSStringFromRect(view.frame));
for (NSView *subview in view.subviews) {
[self logViewHierarchy:subview level:level + 1];
}
}
// private method, used in windowDidLoad, to find menu items of interest
// iterates through submenus to find the correct one...
- (NSMenuItem *)menuItemWithTag:(NSInteger)tag inMenu:(NSMenu *)menu {
for (NSMenuItem *item in [menu itemArray]) {
if ([item tag] == tag) {
return item;
}
if ([item submenu]) {
NSMenuItem *subMenuItem = [self menuItemWithTag:tag inMenu:[item submenu]];
if (subMenuItem) {
return subMenuItem;
}
}
}
return nil;
}
- (void) populateBasicsTab
{
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
[self.fieldName setStringValue: [document.model name]];
[self.fieldTitle setStringValue: [document.model title]];
[self.fieldArchetype setStringValue: [document.model archetype]];
[self.fieldOrigin setStringValue: [document.model origin]];
[self.fieldSex setStringValue: [document.model sex]];
[self.fieldHairColor setStringValue: [document.model hairColor]];
[self.fieldEyeColor setStringValue: [document.model eyeColor]];
[self.fieldHeight setStringValue: [NSString stringWithFormat: @"%f", [document.model height]]];
[self.fieldWeight setStringValue: [NSString stringWithFormat: @"%f", [document.model weight]]];
[self.fieldBirthday setStringValue: [NSString stringWithFormat: @"%lu. %@ %lu %@",
(unsigned long)[[document.model birthday] day],
[[document.model birthday] monthName],
(unsigned long)[[document.model birthday] year],
[[document.model birthday] year] > 0 ? @"AF" : @"BF"]];
[self.fieldGod setStringValue: [document.model god]];
[self.fieldStars setStringValue: [document.model stars]];
[self.fieldReligion setStringValue: [document.model religion]];
[self.fieldSocialStatus setStringValue: [document.model socialStatus]];
[self.fieldParents setStringValue: [document.model parents]];
[self.fieldMagicalDabbler setStringValue: [document.model isMagicalDabbler] ? _(@"Ja") : _(@"Nein")];
if ([document.model element] && [document.model mageAcademy])
{
[self.fieldMageAcademy setStringValue: [NSString stringWithFormat: @"%@ (%@)", [document.model mageAcademy], [document.model element]]];
}
else if ([document.model element] && ![document.model mageAcademy])
{
[self.fieldMageAcademy setStringValue: [NSString stringWithFormat: @"%@", [document.model element]]];
[self.fieldMageAcademyBold setStringValue: _(@"Element")];
}
else if (![document.model element] && [document.model mageAcademy])
{
[self.fieldMageAcademy setStringValue: [document.model mageAcademy]];
}
else
{
[self.fieldMageAcademyBold setHidden: YES];
[self.fieldMageAcademy setHidden: YES];
}
if ([document.model isMemberOfClass: [DSACharacterHeroHumanMage class]])
{
[self.fieldMageAcademyBold setStringValue: _(@"Magierakademie")];
}
else if ([document.model isMemberOfClass: [DSACharacterHeroHumanWarrior class]])
{
[self.fieldMageAcademyBold setStringValue: _(@"Kriegerakademie")];
}
else if ([document.model isMemberOfClass: [DSACharacterHeroDwarfGeode class]])
{
[self.fieldMageAcademyBold setStringValue: _(@"Geodische Schule")];
}
// Create and configure your view model
DSACharacterViewModel *viewModel = [[DSACharacterViewModel alloc] init];
DSACharacterHero *model = (DSACharacterHero *)document.model;
viewModel.model = model; // Pass the entire model to the viewModel
[self.fieldMoney bind:NSValueBinding
toObject:viewModel
withKeyPath:@"formattedWallet"
options:nil];
[self addObserverForObject: viewModel keyPath: @"formattedWallet"];
[self.fieldLifePoints bind:NSValueBinding
toObject:viewModel
withKeyPath:@"formattedLifePoints"
options:nil];
[self addObserverForObject: viewModel keyPath: @"formattedLifePoints"];
[self.fieldAstralEnergy bind:NSValueBinding
toObject:viewModel
withKeyPath:@"formattedAstralEnergy"
options:nil];
[self addObserverForObject: viewModel keyPath: @"formattedAstralEnergy"];
[self.fieldKarmaPoints bind:NSValueBinding
toObject:viewModel
withKeyPath:@"formattedKarmaPoints"
options:nil];
[self addObserverForObject: viewModel keyPath: @"formattedKarmaPoints"];
[self.imageViewPortrait setImage: [document.model portrait]];
[self.imageViewPortrait setImageScaling: NSImageScaleProportionallyUpOrDown];
NSLog(@"populateBasicsTab: before positive traits");
for (NSString *field in @[ @"MU", @"KL", @"IN", @"CH", @"FF", @"GE", @"KK" ])
{
NSString *fieldKey = [NSString stringWithFormat:@"field%@", field]; // Constructs "fieldAG", "fieldHA", etc.
NSTextField *fieldControl = [self valueForKey:fieldKey]; // Dynamically retrieves self.fieldAG, self.fieldHA, etc.
[fieldControl bind:NSValueBinding
toObject:viewModel
withKeyPath: [NSString stringWithFormat:@"formattedPositiveTraits.%@", field]
options: nil];
[self addObserverForObject: viewModel keyPath: [NSString stringWithFormat:@"formattedPositiveTraits.%@", field]];
}
for (NSString *field in @[ @"AG", @"HA", @"RA", @"TA", @"NG", @"GG", @"JZ" ])
{
NSString *fieldKey = [NSString stringWithFormat:@"field%@", field]; // Constructs "fieldAG", "fieldHA", etc.
NSTextField *fieldControl = [self valueForKey:fieldKey]; // Dynamically retrieves self.fieldAG, self.fieldHA, etc.
[fieldControl bind:NSValueBinding
toObject:viewModel
withKeyPath: [NSString stringWithFormat:@"formattedNegativeTraits.%@", field]
options: nil];
[self addObserverForObject: viewModel keyPath: [NSString stringWithFormat:@"formattedNegativeTraits.%@", field]];
}
NSLog(@"BEFORE displaying the LOAD");
[self.fieldLoad setStringValue: [NSString stringWithFormat: @"%.2f", [document.model load]]];
[self.fieldEncumbrance setStringValue: [NSString stringWithFormat: @"%.0f", [document.model encumbrance]]];
[self.fieldArmor setStringValue: [NSString stringWithFormat: @"%.0f", [document.model armor]]];
NSLog(@"AFTER displaying the LOAD");
[self.fieldAttackBaseValue bind:NSValueBinding toObject:document.model withKeyPath:@"attackBaseValue" options:nil];
[self addObserverForObject: document.model keyPath: @"attackBaseValue"];
[self.fieldCarryingCapacity bind:NSValueBinding toObject:document.model withKeyPath:@"carryingCapacity" options:nil];
[self addObserverForObject: document.model keyPath: @"carryingCapacity"];
NSLog(@"DSACharacterWindowController populateBasicsTab: carryingCapacity: %lu", (unsigned long) document.model.carryingCapacity);
[self.fieldDodge bind:NSValueBinding toObject:document.model withKeyPath:@"dodge" options:nil];
[self addObserverForObject: document.model keyPath: @"dodge"];
[self.fieldEndurance bind:NSValueBinding toObject:document.model withKeyPath:@"endurance" options:nil];
[self addObserverForObject: document.model keyPath: @"endurance"];
[self.fieldMagicResistance bind:NSValueBinding toObject:document.model withKeyPath:@"magicResistance" options:nil];
[self addObserverForObject: document.model keyPath: @"magicResistance"];
[self.fieldParryBaseValue bind:NSValueBinding toObject:document.model withKeyPath:@"parryBaseValue" options:nil];
[self addObserverForObject: document.model keyPath: @"parryBaseValue"];
[self.fieldRangedCombatBaseValue bind:NSValueBinding toObject:document.model withKeyPath:@"rangedCombatBaseValue" options:nil];
[self addObserverForObject: document.model keyPath: @"rangedCombatBaseValue"];
[self.fieldLevel bind:NSValueBinding toObject:document.model withKeyPath:@"level" options:nil];
[self addObserverForObject: document.model keyPath: @"level"];
[self.fieldAdventurePoints bind:NSValueBinding toObject:document.model withKeyPath:@"adventurePoints" options:nil];
[self addObserverForObject: document.model keyPath: @"adventurePoints"];
NSLog(@"AFTER adding all those observers....");
[self populateInventory];
NSLog(@"End of populateBasicsTab");
}
- (void)populateInventory {
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
NSLog(@"DSACharacterWindowController populateInventory called");
DSAActionIcon *imageEye = [DSAActionIcon iconWithAction:@"examine" andSize:@"64x64"];
[self replaceView:self.imageEye withView:imageEye];
self.imageEye = imageEye;
DSAActionIconConsume *imageMouth= [DSAActionIconConsume iconWithAction:@"consume" andSize:@"64x64"];
imageMouth.ownerCharacter = document.model;
[self replaceView:self.imageMouth withView:imageMouth];
self.imageMouth = imageMouth;
DSAActionIcon *imageTrash = [DSAActionIcon iconWithAction:@"dispose" andSize:@"64x64"];
[self replaceView:self.imageTrash withView:imageTrash];
self.imageTrash = imageTrash;
NSString *imagePath;
NSImage *image;
NSLog(@"after eye and mouth and trash");
if ([document.model.sex isEqualToString: _(@"männlich")])
{
imagePath = [[NSBundle mainBundle] pathForResource:@"Male_shape" ofType:@"png"];
}
else
{
imagePath = [[NSBundle mainBundle] pathForResource:@"Female_shape" ofType:@"png"];
}
image = imagePath ? [[NSImage alloc] initWithContentsOfFile:imagePath] : nil;
self.imageViewBodyShape.image = image;
// Update general inventory slots
[self updateInventorySlotsWithInventory:document.model.inventory
inventoryIdentifier:@"inventory"
startingSlotCounter:0];
CGFloat hungerLevel = [document.model.statesDict[@(DSACharacterStateHunger)] floatValue];
CGFloat thirstLevel = [document.model.statesDict[@(DSACharacterStateThirst)] floatValue];
// Update bars
[self updateBar:self.progressBarHunger withSeverity: hungerLevel];
[self updateBar:self.progressBarThirst withSeverity: thirstLevel];
// NSLog(@"after general inventory");
// [self addObserverForObject: document.model keyPath: @"statesDict"];
// Update body part inventories
NSInteger bodySlotCounter = 0; // Start a global body slot counter
for (NSString *propertyName in document.model.bodyParts.inventoryPropertyNames) {
DSAInventory *inventory = [document.model.bodyParts valueForKey:propertyName];
// NSLog(@"DSACharacterWindowController populateInvenotry THE BODY SLOTS: %@", propertyName);
bodySlotCounter = [self updateInventorySlotsWithInventory:inventory
inventoryIdentifier:@"body"
startingSlotCounter:bodySlotCounter];
}
[self updateCharacterStateView];
}
- (void)replaceView:(NSView *)oldView withView:(NSView *)newView {
NSView *superview = oldView.superview;
NSRect frame = oldView.frame;
newView.frame = frame;
[oldView removeFromSuperview];
[superview addSubview:newView positioned:NSWindowAbove relativeTo:nil];
}
- (void)updateCharacterStateView {
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
if (self.viewCharacterStatus == nil)
{
self.viewCharacterStatus = [[DSACharacterStatusView alloc] init];
}
[self.viewCharacterStatus setCharacter: document.model];
}
- (void)updateBar:(NSProgressIndicator *)bar withSeverity:(CGFloat) severity
{
//NSLog(@"UPDATING BAR, NEW SEVERITY: %f", severity);
if (severity < 0 || severity > 1)
{
NSLog(@"DSACharacterWindowController updateBar: invalid severity %f", severity);
return;
}
[bar setDoubleValue: severity];
}
- (void) handleInventoryUpdate {
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
NSLog(@"DSACharacterWindowController handleInventoryUpdate called for model: %@", document.model.name);
[self populateInventory];
[self updateLoadDisplay];
[self updateArmorDisplay];
[self updateEncumbranceDisplay];
[self.document updateChangeCount: NSChangeDone];
}
- (void)handleCharacterStateChange:(NSNotification *)notification
{
NSDictionary *userInfo = notification.userInfo;
if (!userInfo) return;
DSACharacterState state = [userInfo[@"state"] integerValue];
NSNumber *value = userInfo[@"value"];
switch (state)
{
case DSACharacterStateHunger:
[self updateBar: self.progressBarHunger withSeverity: [value doubleValue]];
break;
case DSACharacterStateThirst:
[self updateBar: self.progressBarThirst withSeverity: [value doubleValue]];
break;
case DSACharacterStateDead:
if ([value boolValue] == YES)
{
[self handleCharacterDeath];
}
break;
default:
NSLog(@"DSACharacterWindowController don't know how to handle state change for state %@", @(state));
}
[self updateCharacterStateView];
[self.document updateChangeCount: NSChangeDone];
}
- (void)handleLogsMessage:(NSNotification *)notification
{
NSDictionary *userInfo = notification.userInfo;
if (!userInfo) return;
LogSeverity severity = [userInfo[@"severity"] integerValue];
NSString *message = userInfo[@"message"];
if (!message) return;
NSLog(@"Got message: %@", message);
// Get timestamp
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSString *timestamp = [formatter stringFromDate:[NSDate date]];
// Format log entry with bold timestamp
NSMutableAttributedString *logEntry = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@", timestamp, message]];
// Apply bold font to timestamp
[logEntry addAttribute:NSFontAttributeName value:[NSFont boldSystemFontOfSize:12] range:NSMakeRange(0, timestamp.length)];
// Apply color based on severity
NSColor *textColor;
switch (severity) {
case LogSeverityInfo:
textColor = [NSColor blackColor];
break;
case LogSeverityHappy:
textColor = [NSColor blueColor];
break;
case LogSeverityWarning:
textColor = [NSColor brownColor];
break;
case LogSeverityCritical:
textColor = [NSColor redColor];
break;
}
[logEntry addAttribute:NSForegroundColorAttributeName value:textColor range:NSMakeRange(timestamp.length + 1, message.length)];
// Append to existing logs, ensuring we don't exceed the field’s capacity
NSLog(@"That's the log entry: %@", logEntry);
[self appendLogMessage:logEntry];
}
- (void)appendLogMessage:(NSAttributedString *)newLog {
NSMutableAttributedString *existingLogs = [[NSMutableAttributedString alloc] initWithAttributedString:self.fieldLogs.attributedStringValue];
// Store log entries as attributed strings
NSMutableArray<NSAttributedString *> *logEntries = [NSMutableArray array];
// Define regex pattern for timestamps (e.g., "12:34:56")
NSString *timestampPattern = @"\\b\\d{2}:\\d{2}:\\d{2}\\b";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:timestampPattern options:0 error:nil];
__block NSInteger lastMatchLocation = 0;
NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:existingLogs.string options:0 range:NSMakeRange(0, existingLogs.length)];
// Extract log messages based on timestamp locations
for (NSTextCheckingResult *match in matches) {
if (match.range.location > lastMatchLocation) {
NSRange entryRange = NSMakeRange(lastMatchLocation, match.range.location - lastMatchLocation);
NSAttributedString *logEntry = [existingLogs attributedSubstringFromRange:entryRange];
[logEntries addObject:logEntry];
}
lastMatchLocation = match.range.location; // Update last match location
}
// Add the last entry if not already added
if (lastMatchLocation < existingLogs.length) {
NSAttributedString *lastLog = [existingLogs attributedSubstringFromRange:NSMakeRange(lastMatchLocation, existingLogs.length - lastMatchLocation)];
[logEntries addObject:lastLog];
}
// Add the new log entry
[logEntries addObject:newLog];
// Define max number of log entries allowed
NSInteger maxEntries = 6; // Adjust as needed
// Remove oldest entries if exceeding max
while (logEntries.count > maxEntries) {
[logEntries removeObjectAtIndex:0];
}
// Rebuild the attributed string **with newline checks**
NSMutableAttributedString *updatedLogs = [[NSMutableAttributedString alloc] init];
for (NSInteger i = 0; i < logEntries.count; i++) {
// Append the log entry
[updatedLogs appendAttributedString:logEntries[i]];
// Only add a newline if the previous entry didn't end with one
if (i < logEntries.count - 1) { // Avoid adding a newline after the last entry
NSString *lastEntryString = [logEntries[i] string];
if (![lastEntryString hasSuffix:@"\n"]) {
[updatedLogs appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
}
}
}
// Update NSTextField while preserving formatting
self.fieldLogs.attributedStringValue = updatedLogs;
}
// Updates all slots in the specified inventory
- (NSInteger)updateInventorySlotsWithInventory:(DSAInventory *)inventory
inventoryIdentifier:(NSString *)inventoryIdentifier
startingSlotCounter:(NSInteger)startingSlotCounter {
NSInteger slotCounter = startingSlotCounter;
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
//NSLog(@"DSACharacterWindowController updateInventorySlotsWithInventory : updateInventorySlotsWithInventory: %@", inventoryIdentifier);
for (NSInteger i = 0; i < inventory.slots.count; i++) {
DSASlot *slot = inventory.slots[i];
NSString *iconName = slot.object ? [NSString stringWithFormat:@"%@-64x64", [slot.object icon]] : nil;
NSString *imagePath = iconName ? [[NSBundle mainBundle] pathForResource:iconName ofType:@"webp"] : nil;
// Generate the name of the slot view from the identifier
NSString *uiName = [NSString stringWithFormat:@"%@Slot%ld", inventoryIdentifier, (long)slotCounter];
// NSLog(@"DSACharacterWindowController Updating UI for: %@", uiName);
// Access the slot view (already a DSAInventorySlotView)
DSAInventorySlotView *slotView = [self valueForKey:uiName];
if (slotView) {
//NSLog(@"DSACharacterWindowController Found slotView for %@, updating properties", uiName);
// Update properties directly
slotView.slot = slot;
slotView.slotIndex = slotCounter;
slotView.inventoryIdentifier = inventoryIdentifier;
slotView.item = slot.object; // Set the item in the slot
slotView.model = document.model;
// Update the image
NSImage *image = imagePath ? [[NSImage alloc] initWithContentsOfFile:imagePath] : nil;
slotView.image = image;
// Set drag-and-drop configuration
[slotView setInitiatesDrag:YES];
[slotView registerForDraggedTypes:@[NSStringPboardType]];
// Update the quantity label
[slotView updateQuantityLabelWithQuantity:slot.quantity];
[slotView updateToolTip];
} else {
NSLog(@"DSACharacterWindowController: updateInventorySlotsWithInventory Slot view %@ not found, skipping update", uiName);
}
// Increment the slot counter for the next slot
slotCounter++;
}
// Return the updated slot counter for chaining
return slotCounter;
}
// Helper method for setting the image for a specific slot view
- (void)updateSlotImageForSlotView:(DSAInventorySlotView *)slotView withImageNamed:(NSString *)imageName {
NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:@"webp"];
NSImage *image = imagePath ? [[NSImage alloc] initWithContentsOfFile:imagePath] : nil;
slotView.image = image;
}
- (void)updateLoadDisplay {
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
if (!document.model) return;
// Calculate the total weight from the character model
float totalLoad = [document.model load];
// Update the UI field with the total weight
self.fieldLoad.stringValue = [NSString stringWithFormat:@"%.2f", totalLoad];
NSLog(@"Updated load display: %.2f", totalLoad);
}
- (void)updateEncumbranceDisplay {
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
if (!document.model) return;
// Calculate the total weight from the character model
float totalEncumbrance = [document.model encumbrance];
// Update the UI field with the total weight
self.fieldEncumbrance.stringValue = [NSString stringWithFormat:@"%.0f", totalEncumbrance];
NSLog(@"Updated encumbrance display: %.0f", totalEncumbrance);
}
- (void)updateArmorDisplay {
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
if (!document.model) return;
// Calculate the total weight from the character model
float totalArmor = [document.model armor];
// Update the UI field with the total weight
self.fieldArmor.stringValue = [NSString stringWithFormat:@"%.0f", totalArmor];
NSLog(@"Updated armor display: %.0f", totalArmor);
}
- (void)populateFightingTalentsTab
{
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
DSACharacterHero *model = (DSACharacterHero *)document.model;
NSTabViewItem *mainTabItem = [self.tabViewMain tabViewItemAtIndex:[self.tabViewMain indexOfTabViewItemWithIdentifier:@"item 2"]];
NSRect subTabViewFrame = mainTabItem.view ? mainTabItem.view.bounds : NSMakeRect(0, 0, 400, 300);
NSTabView *subTabView = [[NSTabView alloc] initWithFrame:subTabViewFrame];
[subTabView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
NSMutableArray *fightingTalents = [NSMutableArray array];
NSMutableSet *fightingCategories = [NSMutableSet set];
// Enumerate talents to find all fighting talents
[model.talents enumerateKeysAndObjectsUsingBlock:^(id key, DSATalent *obj, BOOL *stop)
{
if ([obj isKindOfClass:[DSAFightingTalent class]])
{
DSAFightingTalent *fightingTalent = (DSAFightingTalent *)obj;
if ([[fightingTalent category] isEqualToString:@"Kampftechniken"])
{
[fightingTalents addObject: fightingTalent];
[fightingCategories addObject:[fightingTalent subCategory]];
}
}
else
{
//NSLog(@"DSACharacterWindowController populateFightingTalentsTab unexpected DSATalent subclass");
}
}];
// Sort the fighting categories alphabetically
NSArray *sortedFightingCategories = [[fightingCategories allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
// Sort the fighting talents by subCategory
NSSortDescriptor *nameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortedFightingTalents = [fightingTalents sortedArrayUsingDescriptors:@[nameSortDescriptor]];
// Iterate through sorted categories and create tabs for them
for (NSString *category in sortedFightingCategories)
{
// Filter talents that belong to the current category
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(DSAFightingTalent *evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject.subCategory isEqualToString:category];
}];
NSArray *filteredTalents = [sortedFightingTalents filteredArrayUsingPredicate:predicate];
// Call the helper method to add the tab for this category
[self addTabForCategory:category
inSubTabView:subTabView
withItems:filteredTalents
currentItemsByName: model.currentTalents];
}
// Set the subTabView for item 2
[mainTabItem setView:subTabView];
}
- (void)populateGeneralTalentsTab
{
NSLog(@"DSACharacterWindowController populateGeneralTalentsTab called");
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
DSACharacterHero *model = (DSACharacterHero *)document.model;
NSTabViewItem *mainTabItem = [self.tabViewMain tabViewItemAtIndex:[self.tabViewMain indexOfTabViewItemWithIdentifier:@"item 3"]];
NSRect subTabViewFrame = mainTabItem.view ? mainTabItem.view.bounds : NSMakeRect(0, 0, 400, 300);
NSTabView *subTabView = [[NSTabView alloc] initWithFrame:subTabViewFrame];
[subTabView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
NSMutableArray *otherTalents = [NSMutableArray array];
NSMutableSet *talentCategories = [NSMutableSet set];
// Enumerate talents to find all categories excluding "Kampftechniken"
NSLog(@"DSACharacterWindowController populateGeneralTalentsTab BEFORE filtering out Kampftechniken: %@", model.talents);
[model.talents enumerateKeysAndObjectsUsingBlock:^(id key, DSATalent *obj, BOOL *stop)
{
if (![[obj category] isEqualToString:@"Kampftechniken"])
{
[otherTalents addObject: obj];
[talentCategories addObject: [obj category]];
}
}];
NSLog(@"DSACharacterWindowController populateGeneralTalentsTab after filtering out Kampftechniken: %@", otherTalents);
// Sort the talent categories alphabetically
NSArray *sortedTalentCategories = [[talentCategories allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
// Sort the other talents by name
NSSortDescriptor *nameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortedOtherTalents = [otherTalents sortedArrayUsingDescriptors:@[nameSortDescriptor]];
// Iterate through sorted categories and create tabs for them
for (NSString *category in sortedTalentCategories)
{
// Filter talents that belong to the current category
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(DSAGeneralTalent *evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject.category isEqualToString:category];
}];
NSArray *filteredTalents = [sortedOtherTalents filteredArrayUsingPredicate:predicate];
// Call the helper method to add the tab for this category
[self addTabForCategory:category
inSubTabView:subTabView
withItems:filteredTalents
currentItemsByName:model.currentTalents];
}
// Set the subTabView for the current tab
[mainTabItem setView:subTabView];
}
- (void)populateProfessionsTab
{
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
DSACharacterHero *model = (DSACharacterHero *)document.model;
NSLog(@"populateProfessionsTab");
NSTabViewItem *mainTabItem = [self.tabViewMain tabViewItemAtIndex: [self.tabViewMain indexOfTabViewItemWithIdentifier:@"item 5"]];
if ([model professions] == nil)
{
NSLog(@"don't have professions, not showing professions tab");
[self.tabViewMain removeTabViewItem:mainTabItem];
return;
}
NSRect subTabViewFrame = mainTabItem.view ? mainTabItem.view.bounds : NSMakeRect(0, 0, 400, 300);
NSTabView *subTabView = [[NSTabView alloc] initWithFrame:subTabViewFrame];
[subTabView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
NSMutableArray *professions = [NSMutableArray array];
NSMutableSet *categories = [NSMutableSet set];
// Enumerate professions to find all categories
[model.professions enumerateKeysAndObjectsUsingBlock:^(id key, DSAProfession *obj, BOOL *stop)
{
[professions addObject: obj];
[categories addObject: [obj category]];
}];
// Sort the categories alphabetically
NSArray *sortedCategories = [[categories allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
// Sort the professions by name
NSSortDescriptor *nameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortedProfessions = [professions sortedArrayUsingDescriptors:@[nameSortDescriptor]];
// Iterate through sorted categories and create tabs for them
for (NSString *category in sortedCategories)
{
// Filter professions that belong to the current category
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(DSAGeneralTalent *evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject.category isEqualToString:category];
}];
NSArray *filteredProfessions = [sortedProfessions filteredArrayUsingPredicate:predicate];
// Call the helper method to add the tab for this category
[self addTabForCategory:category
inSubTabView:subTabView
withItems:filteredProfessions
currentItemsByName:model.currentProfessions];
}
// Set the subTabView for the current tab
[mainTabItem setView:subTabView];
}
- (void)populateMagicTalentsTab
{
DSACharacterDocument *document = (DSACharacterDocument *)self.document;
DSACharacterHero *model = (DSACharacterHero *)document.model;
NSTabViewItem *mainTabItem = [self.tabViewMain tabViewItemAtIndex: [self.tabViewMain indexOfTabViewItemWithIdentifier:@"item 4"]];
if (model.spells == nil || [model.spells count] == 0)
{
NSLog(@"not being magic, not showing magic talents tab");
[self.tabViewMain removeTabViewItem:mainTabItem];
return;
}
NSRect subTabViewFrame = mainTabItem.view ? mainTabItem.view.bounds : NSMakeRect(0, 0, 400, 300);
NSTabView *subTabView = [[NSTabView alloc] initWithFrame: subTabViewFrame];
[subTabView setAllowsTruncatedLabels: YES];
[subTabView setControlSize:NSControlSizeSmall];
[subTabView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
NSMutableArray *spells = [NSMutableArray array];
NSMutableSet *categories = [NSMutableSet set];
// Enumerate talents to find all categories
[model.spells enumerateKeysAndObjectsUsingBlock:^(id key, DSASpell *obj, BOOL *stop)
{
[spells addObject: obj];
[categories addObject: [obj category]];
}];
// Sort spells by name
NSSortDescriptor *nameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortedSpells = [spells sortedArrayUsingDescriptors:@[nameSortDescriptor]];
// Sort categories alphabetically
NSArray *sortedCategories = [[categories allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
// Containers for categories that start with "Beschwörung" and "Verwandlung"
NSMutableArray *beschwoerungCategories = [NSMutableArray array];
NSMutableArray *verwandlungCategories = [NSMutableArray array];
// Separate categories based on naming
for (NSString *category in sortedCategories)
{
if ([category hasPrefix:@"Beschwörung"] || [category isEqualToString:@"Die Sieben Formeln der Zeit"])
{
[beschwoerungCategories addObject:category];
}
else if ([category hasPrefix:@"Verwandlung"])
{
[verwandlungCategories addObject:category];
}
else
{
// Non-grouped categories: filter spells and add tabs
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(DSAGeneralTalent *evaluatedObject, NSDictionary *bindings)
{
return [evaluatedObject.category isEqualToString:category];
}];
NSArray *filteredSpells = [sortedSpells filteredArrayUsingPredicate:predicate];
[self addTabForCategory:category
inSubTabView:subTabView
withItems:filteredSpells
currentItemsByName:model.currentSpells];
}
}
// Sort "Beschwörung" and "Verwandlung" categories alphabetically
NSArray *sortedBeschwoerungCategories = [beschwoerungCategories sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];