File: PdfViewer.m

package info (click to toggle)
gworkspace 0.9.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 20,832 kB
  • sloc: objc: 69,382; sh: 488; makefile: 39
file content (520 lines) | stat: -rw-r--r-- 13,724 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
/* PdfViewer.m
 *  
 * Copyright (C) 2004-2012 Free Software Foundation, Inc.
 *
 * Author: Enrico Sersale <enrico@imago.ro>
 * Date: January 2004
 *
 * This file is part of the GNUstep Inspector 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., 51 Franklin Street, Fifth Floor, Boston, MA 02111 USA.
 */

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

#import <AppKit/AppKit.h>
#if !HAVE_POPPLERKIT
#import <PDFKit/PDFDocument.h>
#import <PDFKit/PDFImageRep.h>
#else
#import <PopplerKit/PopplerKit.h>
#endif
#import "PdfViewer.h"

#define MAXPAGES 9999

const double PDFResolution = 72.0;

@implementation PdfViewer

- (void)dealloc
{
  TEST_RELEASE (pdfPath);	
#if !HAVE_POPPLERKIT
  TEST_RELEASE (pdfDoc);
  TEST_RELEASE (imageRep);
#else
  TEST_RELEASE (pdfRenderer);
#endif
  RELEASE (backButt);
  RELEASE (nextButt);
  RELEASE (scroll);
  RELEASE (matrix);
  RELEASE (imageView);
  RELEASE (errLabel);
  [super dealloc];
}

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

#define MARGIN 3
		
      vr = NSMakeRect(0, r.size.height - 25 - MARGIN, 25, 25);
      nextButt = [[NSButton alloc] initWithFrame: vr];
      [nextButt setButtonType: NSMomentaryLight];
      [nextButt setImagePosition: NSImageOnly];	
      [nextButt setImage: [NSImage imageNamed: @"common_ArrowUp.tiff"]];
      [nextButt setTarget: self];
      [nextButt setAction: @selector(nextPage:)];
      [self addSubview: nextButt]; 

      vr.origin.y -= 25;
      backButt = [[NSButton alloc] initWithFrame: vr];
      [backButt setButtonType: NSMomentaryLight];
      [backButt setImagePosition: NSImageOnly];	
      [backButt setImage: [NSImage imageNamed: @"common_ArrowDown.tiff"]];
      [backButt setTarget: self];
      [backButt setAction: @selector(previousPage:)];
      [self addSubview: backButt]; 

      vr.origin.x = 25 + MARGIN;
      vr.size.width = r.size.width - vr.origin.x;
      vr.size.height = 50;
      scroll = [[NSScrollView alloc] initWithFrame: vr];
      [scroll setBorderType: NSBezelBorder];
      [scroll setHasHorizontalScroller: YES];
      [scroll setHasVerticalScroller: NO]; 
      [scroll setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable];
      [self addSubview: scroll]; 

    cell = AUTORELEASE ([NSButtonCell new]);
    [cell setButtonType: NSPushOnPushOffButton];
    [cell setImagePosition: NSImageOverlaps]; 
						
    matrix = [[NSMatrix alloc] initWithFrame: NSZeroRect
				            				mode: NSRadioModeMatrix prototype: cell
			       												numberOfRows: 0 numberOfColumns: 0];
    [matrix setIntercellSpacing: NSZeroSize];
    [matrix setCellSize: NSMakeSize(26, [[scroll contentView] bounds].size.height)];
		[matrix setAllowsEmptySelection: YES];
		[matrix setTarget: self];
		[matrix setAction: @selector(goToPage:)];
		[scroll setDocumentView: matrix];	

    vr.size.height = vr.origin.y - 42 - MARGIN;
    vr.origin.x = 0;
    vr.origin.y = 42;
    vr.size.width = r.size.width;
		imageView = [[NSImageView alloc] initWithFrame: vr];
    [imageView setImageFrameStyle: NSImageFrameGrayBezel];
 //   [imageView setImageScaling: NSScaleNone];
		[imageView setImageAlignment: NSImageAlignCenter];
		[imageView setEditable: NO];
  	[self addSubview: imageView]; 

    vr.origin.x = 2;
    vr.origin.y = 170;
    vr.size.width = r.size.width - 4;
    vr.size.height = 25;
		errLabel = [[NSTextField alloc] initWithFrame: vr];	
		[errLabel setFont: [NSFont systemFontOfSize: 18]];
		[errLabel setAlignment: NSCenterTextAlignment];
		[errLabel setBackgroundColor: [NSColor windowBackgroundColor]];
		[errLabel setTextColor: [NSColor grayColor]];	
		[errLabel setBezeled: NO];
		[errLabel setEditable: NO];
		[errLabel setSelectable: NO];
		[errLabel setStringValue: NSLocalizedString(@"Invalid Contents", @"")];

    vr.origin.x = 141;
    vr.origin.y = 10;
    vr.size.width = 115;
    vr.size.height = 25;
	  editButt = [[NSButton alloc] initWithFrame: vr];
	  [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);

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

		valid = YES;
		
    pdfPath = nil;
    
    [self setContextHelp];
	}
	
	return self;
}

