File: PajeEntityInspector.m

package info (click to toggle)
paje.app 1.98-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,428 kB
  • sloc: objc: 24,517; ansic: 6,998; makefile: 134; sh: 42; java: 31
file content (825 lines) | stat: -rw-r--r-- 27,040 bytes parent folder | download | duplicates (3)
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
/*
    Copyright (c) 1998--2005 Benhur Stein
    
    This file is part of Paj.

    Paj is free software; you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License as published by the
    Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    Paj 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 Lesser General Public License
    for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Paj; if not, write to the Free Software Foundation, Inc.,
    59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include "PajeEntityInspector.h"
#include "SourceCodeReference.h"
#include "SourceTextController.h"
#include "PajeType.h"
#include "Macros.h"

#define SUBVIEW_SEPARATION 2
#define BOTTOM_MARGIN 10

@interface InnerStatesCell : NSCell
@end
@implementation InnerStatesCell
- (void)drawInteriorWithFrame:(NSRect)frame inView:(NSView *)controlView
{
    PajeEntity *entity;
    unsigned count;
    unsigned i;
    double duration;
    float x0;
    float x;
    float h;
    
    entity = [self representedObject];
    [[entity color] set];
    NSRectFill(frame);
    duration = [entity duration];
    x = x0 = NSMinX(frame);
    h = NSHeight(frame) * 2 / 3 - 1;
    count = [entity subCount];
    for (i = 0; i < count; i++) {
        double subDuration;
        float w;

        [[entity subColorAtIndex:i] set];
        subDuration = [entity subDurationAtIndex:i];
        w = subDuration / duration * NSWidth(frame);
        NSRectFill(NSMakeRect(x, NSMinY(frame), w, h));
        x += w; 
    }
    [[NSColor blackColor] set];
    NSFrameRect(NSMakeRect(x0, NSMinY(frame), x - x0, h + 1));
    NSFrameRect(frame);
}
@end


@implementation PajeEntityInspector

static NSMutableArray *allInstances;

+ (PajeEntityInspector *)inspector
{
    NSEnumerator *instEnum;
    PajeEntityInspector *inspector;
    if (allInstances == nil) {
        allInstances = [[NSMutableArray alloc] init];
    }
    instEnum = [allInstances objectEnumerator];
    while ((inspector = [instEnum nextObject]) != nil) {
        if ([inspector isReusable]) {
            return inspector;
        }
    }
    inspector = [[self alloc] init];
    [allInstances addObject:inspector];
    [inspector release];
    return inspector;
}

- (void)windowWillClose:(NSNotification *)notification
{
    if ([notification object] == inspectionWindow) {
        [allInstances removeObjectIdenticalTo:self];
    }
}

- (id)init
{
    Class class = [self class];
    BOOL loaded = NO;
    NSDictionary *nameTable = [NSDictionary dictionaryWithObjectsAndKeys:
                                  self, @"NSOwner", nil];

    while (!loaded && (class != [class superclass])) {
        NSBundle *bundle = [NSBundle bundleForClass:class];
        NSString *filename = @"PajeEntityInspector";
        loaded = [bundle loadNibFile:filename
	    	   externalNameTable:nameTable
		            withZone:[self zone]];
        class = [class superclass];
    }
    if (!loaded) {
        NSRunAlertPanel(@"Can't find file",
                        @"Interface description file '%@' not found",
                        nil, nil, nil, @"PajeEntityInspector");
        [self release];
        return nil;
    }

    [[showFileButton retain] removeFromSuperview];
    archivedTitleField = [NSArchiver archivedDataWithRootObject:titleField];
    archivedValueField = [NSArchiver archivedDataWithRootObject:valueField];
    [archivedTitleField retain];
    [archivedValueField retain];
    [titleField removeFromSuperview];
    [valueField removeFromSuperview];
    [fieldBox setContentViewMargins:NSMakeSize(2, 2)];
    archivedBox= [[NSArchiver archivedDataWithRootObject:fieldBox] retain];
    [fieldBox removeFromSuperview];

    [relatedEntitiesBox retain];
    [relatedEntitiesBox setContentViewMargins:NSMakeSize(2, 2)];
    [relatedEntitiesBox removeFromSuperview];

    [nameField retain];
    [colorField retain];
    [reuseButton retain];
    [filterButton retain];

    return self;
}

- (void)dealloc
{
    Assign(inspectedEntity, nil);
    Assign(filter, nil);

    Assign(relatedEntitiesBox, nil);
    Assign(archivedBox, nil);
    Assign(archivedTitleField, nil);
    Assign(archivedValueField, nil);

    Assign(nameField, nil);
    Assign(colorField, nil);
    Assign(reuseButton, nil);
    Assign(filterButton, nil);

    [super dealloc];
}

- (void)reset
{
    // remove everything from the panel
    [[[inspectionWindow contentView] subviews]
            makeObjectsPerformSelector:@selector(removeFromSuperview)];

    // add the top widgets
    [[inspectionWindow contentView] addSubview:nameField];
    [[inspectionWindow contentView] addSubview:colorField];
    [[inspectionWindow contentView] addSubview:reuseButton];
    [[inspectionWindow contentView] addSubview:filterButton];

    // initialize bounding box
    boundingBox = NSUnionRect([colorField frame], [nameField frame]);
}

- (void)addSubview:(NSView *)view
{
    NSRect frame;

    if (view == nil) {
        return;
    }

    // add view bellow other views
    frame = [view frame];
    frame.origin.y = NSMinY(boundingBox) - NSHeight(frame) - SUBVIEW_SEPARATION;
    frame.origin.x = NSMinX(boundingBox);
    frame.size.width = NSWidth(boundingBox);
    [view setFrame:frame];
    [[inspectionWindow contentView] addSubview:view];

    // update bounding box to reflect new view
    boundingBox = NSUnionRect(boundingBox, frame);
}

- (void)addLastSubview:(NSView *)view
{
    NSRect frame;

    if (view == nil)
        return;

    // the last view can autosize if window changes size. resize window
    // before adding it, if necessary
    frame = [view frame];
    int dif = NSMinY(boundingBox) - SUBVIEW_SEPARATION
            - NSHeight(frame) - BOTTOM_MARGIN;
    if (dif != 0) {
        NSSize windowSize = [inspectionWindow frame].size;
        windowSize.height -= dif;
        [inspectionWindow setContentSize:windowSize];
    }

    // bottom is now at window margin
    frame.origin.y = BOTTOM_MARGIN;
    frame.origin.x = NSMinX(boundingBox);
    frame.size.width = NSWidth(boundingBox);

    // the size of the window may have changed -- boundingBox is no longer valid
    boundingBox = NSUnionRect([colorField frame], frame);

    [view setFrame:frame];
    [[inspectionWindow contentView] addSubview:view];
}

- (IBAction)filterEntityName:(id)sender
{
    PajeEntityType *entityType;
    id entityValue;

    entityType = [inspectedEntity entityType];
    entityValue = [inspectedEntity value];
    if (entityType != nil && entityValue != nil) {
        NSString *filtering;
        NSDictionary *userInfo;
        filtering = [sender state] ? @"YES" : @"NO";
        userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                                         entityType, @"EntityType",
                                         entityValue, @"EntityValue",
                                         filtering, @"Show",
                                         nil];
        [[NSNotificationCenter defaultCenter]
                postNotificationName:@"PajeFilterEntityValueNotification"
                              object:self
                            userInfo:userInfo];
    }
}

- (NSBox *)boxWithTitle:(NSString *)boxTitle
            fieldTitles:(NSArray *)titles
            fieldValues:(NSArray *)values
{
    NSBox *box;
    int index;
    float curY;
    float titleWidth = 0;
    float leftMargin;
    float deltaHeight;
    NSTextField *field1;
    NSRect boxFrame;

    NSAssert([titles count] == [values count],
             @"count of fields and values do not match");
    
    // I don't know a better way of copying a box...
    box = [NSUnarchiver unarchiveObjectWithData:archivedBox];
    field1 = [NSUnarchiver unarchiveObjectWithData:archivedTitleField];
    leftMargin = NSMinX([field1 frame]);
    curY = NSMinY([field1 frame]);
#ifdef __APPLE__
    curY -= 4;
#endif
    deltaHeight = NSHeight([box frame]) - NSMaxY([field1 frame]);

    [box setTitle:boxTitle];

    for (index = 0; index < [titles count]; index++) {
        float w;
        NSString *title = [[titles objectAtIndex:index] description];
        [field1 setStringValue:title];
        w = [[field1 cell] cellSize].width;
        if (w > titleWidth) titleWidth = w;
    }
    for (index = [titles count] - 1; index >= 0; index--) {
        float height;
        NSString *title = [[titles objectAtIndex:index] description];
        NSString *value = [[values objectAtIndex:index] description];
        NSTextField *tField;
        NSTextField *vField;
        
        tField = [NSUnarchiver unarchiveObjectWithData:archivedTitleField];
        vField = [NSUnarchiver unarchiveObjectWithData:archivedValueField];
        
        [tField setStringValue:title];
        [vField setStringValue:value];
        height = MAX([[tField cell] cellSize].height,
                     [[vField cell] cellSize].height);
        
        if ([value isEqual:@"**AQUI**"]) {
            NSCell *cell = [[InnerStatesCell alloc] init];
            [cell setRepresentedObject:inspectedEntity];
            [vField setCell:cell];
            [cell release];
        }
        
        [tField setFrame:NSMakeRect(leftMargin, curY, titleWidth, height)];
        [vField setFrame:NSMakeRect(leftMargin + titleWidth + 2, curY, 10, height)];
        [box addSubview:tField];
        [box addSubview:vField];
        
        curY += height+2;
    }
    boxFrame = [box frame];
    boxFrame.size.height = curY - 2 + deltaHeight;
    boxFrame.size.width = leftMargin + titleWidth + 2 + 10 + leftMargin;
    [box setFrame:boxFrame];
    //[box sizeToFit];

    return box;
}

- (void)addSourceReference
{
    SourceCodeReference *sourceRef;
    NSBox *box;
    NSArray *values;
    NSRect buttonFrame;
    NSRect contentFrame;
    
    // source code reference
    sourceRef = [filter valueOfFieldNamed:@"FileReference"
                                forEntity:inspectedEntity];
    if (sourceRef == nil) {
        return;
    }

    values = [NSArray arrayWithObjects:
            [sourceRef filename],
            [NSString stringWithFormat:@"%d", [sourceRef lineNumber]],
            nil];
    
    box = [self boxWithTitle:@"Source File"
            fieldTitles:[NSArray arrayWithObjects:@"File", @"Line", nil]
            fieldValues:values];
    [box sizeToFit];
            
    contentFrame = [[box contentView] frame];
    [showFileButton sizeToFit];
    buttonFrame = [showFileButton frame];
    [showFileButton setFrame:NSMakeRect(NSMaxX(contentFrame) + 2,
                                        0,
                                        NSWidth(buttonFrame),
                                        NSHeight(contentFrame))];
    [box addSubview:showFileButton];
    [box sizeToFit];

    [self addSubview:box];
}


- (NSBox *)boxWithTitle:(NSString *)boxTitle
           fieldObjects:(NSArray *)objects
            fieldTitles:(NSArray *)titles
            fieldValues:(NSArray *)values
{
    return [self boxWithTitle:boxTitle
                  fieldTitles:titles
                  fieldValues:values];
}

- (NSBox *)boxWithTitle:(NSString *)boxTitle
            fieldTitles:(NSArray *)titles
             fieldNames:(NSArray *)names
{
    NSString *fieldName;
    NSEnumerator *fieldNameEnum = [names objectEnumerator];
    NSMutableArray *fieldValues = [NSMutableArray array];

    while ((fieldName = [fieldNameEnum nextObject]) != nil) {
        id fieldValue = [inspectedEntity valueOfFieldNamed:fieldName];
        if (fieldValue == nil) fieldValue = @"";
        [fieldValues addObject:[fieldValue description]];
        [nonDisplayedFields removeObject:fieldName];
    }
    return [self boxWithTitle:boxTitle
                  fieldTitles:titles
                  fieldValues:fieldValues];
}

- (void)addBoxForContainer:(PajeContainer *)container
             upToContainer:(PajeContainer *)upto
                 withTitle:(NSString *)title
{
    NSBox *box;
    NSMutableArray *fieldTitles;
    NSMutableArray *fieldValues;
    NSMutableArray *fieldObjects;
    
    if (container == nil) {
        return;
    }

    fieldTitles = [NSMutableArray array];
    fieldValues = [NSMutableArray array];
    fieldObjects = [NSMutableArray array];
    while ([container container] != nil && ![container isEqual:upto]) {
      [fieldTitles insertObject:[[container entityType] description] atIndex:0];
      [fieldValues insertObject:[container name] atIndex:0];
      [fieldObjects insertObject:container atIndex:0];
      container = [container container];
    }

    box = [self boxWithTitle:title
                fieldObjects:fieldObjects
                 fieldTitles:fieldTitles
                 fieldValues:fieldValues];
    [self addSubview:box];
}

- (void)addLocalFields
{
    PajeContainer *container;
    PajeContainer *sourceContainer;
    PajeContainer *destContainer;
    NSBox *box;
    NSMutableArray *fieldTitles;
    NSMutableArray *fieldValues;
    NSDate *startTime;
    NSDate *endTime;
    double duration;
    double exclusiveDuration;
    id startLogical;
    id endLogical;

    // container information
    container = [inspectedEntity container];
    [self addBoxForContainer:container
               upToContainer:nil
                   withTitle:@"Container"];
    [nonDisplayedFields removeObject:@"Container"];

    sourceContainer = [inspectedEntity valueOfFieldNamed:@"SourceContainer"];
    if (sourceContainer != nil) {
        [self addBoxForContainer:sourceContainer
                   upToContainer:container
                       withTitle:@"Source Container"];
        [nonDisplayedFields removeObject:@"SourceContainer"];
    }
    destContainer = [inspectedEntity valueOfFieldNamed:@"DestContainer"];
    if (destContainer != nil) {
        [self addBoxForContainer:destContainer
                   upToContainer:container
                       withTitle:@"Dest Container"];
        [nonDisplayedFields removeObject:@"DestContainer"];
    }

    // timing information
    fieldTitles = [NSMutableArray array];
    fieldValues = [NSMutableArray array];
    startTime = [inspectedEntity startTime];
    endTime = [inspectedEntity endTime];
    duration = [inspectedEntity duration];
    if (duration == 0) {
        [fieldTitles addObject:@"Time"];
        [fieldValues addObject:[startTime description]];
    } else {
        [fieldTitles addObject:@"Start Time"];
        [fieldValues addObject:[startTime description]];
        [fieldTitles addObject:@"End Time"];
        [fieldValues addObject:[endTime description]];
        [fieldTitles addObject:@"Duration"];
        [fieldValues addObject:[NSString stringWithFormat:@"%.6f", duration]];
    }
    if (![inspectedEntity isAggregate]
        && [inspectedEntity drawingType] == PajeStateDrawingType) {
        exclusiveDuration = [inspectedEntity exclusiveDuration];
        if (exclusiveDuration != duration) {
            [fieldTitles addObject:@"Exclusive Duration"];
            [fieldValues addObject:[NSString stringWithFormat:@"%.6f (%.1f%%)",
                                         exclusiveDuration,
                                         exclusiveDuration/duration*100]];
        }
    }
    startLogical = [inspectedEntity valueOfFieldNamed:@"StartLogical"];
    if (startLogical != nil) {
        [fieldTitles addObject:@"Start Logical"];
        [fieldValues addObject:[startLogical description]];
        [nonDisplayedFields removeObject:@"StartLogical"];
    }
    endLogical = [inspectedEntity valueOfFieldNamed:@"EndLogical"];
    if (endLogical != nil) {
        [fieldTitles addObject:@"End Logical"];
        [fieldValues addObject:[endLogical description]];
        [nonDisplayedFields removeObject:@"EndLogical"];
    }

    [nonDisplayedFields removeObject:@"Time"];
    [nonDisplayedFields removeObject:@"StartTime"];
    [nonDisplayedFields removeObject:@"EndTime"];
    [nonDisplayedFields removeObject:@"Duration"];
    [nonDisplayedFields removeObject:@"Exclusive Duration"];
    
    box = [self boxWithTitle:@"Timing"
                 fieldTitles:fieldTitles
                 fieldValues:fieldValues];
    [self addSubview:box];

    /* Inner Entities */
    unsigned innerCount;
    innerCount = [inspectedEntity condensedEntitiesCount];
    if (innerCount > 0) {
        [fieldTitles removeAllObjects];
        [fieldValues removeAllObjects];
        [fieldTitles addObject:@"Count"];
        [fieldValues addObject:[NSString stringWithFormat:@"%d", innerCount]];
        [fieldTitles addObject:@"Values"];
        [fieldValues addObject:@"**AQUI**"];
        int i;
        int subCount;
        int count;
        double value;
        double total;
        if ([inspectedEntity drawingType] == PajeStateDrawingType) {
            total = duration;
        } else {
            total = innerCount;
        }
        subCount = [inspectedEntity subCount];
        if (subCount <= 5) count = subCount;
        else count = 4;
        for (i = 0; i < count; i++) {
            [fieldTitles addObject:[inspectedEntity subValueAtIndex:i]];
            if ([inspectedEntity drawingType] == PajeStateDrawingType) {
                value = [inspectedEntity subDurationAtIndex:i];
                [fieldValues addObject:
                            [NSString stringWithFormat:@"%.6f (%.1f%%)",
                                    value, value/total*100]];
            } else {
                value = [inspectedEntity subCountAtIndex:i];
                [fieldValues addObject:
                            [NSString stringWithFormat:@"%d (%.1f%%)",
                                    (int)value, value/total*100]];
            }
        }
        if (count < subCount) {
            value = 0;
            for (; i < subCount; i++) {
                if ([inspectedEntity drawingType] == PajeStateDrawingType) {
                    value += [inspectedEntity subDurationAtIndex:i];
                } else {
                    value += [inspectedEntity subCountAtIndex:i];
                }
            }
            [fieldTitles addObject:[NSString stringWithFormat:@"Other %d", i - count]];
            if ([inspectedEntity drawingType] == PajeStateDrawingType) {
                [fieldValues addObject:
                            [NSString stringWithFormat:@"%.6f (%.1f%%)",
                                    value, value/total*100]];
            } else {
                [fieldValues addObject:
                            [NSString stringWithFormat:@"%d (%.1f%%)",
                                    (int)value, value/total*100]];
            }
        }
        box = [self boxWithTitle:@"Inner Entities"
                     fieldTitles:fieldTitles
                     fieldValues:fieldValues];
        [self addSubview:box];
    }
}

