File: Contents.m

package info (click to toggle)
gworkspace 1.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 15,124 kB
  • sloc: objc: 71,982; sh: 488; makefile: 43
file content (741 lines) | stat: -rw-r--r-- 19,023 bytes parent folder | download
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
/* Contents.m
 *  
 * Copyright (C) 2004-2024 Free Software Foundation, Inc.
 *
 * Author: Enrico Sersale
 * Author: Riccardo Mottola <rm@gnu.org>
 *
 * Date: January 2004
 *
 * This file is part of the GNUstep GWorkspace application
 *
 * This program 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 program 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
 */

#include <math.h>
#include "config.h"

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "Contents.h"
#import "ContentViewersProtocol.h"
#import "Inspector.h"
#import "IconView.h"
#import "Functions.h"
#import "FSNodeRep.h"

#define ICNSIZE 48
#define MAXDATA 1000

#if defined(__MINGW__)
#define SHPATH "/bin/sh"
#define FILEPATH "/bin/file"
#endif

static NSString *nibName = @"Contents";

@implementation Contents

- (void)dealloc
{
  RELEASE (viewers);
  RELEASE (currentPath);
  RELEASE (genericView);
  RELEASE (noContsView);
  RELEASE (textViewer);
  RELEASE (mainBox);
  RELEASE (pboardImage);
      
  [super dealloc];
}

- (id)initForInspector:(id)insp
{
  self = [super init];
  
  if (self)
    {
      NSBundle *bundle;
      NSEnumerator *enumerator;
      NSString *imagepath;
      NSString *bundlesDir;
      NSArray *bnames;
      id label;
      unsigned i;
      NSRect r;

      if ([NSBundle loadNibNamed: nibName owner: self] == NO)
        {
          NSLog(@"failed to load %@!", nibName);
          [NSApp terminate: self];
        }

      RETAIN (mainBox);
      RELEASE (win);

      inspector = insp;
      [iconView setInspector: inspector];
      viewers = [NSMutableArray new];
      currentPath = nil;

      fm = [NSFileManager defaultManager];
      ws = [NSWorkspace sharedWorkspace];

      bundle = [NSBundle bundleForClass: [inspector class]];
      imagepath = [bundle pathForResource: @"Pboard" ofType: @"tiff"];
      pboardImage = [[NSImage alloc] initWithContentsOfFile: imagepath];

      r = [[viewersBox contentView] bounds];

      enumerator = [NSSearchPathForDirectoriesInDomains
                     (NSLibraryDirectory, NSAllDomainsMask, YES) objectEnumerator];
      while ((bundlesDir = [enumerator nextObject]) != nil)
        {
          bundlesDir = [bundlesDir stringByAppendingPathComponent: @"Bundles"];
          bnames = [fm directoryContentsAtPath: bundlesDir];

          for (i = 0; i < [bnames count]; i++)
            {
              NSString *bname = [bnames objectAtIndex: i];
	
              if ([[bname pathExtension] isEqual: @"inspector"])
                {
                  NSString *bpath = [bundlesDir stringByAppendingPathComponent: bname];

                  bundle = [NSBundle bundleWithPath: bpath];

                  if (bundle)
                    {
                      Class principalClass = [bundle principalClass];

                      if ([principalClass conformsToProtocol: @protocol(ContentViewersProtocol)])
                        {
                          CREATE_AUTORELEASE_POOL (pool);
                          id vwr = [[principalClass alloc] initWithFrame: r inspector: self];

                          [viewers addObject: vwr];
                          [vwr release];
                          RELEASE (pool);
                        }
                    }
                }
            }
        }

    // We reorter viewers and put the ImageViewer at the end, so that specialized viewers,
    // e.g. PDF Viewer, can take precedence
    // String comparison, so no class import is needed
    for (i = 0; i < [viewers count]; i++)
      {
        id vwr = [viewers objectAtIndex: i];

        if ([NSStringFromClass([vwr class]) isEqualToString:@"ImageViewer"])
          {
            [viewers removeObjectAtIndex: i];
            [viewers addObject: vwr];
            break;
          }
      }

    textViewer = [[TextViewer alloc] initWithFrame: r forInspector: self];					
    genericView = [[GenericView alloc] initWithFrame: r];					

    noContsView = [[NSView alloc] initWithFrame: r];
    MAKE_LABEL (label, NSMakeRect(2, 125, 254, 65), _(@"No Contents Inspector"), 'c', YES, noContsView);		  
    [label setFont: [NSFont systemFontOfSize: 18]];
    [label setTextColor: [NSColor grayColor]];				

    currentViewer = nil;
  }
  
  return self;
}

