File: ZipperDocument.m

package info (click to toggle)
zipper.app 1.5-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 644 kB
  • sloc: objc: 3,829; makefile: 11
file content (550 lines) | stat: -rw-r--r-- 15,066 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
/*

  ZipperDocument.m
  Zipper

  Copyright (C) 2012 Free Software Foundation, Inc

  Authors: Dirk Olmes <dirk@xanthippe.ping.de>
           Riccardo Mottola <rm@gnu.org>

  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 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

 */

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "ZipperDocument.h"
#import "ZipperCell.h"
#import "Archive.h"
#import "TableViewDataSource.h"
#import "PreferencesController.h"
#import "Preferences.h"
#import "NSFileManager+Custom.h"
#import "FileInfo.h"

#define X_INVALID_COL_ID	@"InvalidColumIdentiferException"

#if !defined (GNUSTEP) &&  (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4)
#define sel_isEqual(s1,s2) ((s1)==(s2))
#endif

@interface ZipperDocument (PrivateAPI)
- (BOOL)openArchiveWithPath:(NSString *)path;
- (void)addRatioColumn;
- (void)removeRatioColumn;
- (void)extractIncludingPathInfo:(BOOL)includePathInfo;
- (void)setArchive:(Archive *)archive;
- (void)openFile:(NSString *)file withDefaultApp:(NSString *)defaultApp;
- (Class)archiveClassForFile:(NSString *)filename;
- (Class)archiveClassByFileExtension:(NSString *)path;
- (Class)archiveClassByFileContents:(NSString *)path;
- (BOOL)createUnarchiveDestinationIfNecessary:(NSString *)path;
@end

@implementation ZipperDocument : NSDocument

- (id)init
{
	[super init];
	_tableViewDataSource = nil;
	return self;
}

- (void)dealloc
{
	[_archive release];
	[_tableViewDataSource release];
	[super dealloc];
}

//-----------------------------------------------------------------------------
// NSDocument overrides
//-----------------------------------------------------------------------------
/*" Name of the .gsmarkup file to load */
- (NSString *)windowNibName
{
	return @"ZipperDocument";
}

/*" Override of NSDocument, called when document is about to be opened */
- (void)windowControllerDidLoadNib:(NSWindowController *)controller;
{
	NSSize size;
	NSTableColumn *tableColumn;
	NSCell *cell = [[ZipperCell alloc] init];

	[super windowControllerDidLoadNib: controller];
	[_tableView setDataSource: [self tableViewDataSource]];
	[_tableView reloadData];
	[_tableView setDoubleAction: @selector(tableViewDoubleAction:)];

	// allow for a little bit more space between the columns
	size = [_tableView intercellSpacing];
	size.width += 5.0;
	[_tableView setIntercellSpacing:size];
		
	// right-align the size column
	tableColumn = [_tableView tableColumnWithIdentifier:COL_ID_SIZE];
	[[tableColumn dataCell] setAlignment:NSRightTextAlignment];
	// set the ZipperCell for the name column
	tableColumn = [_tableView tableColumnWithIdentifier:COL_ID_NAME];
	[tableColumn setDataCell:cell];
	[cell release];	
}

- (BOOL)readFromFile:(NSString *)fileName ofType:(NSString *)docType
{
	return [self openArchiveWithPath:fileName];
}

//-----------------------------------------------------------------------------
// Opening archive files
//-----------------------------------------------------------------------------
- (BOOL)openArchiveWithPath:(NSString *)path
{
	Class archiveClass = nil;

	archiveClass = [self archiveClassForFile:path];
	NSAssert1(archiveClass != nil, 
		@"No archive class registered for '%@'. This should not happen", path);	
	if ([archiveClass executableDoesExist] == NO)
	{
		// ouch, no executable set (yet)
		NSString *message;
		PreferencesController *prefsController;
	
		message = [NSString stringWithFormat:
			@"Missing unarchiver for file \"%@\". Please provide a value!", path];
		NSRunAlertPanel(@"Error in Preferences", message, nil, nil, nil);
				
		// bring up the prefs panel
		prefsController = [[PreferencesController alloc] init];
		[prefsController showPreferencesPanel];
		[prefsController release];
		
		// invoke recursively as the unarchiver should have been set in prefs by now
		if ([archiveClass executableDoesExist])
		{
			return [self openArchiveWithPath:path];
		}
		else
		{
			// no archiver executable set via prefs, give up
			return NO;
		} 
	}
	
	if ([archiveClass hasRatio])
	{
		[self addRatioColumn];
	}
	else
	{
		[self removeRatioColumn];
	}
		
	[self setArchive:[archiveClass newWithPath:path]];
	[_archive sortByFilename];
	[_tableView reloadData];

	return YES;
}