- (void)addGlobalFields
{
    // global fields
    [nameField setStringValue:[[filter valueForEntity:inspectedEntity] stringValue]];
    [colorField setTarget:nil];
    [colorField setColor:[filter colorForEntity:inspectedEntity]];
    [colorField setAction:@selector(colorChanged:)];
    [colorField setTarget:self];
    [inspectionWindow setTitle:[filter descriptionForEntityType:
                                 [filter entityTypeForEntity:inspectedEntity]]];

    [nonDisplayedFields removeObject:@"PajeEventName"];
    //[nonDisplayedFields removeObject:@"Value"];
    [nonDisplayedFields removeObject:@"Color"];

    [nonDisplayedFields removeObject:@"EntityType"];
    [nonDisplayedFields removeObject:@"Value"];
}

- (void)addOtherFields
{
    // other fields
    if ([nonDisplayedFields count] > 0) {
        NSBox *box;
        NSArray *fieldTitles = [nonDisplayedFields allObjects];

        box = [self boxWithTitle:@"Other values"
                     fieldTitles:fieldTitles
                      fieldNames:fieldTitles];
        [self addSubview:box];
    }
}

- (BOOL)isReusable
{
    return [reuseButton state];
}

- (void)setReusable:(BOOL)reuse
{
    [reuseButton setState:reuse];
}