- (void)displayPath:(NSString *)path
{
#if !HAVE_POPPLERKIT
  PDFDocument *doc;
#else
  PopplerDocument *doc;
#endif
  
  ASSIGN (pdfPath, path);

  if ([self superview]) {      
    [inspector contentsReadyAt: pdfPath];
  }
  
  [editButt setEnabled: NO];	
  
#if !HAVE_POPPLERKIT
  doc = [PDFDocument documentFromFile: pdfPath];

  if ([doc isOk] && ([doc errorCode] == 0)) {
    NSSize imageSize;
#else
  NS_DURING
    doc = [PopplerDocument documentWithPath: pdfPath];
  NS_HANDLER
    doc = nil;
  NS_ENDHANDLER

  if (doc) {
#endif
    int npages;
	  NSBundle *bundle;
	  NSString *imagePath;
	  NSImage *miniPage;
    id cell;
    int i;

    if (valid == NO) {
      valid = YES;
      [errLabel removeFromSuperview];
      [self addSubview: backButt]; 
      [self addSubview: nextButt]; 
      [self addSubview: scroll]; 
      [self addSubview: imageView]; 
    }
    
    [imageView setImage: nil];
    
    [editButt setEnabled: YES];		
    [[self window] makeFirstResponder: editButt];
    
	  if (matrix) {
		  [matrix removeFromSuperview];	
		  [scroll setDocumentView: nil];		
		  DESTROY (matrix);
	  }
    
  	cell = AUTORELEASE ([NSButtonCell new]);
  	[cell setButtonType: NSPushOnPushOffButton];
  	[cell setImagePosition: NSImageOverlaps]; 

  	matrix = [[NSMatrix alloc] initWithFrame: NSZeroRect
				            				mode: NSRadioModeMatrix prototype: cell
			       												numberOfRows: 0 numberOfColumns: 0];
  	[matrix setIntercellSpacing: NSZeroSize];
  	[matrix setCellSize: NSMakeSize(26, [[scroll contentView] bounds].size.height)];
		[matrix setAllowsEmptySelection: YES];
		[matrix setTarget: self];
		[matrix setAction: @selector(goToPage:)];
		[scroll setDocumentView: matrix];	

		bundle = [NSBundle bundleForClass: [self class]];
		imagePath = [bundle pathForResource: @"page" ofType: @"tiff" inDirectory: nil];		
		miniPage = [[NSImage alloc] initWithContentsOfFile: imagePath];
    
    npages = [doc countPages];
    
		for (i = 0; i < npages; i++) {
      [matrix addColumn];

			cell = [matrix cellAtRow: 0 column: i];
			if (i < 100) {
				[cell setFont: [NSFont systemFontOfSize: 10]];
			} else {
				[cell setFont: [NSFont systemFontOfSize: 8]];
			}
			[cell setImage: miniPage];     
			[cell setTitle: [NSString stringWithFormat: @"%i", i+1]];     
		}
		[matrix sizeToCells];
		RELEASE (miniPage);	    

#if !HAVE_POPPLERKIT
    DESTROY (imageRep);
    ASSIGN (pdfDoc, doc);

    imageSize = NSMakeSize([pdfDoc pageWidth: 1],
                                    [pdfDoc pageHeight: 1]);
    imageRep = [[PDFImageRep alloc] initWithDocument: pdfDoc];
    [imageRep setSize: imageSize];
#else
    DESTROY (pdfRenderer);
    ASSIGN (pdfDoc, doc);

    if ([PopplerCairoImageRenderer isSupported])
      pdfRenderer = [[PopplerCairoImageRenderer alloc] initWithDocument:
							 pdfDoc];
    else
      pdfRenderer = [[PopplerSplashRenderer alloc] initWithDocument: pdfDoc];
#endif

  } else {
    if (valid) {
      valid = NO;
      [backButt removeFromSuperview];
      [nextButt removeFromSuperview];
      [scroll removeFromSuperview];
      [imageView removeFromSuperview];
			[self addSubview: errLabel];      
			[editButt setEnabled: NO];		
    }
  }
  
  if (valid) {
    [matrix selectCellAtRow: 0 column: 0];
    [matrix sendAction];
  }
}

- (void)displayLastPath:(BOOL)forced
{
  if (pdfPath) {
    if (forced) {
      [self displayPath: pdfPath];
    } else {
      [inspector contentsReadyAt: pdfPath];
    }
  }
}

- (void)goToPage:(id)sender
{
  NSImage *image = nil;
  int index;
  NSSize imsize;
  NSSize unscaledSize;
                                              

  index = [matrix selectedColumn] + 1;
  if (index <= 0)
    return;

  imsize = [imageView bounds].size;
#if !HAVE_POPPLERKIT
  unscaledSize = NSMakeSize([pdfDoc pageWidth: index], [pdfDoc pageHeight: index]);
#else
  unscaledSize = [[pdfDoc page: index] size];
  float scaleFactor = 1.0;
  NSImageRep *imageRep;
#endif

  if ((imsize.width < unscaledSize.width) || (imsize.height < unscaledSize.height))
    {
      float rw, rh;
#if !HAVE_POPPLERKIT
      NSSize scaledSize;
      float xfactor, yfactor;  
#endif

      rw = imsize.width / unscaledSize.width;
      rh = imsize.height / unscaledSize.height;

#if HAVE_POPPLERKIT
      scaleFactor = rw <= rh ? rw : rh;
#else
      if (rw <= rh)
	{
	  scaledSize.width = unscaledSize.width * rw;
	  scaledSize.height = floor(imsize.width * unscaledSize.height / unscaledSize.width + 0.5);
	}
      else
	{
	  scaledSize.height = unscaledSize.height * rh;
	  scaledSize.width  = floor(imsize.height * unscaledSize.width / unscaledSize.height + 0.5);    
	}

      xfactor = scaledSize.width / unscaledSize.width * PDFResolution;
      yfactor = scaledSize.height / unscaledSize.height * PDFResolution;

      [imageRep setResolution: (xfactor < yfactor ? xfactor : yfactor)];
#endif
    }

#if !HAVE_POPPLERKIT
  [imageRep setPageNum: index];
#else
  imageRep = [pdfRenderer renderPage: [pdfDoc page: index] scale: scaleFactor];
#endif

  image = [[NSImage alloc] initWithSize: [imageRep size]];
  [image setBackgroundColor: [NSColor whiteColor]];
  [image setScalesWhenResized: YES];
  [image addRepresentation: imageRep];
  [imageView setImage: image];
  RELEASE (image);
}

- (void)displayData:(NSData *)data 
             ofType:(NSString *)type
{
}

- (NSString *)currentPath
{
  return pdfPath;
}

- (void)stopTasks
{

}

- (BOOL)canDisplayPath:(NSString *)path
{
  NSDictionary *attributes;
	NSString *defApp, *fileType;

  attributes = [[NSFileManager defaultManager] fileAttributesAtPath: path
                                                       traverseLink: YES];
  if ([attributes objectForKey: NSFileType] == NSFileTypeDirectory) {
    return NO;
  }		
		
	[ws getInfoForFile: path application: &defApp type: &fileType];

  if(([fileType isEqual: NSPlainFileType] == NO)
                  && ([fileType isEqual: NSShellCommandFileType] == NO)) {
    return NO;
  }
	
	if ([[[path pathExtension] lowercaseString] isEqual: @"pdf"]) {
		return YES;
	}

	return NO;
}

- (BOOL)canDisplayDataOfType:(NSString *)type
{
  return NO;
}

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

- (NSString *)description
{
	return NSLocalizedString(@"This Inspector allow you View the content of a PDF file", @"");	
}

- (void)nextPage:(id)sender
{
  int index;


  index = [matrix selectedColumn] + 1;
  if (index <= 0)
    return;

  if (index < [pdfDoc countPages])
    index++;
  else
    index = [pdfDoc countPages];

  [matrix selectCellAtRow:0 column:index-1];
  [matrix sendAction];
}

- (void)previousPage:(id)sender
{
  int index;

  index = [matrix selectedColumn] + 1;
  if (index <= 0)
    return;

  if (index > 1)
    index--;
  else
    index = 1;

  [matrix selectCellAtRow:0 column:index-1];
  [matrix sendAction];
}



- (void)editFile:(id)sender
{
	NSString *appName;
  NSString *type;

  [ws getInfoForFile: pdfPath application: &appName type: &type];

	if (appName) {
    NS_DURING
      {
    [ws openFile: pdfPath withApplication: appName];
      }
    NS_HANDLER
      {
    NSRunAlertPanel(NSLocalizedString(@"error", @""), 
        [NSString stringWithFormat: @"%@ %@!", 
          NSLocalizedString(@"Can't open ", @""), [pdfPath lastPathComponent]],
                                      NSLocalizedString(@"OK", @""), 
                                      nil, 
                                      nil);                                     
      }
    NS_ENDHANDLER  
	}
}

- (void)setContextHelp
{
  NSString *bpath = [[NSBundle bundleForClass: [self class]] bundlePath];
  NSString *resPath = [bpath stringByAppendingPathComponent: @"Resources"];
  NSArray *languages = [NSUserDefaults userLanguages];
  unsigned i;
     
  for (i = 0; i < [languages count]; i++) {
    NSString *language = [languages objectAtIndex: i];
    NSString *langDir = [NSString stringWithFormat: @"%@.lproj", language];  
    NSString *helpPath = [langDir stringByAppendingPathComponent: @"Help.rtfd"];
  
    helpPath = [resPath stringByAppendingPathComponent: helpPath];
  
    if ([fm fileExistsAtPath: helpPath]) {
      NSAttributedString *help = [[NSAttributedString alloc] initWithPath: helpPath
                                                       documentAttributes: NULL];
      if (help) {
        [[NSHelpManager sharedHelpManager] setContextHelp: help forObject: self];
        RELEASE (help);
      }
    }
  }
}

@end