- (NSView *)inspView
{
  return mainBox;
}

- (NSString *)winname
{
  return NSLocalizedString(@"Contents Inspector", @"");
}

- (void)activateForPaths:(NSArray *)paths
{
  if ([paths count] == 1)
    {
      [self showContentsAt: [paths objectAtIndex: 0]];
    }
  else
    {
      NSImage *icon = [[FSNodeRep sharedInstance] multipleSelectionIconOfSize: ICNSIZE];
      NSString *items;
    
      items = [NSString stringWithFormat: @"%lu %@",
                        (unsigned long)[paths count],
                        NSLocalizedString(@"Items", @"")];
      [titleField setStringValue: items];  
      [iconView setImage: icon];
    
      [viewersBox setContentView: noContsView];
      currentViewer = noContsView;
    
      if (currentPath) {
        [inspector removeWatcherForPath: currentPath];
        DESTROY (currentPath);
      }    
	
      [[inspector win] setTitle: [self winname]];
    }
}

- (id)viewerForPath:(NSString *)path
{
  NSInteger i;
  
  if ((path == nil) || ([fm fileExistsAtPath: path] == NO))
    {
      return nil;
    }
    
  for (i = 0; i < [viewers count]; i++)
    {
      id vwr = [viewers objectAtIndex: i];		
      if ([vwr canDisplayPath: path])
        {
          return vwr;
        }				
    }
  
  return nil;
}

- (id)viewerForDataOfType:(NSString *)type
{
  NSUInteger i;
  
  for (i = 0; i < [viewers count]; i++)
    {
      id vwr = [viewers objectAtIndex: i];		
      
      if ([vwr respondsToSelector: @selector(canDisplayDataOfType:)])
        {
          if ([vwr canDisplayDataOfType: type])
            {
              return vwr;
            }
        } 				
    }
  
  return nil;
}

- (void)showContentsAt:(NSString *)path
{
  NSString *winName;

  // No change in selection? leave current path
  if (currentPath && [currentPath isEqual:path])
    {
      NSLog(@"trying to redisplay %@", path);
      return;
    }

  // we change content to new path or to nil
  // stop current work (e.g. resizing)
  if (currentViewer && [currentViewer respondsToSelector: @selector(stopTasks)])
    {
      [currentViewer stopTasks];
    }

  // stop watching the displayed content, since we change it
  [inspector removeWatcherForPath: currentPath];
  DESTROY (currentPath);

  // Are we going to display the new path?
  if (path && [fm fileExistsAtPath: path])
    {
      id viewer;

      viewer = [self viewerForPath: path];
      if (viewer)
	{
	  currentViewer = viewer;
	  winName = [viewer winname];
	  [viewersBox setContentView: viewer];
    
	  [viewer displayPath: path];
	}
      else
	{
	  FSNode *node = [FSNode nodeWithPath: path];
	  NSImage *icon = [[FSNodeRep sharedInstance] iconOfSize: ICNSIZE forNode: node];

	  [iconView setImage: icon];
	  [titleField setStringValue: [node name]];

	  if ([textViewer tryToDisplayPath: path])
	    {
	      [viewersBox setContentView: textViewer];
	      currentViewer = textViewer;
	      winName = NSLocalizedString(@"Text Inspector", @"");
	      if (currentPath == nil)
		{
		  ASSIGN (currentPath, path);
		  [inspector addWatcherForPath: currentPath];
		}
	    }
	  else
	    {
	      [viewersBox setContentView: genericView];
	      currentViewer = genericView;
	      [genericView showInfoOfPath: path];
	      winName = NSLocalizedString(@"Contents Inspector", @"");
	    }
	}
    }
  else
    {
      [iconView setImage: nil];
      [titleField setStringValue: @""];
      [viewersBox setContentView: noContsView];
      currentViewer = noContsView;
      winName = NSLocalizedString(@"Contents Inspector", @"");

      if (currentPath)
	{
	  [inspector removeWatcherForPath: currentPath];
	  DESTROY (currentPath);
	}
    }
	
  [[inspector win] setTitle: winName];
}