- (IBAction)entityClicked:(id)sender
{
    NSCell *cell;
    if ([sender isKindOfClass:[NSMatrix class]]) {
        cell = [sender selectedCell];
    } else {
        cell = sender;
    }
    [self inspectEntity:[cell representedObject] withFilter:filter];
}

- (IBAction)colorChanged:(id)sender
{
    [filter setColor:[sender color] forEntity:inspectedEntity];
}

- (void)addScriptBox
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *scriptPath;
    NSString *scriptFieldName;

    scriptPath = [defaults objectForKey:@"EntityInspectorScriptPath"];
    scriptFieldName = [defaults objectForKey:@"EntityInspectorScriptFieldName"];
    if (scriptPath == nil) scriptPath = @"";
    if (scriptFieldName == nil) scriptFieldName = @"";
    [scriptPathField setStringValue:scriptPath];
    [scriptFieldNameField setStringValue:scriptFieldName];

    if ([[filter relatedEntitiesForEntity:inspectedEntity] count] == 0) {
        [scriptFieldSourceMatrix selectCellWithTag:0];
    }

    [[scriptBox retain] autorelease];
    [scriptBox removeFromSuperview];
    [self addSubview:scriptBox];
}

- (void)addRelatedEntities
{
    NSArray *relatedEntities;

    relatedEntities = [filter relatedEntitiesForEntity:inspectedEntity];
    if ([relatedEntities count] > 0) {
        NSEnumerator *relatedEnum;
        int row;
        PajeEntity *related;

        [relatedEntitiesMatrix renewRows:[relatedEntities count] columns:1];
        row = 0;
        relatedEnum = [relatedEntities objectEnumerator];
        while ((related = [relatedEnum nextObject]) != nil) {
            NSButtonCell *cell;
            cell = [relatedEntitiesMatrix cellAtRow:row++ column:0];
            [cell setTitle:[[filter valueForEntity:related] stringValue]];
            [cell setRepresentedObject:related];
            [cell setTarget:self];
            [cell setAction:@selector(entityClicked:)];
        }
        [relatedEntitiesMatrix sizeToCells];
        NSScrollView *sv = [relatedEntitiesMatrix enclosingScrollView];
        NSSize svSize = [sv frame].size;
        svSize.height = MIN(NSHeight([relatedEntitiesMatrix frame]) + 1, 105);
        [sv setFrameSize:svSize];
        [relatedEntitiesBox sizeToFit];
        [self addLastSubview:relatedEntitiesBox];
    }
}