- (Class)archiveClassForFile:(NSString *)path
{
	Class archiveClass;
	
	archiveClass = [self archiveClassByFileContents:path];
	if (archiveClass == nil)
	{
		archiveClass = [self archiveClassByFileExtension:path];
	}
	return archiveClass;
}

- (Class)archiveClassByFileExtension:(NSString *)path
{
	NSString *extension, *secondExtension;
	Class archiveClass = nil;

	extension = [[path pathExtension] lowercaseString];
	secondExtension = [[[path stringByDeletingPathExtension] pathExtension] lowercaseString];

	if ([extension isEqual:@""] == NO)
	{
		NSString *fullExtension;
		
		if ([secondExtension isEqual:@""]) 
		{
			// extension is .gz, .bz etc.
			fullExtension = extension;
		}
		else 
		{
			// extension is .tar.gz etc.
			fullExtension = [secondExtension stringByAppendingPathExtension:extension];
		}

		archiveClass = [Archive classForFileExtension:fullExtension];
		if (archiveClass == nil)
		{
			NSLog(@"No archive class registered for '%@'.", fullExtension);
			
			// try only the last extension
			archiveClass = [Archive classForFileExtension:extension];
		}
	}

	return archiveClass;	
}

/*"
 * Peek inside <code>path</code> to determine file type. This is necessary as some file extensions
 * are ambiguous, e.g. .rar files can either be Java resource archives or rar-packaged files 
 */
- (Class)archiveClassByFileContents:(NSString *)path
{
	NSFileHandle *fileHandle;
	NSData *data, *headerData;
	NSEnumerator *archiverEnum;
	Class archiverClass;
	
	fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
	data = [fileHandle readDataOfLength:4];
	
	archiverEnum = [[Archive allArchivers] objectEnumerator];
	while ((archiverClass = [archiverEnum nextObject]) != nil)
	{
		headerData = [archiverClass magicBytes];
		if ((headerData != nil) && [headerData isEqualToData:data])
		{
			return archiverClass;
		}
	}
		
	return nil;
}

//-----------------------------------------------------------------------------
// validating the UI
//-----------------------------------------------------------------------------
- (BOOL)validateMenuItem:(NSMenuItem *)anItem
{
	SEL	action = [anItem action];
	
	if (sel_isEqual(action, @selector(openFile:)) ||	sel_isEqual(action, @selector(showPreferences:))) 
	{
		return YES;
	}
	
	// enable the extract menu item only if we have something to extract
	if (_archive == nil)
	{
		return NO;
	}
	// do not enable the 'extract flat' menu item if the extractor does not support it
	if (([anItem tag] == 2) && ([[_archive class] canExtractWithoutFullPath] == NO))
	{
		return NO;
	}
	return YES;
}

//------------------------------------------------------------------------------
// action methods
//------------------------------------------------------------------------------
- (void)extract:(id)sender
{
	[self extractIncludingPathInfo:YES];
}

- (void)extractFlat:(id)sender
{
	[self extractIncludingPathInfo:NO];
}