- (void)contentsReadyAt:(NSString *)path
{
  FSNode *node;
  NSImage *icon;

  node = [FSNode nodeWithPath: path];
  [titleField setStringValue: [node name]];
  icon = [[FSNodeRep sharedInstance] iconOfSize: ICNSIZE forNode: node];
  [iconView setImage: icon];

  if (currentPath == nil)
    {
      ASSIGN (currentPath, path);
      [inspector addWatcherForPath: currentPath];
    }
}

- (BOOL)canDisplayDataOfType:(NSString *)type
{
  return ([self viewerForDataOfType: type] != nil);
}

- (void)showData:(NSData *)data 
          ofType:(NSString *)type
{
	NSString *winName;
	id viewer;

  if (currentViewer) {
    if ([currentViewer respondsToSelector: @selector(stopTasks)]) {
      [currentViewer stopTasks]; 
    }
  }   

  if (currentPath) {
    [inspector removeWatcherForPath: currentPath];
    DESTROY (currentPath);
  }
  
  viewer = [self viewerForDataOfType: type];
  
	if (viewer) {   
    currentViewer = viewer;
    winName = [viewer winname];
    [viewersBox setContentView: viewer];
    [viewer displayData: data ofType: type];

	} else {	   
    [iconView setImage: pboardImage];
    [titleField setStringValue: @""];  
    [viewersBox setContentView: noContsView];
    currentViewer = noContsView;
	  winName = NSLocalizedString(@"Data Inspector", @"");
  }
	
	[[inspector win] setTitle: winName];
	[viewersBox setNeedsDisplay: YES];
}

- (BOOL)isShowingData
{
  return (currentPath == nil);
}

- (void)dataContentsReadyForType:(NSString *)typeDescr
                         useIcon:(NSImage *)icon
{
  [iconView setImage: icon];
  [titleField setStringValue: typeDescr];
}

- (void)watchedPathDidChange:(NSDictionary *)info
{
  NSString *path = [info objectForKey: @"path"];
  NSString *event = [info objectForKey: @"event"];

  if (currentPath && [currentPath isEqual: path]) {
    if ([event isEqual: @"GWWatchedPathDeleted"]) {
      [self showContentsAt: nil];

    } else if ([event isEqual: @"GWWatchedFileModified"]) {
      if (currentViewer) {
        if ([currentViewer respondsToSelector: @selector(displayPath:)]) {
          [currentViewer displayPath: currentPath];
        } else if (currentViewer == textViewer) {
          [currentViewer tryToDisplayPath: currentPath];
        }
      }
    }
  }
}

- (id)inspector
{
  return inspector;
}

@end


@implementation TextViewer

- (void)dealloc
{
  RELEASE (editPath);	
  [super dealloc];
}