- (void)inspectEntity:(id<PajeEntity>)entity
           withFilter:(PajeFilter *)f
{
    Assign(inspectedEntity, entity);
    Assign(filter, f);

    nonDisplayedFields = [[NSMutableSet alloc]
            initWithArray:[filter fieldNamesForEntity:entity]];

    [self reset];

    [self addGlobalFields];
    [self addLocalFields];

    [nonDisplayedFields removeObject:@"RelatedEntities"];
    [nonDisplayedFields removeObject:@"FileReference"];

    [self addOtherFields];

    [self addSourceReference];

    // script execution
    [self addScriptBox];

    // Related entities
    [self addRelatedEntities];
    
    int dif = NSMinY(boundingBox) - 10;
    if (dif != 0) {
        NSRect frame = [inspectionWindow frame];
        frame.origin.y += dif;
        frame.size.height -= dif;
        [inspectionWindow setContentSize:frame.size];
    }
    
    Assign(nonDisplayedFields, nil);

//    lastWindowPosition = [inspectionWindow cascadeTopLeftFromPoint:lastWindowPosition];
//    [inspectionWindow display];
    [inspectionWindow orderFront:self];
}

- (void)showSource:(id)sender
{
    SourceCodeReference *FileReference;
    NSString *filename;
    int lineNumber;
    NSArray *sourcePaths;

    FileReference = [inspectedEntity valueOfFieldNamed:@"FileReference"];
    if (!FileReference) {
        NSBeep();
        return;
    }
    
    sourcePaths = [[NSUserDefaults standardUserDefaults]
            arrayForKey:@"PajeSourcePaths"];

    filename = [FileReference filename];
    lineNumber = [FileReference lineNumber];
    if (sourcePaths && ([sourcePaths count] > 0)) {
        NSEnumerator *sourcePathEnum = [sourcePaths objectEnumerator];
        NSString *fullPath;

        while ((fullPath = [sourcePathEnum nextObject]) != nil) {
            fullPath = [fullPath stringByAppendingPathComponent:filename];
            if ([[NSFileManager defaultManager] 
                   isReadableFileAtPath:fullPath]) {
                [[SourceTextController controllerForFilename:fullPath]
                        selectLineNumber:lineNumber];
                return;
            }
        }
    }
    NSRunAlertPanel(@"File Not Found",
                    @"File '%@' has not been found or is not readable.\n"
                     @"Verify the value of the defaults variable"
                     @" \"PajeSourcePaths\" in the Info/Preferences... panel.\n"                      @"Currently, it is set to '%@'",
                    @"Ok", nil, nil, filename, sourcePaths);
}