- (void)extractIncludingPathInfo:(BOOL)includePathInfo
{
  NSOpenPanel *openPanel;
  int rc;

  if (_archive == nil)
    {
      return;
    }

  openPanel = [NSOpenPanel openPanel];
//[openPanel setDelegate:self];
  [openPanel setTitle:@"Extract to"];
  [openPanel setCanChooseFiles:NO];
  [openPanel setCanChooseDirectories:YES];
	
  rc = [openPanel runModalForDirectory:[Preferences lastExtractDirectory] file:nil types:nil];
  if (rc == NSOKButton)
    {
      NSString *message;
      int result;

      NSString *path = [openPanel directory];

      // make sure the destination path exists
      if ([self createUnarchiveDestinationIfNecessary:path] == NO)
	{
 	  return;
	}

      if ([_tableView selectedRow] == -1)
	{
	  // no rows selected ... extract the whole archive
	  result = [_archive expandFiles:nil withPathInfo:includePathInfo toPath:path];
	}
      else
	{
	  NSNumber *rowIndex;

	  // retrieve selected rows && extract them
	  NSMutableArray *extractFiles = [NSMutableArray array];
	  NSEnumerator *rows = [_tableView selectedRowEnumerator];
	  while ((rowIndex = [rows nextObject]) != nil)
	    {
	      [extractFiles addObject:[_archive elementAtIndex:[rowIndex intValue]]]; 
	    }
	  result = [_archive expandFiles:extractFiles withPathInfo:includePathInfo toPath:path];
	}
		
      // save the selected directory for later
      [Preferences setLastExtractDirectory:path];

      if (!result)
	{
          message = [NSString stringWithFormat:@"Successfully expanded to %@", path];
	}
      else
	{
          message = [NSString stringWithFormat:@"A problem occurred expanding archive to %@", path];
	}
      NSRunAlertPanel(@"Expand", message, nil, nil, nil);
    }
}

- (void)selectAll:(id)sender
{
	[_tableView selectAll: self];
}

- (void)deselectAll:(id)sender
{
	[_tableView deselectAll: self];
}

- (void)tableViewDoubleAction:(id)sender
{
	NSEnumerator *enumerator;
	NSMutableArray *filesToExtract;
	NSNumber *row;
	NSString *tempDir;
	FileInfo *info;
	
  	if ([_tableView clickedRow] == -1)
    	{
      		return;
    	}
	// collect all files to extract
	filesToExtract = [NSMutableArray array];
	enumerator = [_tableView selectedRowEnumerator];
	while ((row = [enumerator nextObject]) != nil)
	{
		[filesToExtract addObject:[_archive elementAtIndex:[row intValue]]];
	}
	
	tempDir = [[NSFileManager defaultManager] createTemporaryDirectory];
	[_archive expandFiles:filesToExtract withPathInfo:YES toPath:tempDir];
	// NSWorkspace hopefully knows how to handle the file
	enumerator = [filesToExtract objectEnumerator];
	while ((info = [enumerator nextObject]) != nil)
	{
		NSString *tempFile;
		
		tempFile = [NSString pathWithComponents:[NSArray arrayWithObjects:tempDir, 
			[info fullPath], nil]];
		[self openFile:tempFile withDefaultApp:[Preferences defaultOpenApp]];
	}
}

//- (BOOL)panel:(id)sender isValidFilename:(NSString *)filename
//{
//	NSLog(@"panel:isValidFilename: %@", filename);
//	return YES;
//}
//
//- (NSString *)panel:(id)sender userEnteredFilename:(NSString *)filename confirmed:(BOOL)okFlag
//{
//	NSLog(@"userEnteredFilename: %@", filename);
//	return filename;
//}

//------------------------------------------------------------------------------
// private API
//------------------------------------------------------------------------------
- (void)addRatioColumn
{
	NSTableColumn *ratioColumn;
	int colIndex;
		
	// do it only if the tableView was already loaded
	if (_tableView != nil)
	{	
		ratioColumn = [_tableView tableColumnWithIdentifier:COL_ID_RATIO];
		if (ratioColumn == nil)
		{
			ratioColumn = [[(NSTableColumn *)[NSTableColumn alloc] initWithIdentifier:COL_ID_RATIO] autorelease];
			[[ratioColumn headerCell] setStringValue:@"Ratio"];
			[ratioColumn setWidth:50.0];
			[[ratioColumn dataCell] setAlignment:NSRightTextAlignment];
			[_tableView addTableColumn:ratioColumn];
		}
		
		// here we have a ratio column for sure
		colIndex = [_tableView columnWithIdentifier:COL_ID_RATIO];
		[_tableView moveColumn:colIndex toColumn:3];

		[_tableView reloadData];
	}
}