- (id)initWithFrame:(NSRect)frameRect
       forInspector:(id)insp
{
  self = [super initWithFrame: frameRect];
  
  if (self)
    {
    NSRect r = [self bounds];

    r.origin.y += 45;
    r.size.height -= 45;
    scrollView = [[NSScrollView alloc] initWithFrame: r];
    [scrollView setBorderType: NSBezelBorder];
    [scrollView setHasHorizontalScroller: NO];
    [scrollView setHasVerticalScroller: YES]; 
    [scrollView setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable];
    [[scrollView contentView] setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable];
    [[scrollView contentView] setAutoresizesSubviews: YES];
    [self addSubview: scrollView]; 
    RELEASE (scrollView);
    
    r = [[scrollView contentView] bounds];
    textView = [[NSTextView alloc] initWithFrame: r];
    [textView setBackgroundColor: [NSColor whiteColor]];
    [textView setRichText: YES];
    [textView setEditable: NO];
    [textView setSelectable: NO];
    [textView setHorizontallyResizable: NO];
    [textView setVerticallyResizable: YES];
    [textView setMinSize: NSMakeSize (0, 0)];
    [textView setMaxSize: NSMakeSize (1E7, 1E7)];
    [textView setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable];
    [[textView textContainer] setContainerSize: NSMakeSize(r.size.width, 1e7)];
    [[textView textContainer] setWidthTracksTextView: YES];
    [textView setUsesRuler: NO];
    [scrollView setDocumentView: textView];
    RELEASE (textView);
    
    r.origin.x = 141;
    r.origin.y = 10;
    r.size.width = 115;
    r.size.height = 25;
	  editButt = [[NSButton alloc] initWithFrame: r];
	  [editButt setButtonType: NSMomentaryLight];
    [editButt setImage: [NSImage imageNamed: @"common_ret.tiff"]];
    [editButt setImagePosition: NSImageRight];
	  [editButt setTitle: NSLocalizedString(@"Edit", @"")];
	  [editButt setTarget: self];
	  [editButt setAction: @selector(editFile:)];	
    [editButt setEnabled: NO];		
		[self addSubview: editButt]; 
    RELEASE (editButt);
    
    contsinsp = insp;
    editPath = nil;
    ws = [NSWorkspace sharedWorkspace];
  }
	
  return self;
}

- (BOOL)tryToDisplayPath:(NSString *)path
{
  NSFileManager *fm = [NSFileManager defaultManager];
  NSDictionary *attributes = [fm fileAttributesAtPath: path traverseLink: YES];

  DESTROY (editPath);
  [editButt setEnabled: NO];	

  if (attributes && ([attributes fileType] != NSFileTypeDirectory))
    {
      NSString *app = nil, *type = nil;

      [ws getInfoForFile: path application: &app type: &type];

      if (type && ((type == NSPlainFileType) || (type == NSShellCommandFileType)))
	{
	  NSData *data = [self textContentsAtPath: path withAttributes: attributes];

	  if (data)
	    {
	      CREATE_AUTORELEASE_POOL (pool);
	      NSString *str = [[NSString alloc] initWithData: data
						    encoding: [NSString defaultCStringEncoding]];
	      NSAttributedString *attrstr = [[NSAttributedString alloc] initWithString: str];

	      [[textView textStorage] setAttributedString: attrstr];
	      [[textView textStorage] addAttribute: NSFontAttributeName
					     value: [NSFont systemFontOfSize: 8.0]
					     range: NSMakeRange(0, [attrstr length])];
	      RELEASE (str);
	      RELEASE (attrstr);
	      [editButt setEnabled: YES];
	      ASSIGN (editPath, path);
	      RELEASE (pool);

	      return YES;
	    }
	}
    }

  return NO;
}

- (NSData *)textContentsAtPath:(NSString *)path 
                withAttributes:(NSDictionary *)attributes
{
  unsigned long long nbytes = [attributes fileSize];
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath: path];
  NSData *data;
    
  nbytes = ((nbytes > MAXDATA) ? MAXDATA : nbytes);
  
  NS_DURING
    {
      data = [handle readDataOfLength: nbytes];
    }
  NS_HANDLER
    {
      [handle closeFile];
	    return nil;
    }
  NS_ENDHANDLER
  
  [handle closeFile];
  
  if (data) {
    const char *bytes = [data bytes];
    int i;
    
    for (i = 0; i < nbytes; i++) {
      if (!isascii(bytes[i])) {
        return nil;
      }
    }
    
    return data;
  }

  return nil;
}

- (void)editFile:(id)sender
{
  if (editPath) {
    [[[contsinsp inspector] desktopApp] openFile: editPath];
  }
}

@end


@implementation GenericView

- (void)dealloc
{
  [nc removeObserver: self];
  if (task && [task isRunning]) {
    [task terminate];
	}
  RELEASE (task);
  RELEASE (pipe);
  RELEASE (shComm);
  RELEASE (fileComm);  
  [super dealloc];
}