- (IBAction)executeScript:(id)sender
{
    NSArray *entities;
    NSEnumerator *entitiesEnum;
    PajeEntity *entity;
    NSMutableArray *arguments;
    NSString *fieldName;
    NSString *scriptPath;
    NSTask *task;

    if ([[scriptFieldSourceMatrix selectedCell] tag] == 0) {
        entities = [NSArray arrayWithObject:inspectedEntity];
    } else {
        entities = [inspectedEntity relatedEntities];
        if ([entities count] < 1) {
            NSRunAlertPanel(@"Entity Inspector",
                            @"No related entities!", nil, nil, nil);
            return;
        }
    }

    fieldName = [scriptFieldNameField stringValue];
    if ((fieldName == nil) || ([fieldName isEqual:@""])) {
        NSRunAlertPanel(@"Entity Inspector",
                        @"Field name not defined!", nil, nil, nil);
        return;
    }
    [[NSUserDefaults standardUserDefaults]
            setObject:fieldName forKey:@"EntityInspectorScriptFieldName"];

    scriptPath = [scriptPathField stringValue];
    if ((scriptPath == nil) || ([scriptPath isEqual:@""])) {
        NSRunAlertPanel(@"EntityInspector",
                        @"Program path not defined!", nil, nil, nil);
        return;
    }
    [[NSUserDefaults standardUserDefaults]
            setObject:scriptPath forKey:@"EntityInspectorScriptPath"];

    if (![[NSFileManager defaultManager] isExecutableFileAtPath:scriptPath]) {
        NSRunAlertPanel(@"EntityInspector",
                        @"File '%@' does not exist or is not executable!",
                        nil, nil, nil, scriptPath);
        return;
    }

    arguments = [NSMutableArray array];
    entitiesEnum = [entities objectEnumerator];
    while ((entity = [entitiesEnum nextObject]) != nil) {
        id argument;
        argument = [[entity valueOfFieldNamed:fieldName] description];
        if (argument == nil)
            argument = @"--nil--";
        [arguments addObject:argument];
    }
    
    task = [NSTask launchedTaskWithLaunchPath:scriptPath arguments:arguments];
}

@end