- (void)removeRatioColumn;
{	
	if (_tableView != nil)
	{		
		NSTableColumn *ratioCol;

		ratioCol = [_tableView tableColumnWithIdentifier:COL_ID_RATIO];
		if (ratioCol != nil)
		{
			[_tableView removeTableColumn:ratioCol];
		}
	}
}

/**
 * Returns the DataSource for our table view
 */
- (TableViewDataSource *)tableViewDataSource
{
	if (_tableViewDataSource == nil)
	{
		_tableViewDataSource = [[TableViewDataSource alloc] init];
		[_tableViewDataSource setArchive:_archive];
	}
	return _tableViewDataSource;
}

- (void)setArchive:(Archive *)archive
{
  [_archive release];
  _archive = archive;
  [_archive retain];

  // make sure the data source knows the archive as well
  [_tableViewDataSource setArchive:archive];
}

- (void)openFile:(NSString *)file withDefaultApp:(NSString *)defaultApp;
{
	int rc;
	
	// this sux: if the file does not have an extension, NSWorkspace does not know how to 
	// handle it. Handling of files should be based on file's contents instead of its 
	// extension, like the unix command 'file' does.
	rc = [[NSWorkspace sharedWorkspace] openFile:file];
	if (rc == NO) {
		// NSWorkspace could not open the file, try again with the default app we've been given
		if (defaultApp != nil) {
			rc = [[NSWorkspace sharedWorkspace] openFile:file withApplication:defaultApp];
		} else {
			NSRunAlertPanel(@"Could not open", @"No default open application set in preferences", 
				nil, nil, nil);
			return;
		}
	}
			
	if (rc == NO) {
		NSRunAlertPanel(@"Could not open", @"Don't know how to open file %@", nil, nil, nil, file);
	}
}

- (BOOL)createUnarchiveDestinationIfNecessary:(NSString *)path
{
	BOOL isDir, dirExists;
	
	dirExists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir];
	
	if (dirExists == NO)
	{
		int rc;
		
		rc = NSRunAlertPanel(@"Nonexisting destination", 
			@"The directory '%@' does not exist, do you want to create it?", @"Yes", @"No", nil,
			path);
		if (rc == NSAlertDefaultReturn)
		{
			[[NSFileManager defaultManager] createDirectoryPathWithParents:path];
		}
		else
		{
			return NO;
		}
	}
		
	return YES;
}

//------------------------------------------------------------------------------
// NSTableView delegate methods
//------------------------------------------------------------------------------
- (void)tableView:(NSTableView *)tableView didClickTableColumn:(NSTableColumn *)tableColumn
{
  NSString *identifier = [tableColumn identifier];
  NSImage *image;

  if ([identifier isEqual:COL_ID_NAME])
    [_archive sortByFilename];
  else if ([identifier isEqual:COL_ID_DATE])
    [_archive sortByDate];
  else if ([identifier isEqual:COL_ID_SIZE])
    [_archive sortBySize];
  else if ([identifier isEqual:COL_ID_PATH])
    [_archive sortByPath];
  else if ([identifier isEqual:COL_ID_RATIO])
    [_archive sortByRatio];
  else
    [NSException raise:X_INVALID_COL_ID format:@"invalid column identifier '%@'", identifier];
  
  // reflect the current sort ordering in tableColumn's indicator image
  image = nil;
  if ([_archive sortOrder] == NSOrderedAscending)
    {
      // TODO gnustep-gui does not have an image  preregistered under that name
      image = [NSImage imageNamed:@"NSAscendingSortIndicator"];
    }
  else
    {
      // TODO gnustep-gui does not have an image  preregistered under that name
      image = [NSImage imageNamed:@"NSDescendingSortIndicator"];
    }
  // TODO this isn't implemented in gnustep-gui
  [tableView setIndicatorImage:image inTableColumn:tableColumn];
  
  [tableView reloadData];
}

@end