- (id)initWithFrame:(NSRect)frameRect
{
  self = [super initWithFrame: frameRect];
	
  if (self) {	
    NSString *comm;
    NSRect r;
          
    shComm = nil;      
    fileComm = nil;  
        
    comm = [NSString stringWithCString: SHPATH];
    if ([comm isEqual: @"none"] == NO) {
      ASSIGN (shComm, comm);
    } 
    comm = [NSString stringWithCString: FILEPATH];
    if ([comm isEqual: @"none"] == NO) {
      ASSIGN (fileComm, comm);
    }
    
    nc = [NSNotificationCenter defaultCenter];
    
    r = NSMakeRect(0, 60, frameRect.size.width, 140);
    textview = [[NSTextView alloc] initWithFrame: r];
    [[textview textContainer] setContainerSize: [textview bounds].size];
		[textview setDrawsBackground: NO];
    [textview setRichText: NO];
    [textview setSelectable: NO];
    [textview setVerticallyResizable: NO];
    [textview setHorizontallyResizable: NO];
    
    [self addSubview: textview];
    RELEASE (textview);
  }

  return self;
}

- (void)showInfoOfPath:(NSString *)path
{
  [self showString: @""];

  if (shComm && fileComm)
    {
      CREATE_AUTORELEASE_POOL (pool);
      NSString *str;
      NSFileHandle *handle;

      [nc removeObserver: self];
          if (task && [task isRunning])
            {
              [task terminate];
            }
          DESTROY (task);		
    
          task = [NSTask new]; 
          [task setLaunchPath: shComm];
          str = [NSString stringWithFormat: @"%@ -b \"%@\"", fileComm, path];
          [task setArguments: [NSArray arrayWithObjects: @"-c", str, nil]];
          ASSIGN (pipe, [NSPipe pipe]);
          [task setStandardOutput: pipe];

          handle = [pipe fileHandleForReading];
          [nc addObserver: self
                 selector: @selector(dataFromTask:)
                     name: NSFileHandleReadToEndOfFileCompletionNotification
                   object: handle];

          [handle readToEndOfFileInBackgroundAndNotify];    

          [task launch];   
       
          RELEASE (pool);   
  }
  else
    {  
      [self showString: NSLocalizedString(@"No Contents Inspector", @"")];
    }        
}

- (void)dataFromTask:(NSNotification *)notif
{
  CREATE_AUTORELEASE_POOL (pool);
  NSDictionary *userInfo = [notif userInfo];
  NSData *data = [userInfo objectForKey: NSFileHandleNotificationDataItem];
  NSString *str;
  
  if (data && [data length])
    {
      str = [[NSString alloc] initWithData: data 
                                  encoding: [NSString defaultCStringEncoding]];
    }
  else
    {
      str = [[NSString alloc] initWithString: NSLocalizedString(@"No Contents Inspector", @"")];
    }
  
  [self showString: str];
  
  RELEASE (str);
  RELEASE (pool);   
}

- (void)showString:(NSString *)str
{
  CREATE_AUTORELEASE_POOL (pool);
  NSAttributedString *attrstr = [[NSAttributedString alloc] initWithString: str];      
  NSRange range = NSMakeRange(0, [attrstr length]);
  NSTextStorage *storage = [textview textStorage];
  NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
  
  [storage setAttributedString: attrstr];
  
  [style setParagraphStyle: [NSParagraphStyle defaultParagraphStyle]];   
  [style setAlignment: NSCenterTextAlignment];
  
  [storage addAttribute: NSParagraphStyleAttributeName 
                  value: style 
                  range: range];
  
  [storage addAttribute: NSFontAttributeName 
                  value: [NSFont systemFontOfSize: 18] 
                  range: range];

  [storage addAttribute: NSForegroundColorAttributeName 
                  value: [NSColor darkGrayColor] 
                  range: range];			

  RELEASE (attrstr);
  RELEASE (style);
  RELEASE (pool);   
}

@end