1 // MacTF Copyright 2004 Nathan Oates
5 * This source code is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Public License as published
7 * by the Free Software Foundation; either version 2 of the License,
8 * or (at your option) any later version.
10 * This source code is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * Please refer to the GNU Public License for more details.
15 * You should have received a copy of the GNU Public License along with
16 * this source code; if not, write to:
17 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 /* This file was modified by Kalle Olavi Niemitalo on 2007-10-18. */
23 #import "DataHandler.h"
24 #import "UIElements.h"
26 @implementation DataHandler
29 #pragma mark Startup and Shutdown
33 if (self = [super init])
35 fileList = [[NSMutableArray alloc] init];
36 searchList = [[NSMutableArray alloc] init];
51 #pragma mark Simple Accessors
53 - (NSMutableArray *) fileList
58 - (NSMutableArray *) displayedList
60 if (searchIsActive) return searchList;
64 - (void) setFileList: (NSArray *)newFileList
66 if (fileList != newFileList)
68 [fileList autorelease];
69 fileList = [[NSMutableArray alloc] initWithArray: newFileList];
73 - (void) setSearchList: (NSArray *)newSearchList
75 if (searchList != newSearchList)
77 [searchList autorelease];
78 searchList = [[NSMutableArray alloc] initWithArray: newSearchList];
89 -(id)tableView:(NSTableView *)aTableView
90 objectValueForTableColumn:(NSTableColumn *)aTableColumn
93 id theRecord, theValue;
94 if (searchIsActive) theRecord = [searchList objectAtIndex:rowIndex];
95 else theRecord = [fileList objectAtIndex:rowIndex];
96 theValue = [theRecord objectForKey:[aTableColumn identifier]];
100 // just returns the number of items we have.
101 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
103 if (searchIsActive) return [searchList count];
104 else return [fileList count];
107 - (void) reloadTable {
108 [tableView reloadData];
111 - (IBAction) search:(id)sender {
112 NSString *searchString = [sender stringValue];
113 if ([searchString isEqualToString:@""]) {
117 NSArray *searchTerms = [searchString componentsSeparatedByString:@" "];
118 NSEnumerator *enumerator = [searchTerms objectEnumerator];
120 BOOL firstToken = YES;
121 NSArray *results = [[NSArray alloc] init];
122 while (anObject = [enumerator nextObject]) {
123 if (![anObject isEqualTo:@""]) {
124 NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name contains[cd] %@)", anObject];
126 results = [fileList filteredArrayUsingPredicate:pred];
128 results = [results filteredArrayUsingPredicate:pred];
132 [self setSearchList:results];
133 searchIsActive = YES;
139 // Drag n Drop methods
140 /*- (BOOL)tableView:(NSTableView *)aTableView writeRows:(NSArray*)rows toPasteboard:(NSPasteboard*)pboard {
146 NSMutableArray *tempArray = [NSMutableArray array];
147 movedRows = [[NSMutableArray alloc] init];
150 NSEnumerator *enumerator = [rows objectEnumerator];
151 while ( (index = [enumerator nextObject]) ) {
152 tempObject = [list objectAtIndex:[index intValue]];
153 [tempArray addObject:tempObject];
155 movedRows = tempArray;
156 NSData *data = [NSArchiver archivedDataWithRootObject: tempArray];
157 [pboard declareTypes: [NSArray arrayWithObject: @"NSGeneralPboardType"] owner: nil];
158 [pboard setData: data forType: @"NSGeneralPboardType"];
162 - (BOOL)tableView:(NSTableView*)aTableView acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)operation {
163 NSPasteboard *pboard = [info draggingPasteboard];
164 NSArray *types = [NSArray arrayWithObjects:@"NSFilenamesPboardType", nil];
165 NSString *desiredType = [pboard availableTypeFromArray:types];
166 if (nil == [info draggingSource]) // From other application
168 NSData *carriedData = [pboard dataForType:desiredType];
169 if (nil == carriedData)
171 //the operation failed for some reason
172 NSRunAlertPanel(@"Paste Error", @"Sorry, but the paste operation failed", nil, nil, nil);
175 if ([desiredType isEqualToString:NSFilenamesPboardType]) {
176 //we have a list of file names in an NSData object
177 NSArray *fileArray = [pboard propertyListForType:@"NSFilenamesPboardType"]; //be caseful since this method returns id. We just happen to know that it will be an array.
178 NSEnumerator* selected = [fileArray objectEnumerator];
180 while (currentSelected = [selected nextObject]) {
181 NSLog(@"Upload:%@ to %@", currentSelected, [NSString stringWithString:[UIEl currentPath]]);
182 [UIEl uploadPath:currentSelected toPath:[NSString stringWithString:[UIEl currentPath]]];
186 NSAssert(NO, @"This can't happen");
191 } else if (aTableView == [info draggingSource]) { // From self
194 // From other documents
198 - (NSDragOperation) tableView: (NSTableView *) view
199 validateDrop: (id <NSDraggingInfo>) info
200 proposedRow: (int) row
201 proposedDropOperation: (NSTableViewDropOperation) operation
204 if (nil == [info draggingSource]) // From other application
206 [view setDropRow: row dropOperation: NSTableViewDropAbove];
207 return NSDragOperationCopy;
209 else if (tableView == [info draggingSource]) // From self
211 return NSDragOperationNone;
213 return NSDragOperationNone;
216 // Delegate methods for tableview
218 - (NSMutableDictionary*) getTFFileFromSwappedHexData:(NSData*) input {
220 NSData* mjdHex = [input subdataWithRange:(NSRange) {0,2}];
221 NSData* hrHex = [input subdataWithRange:(NSRange) {2,1}];
222 NSData* minHex = [input subdataWithRange:(NSRange) {3,1}];
223 NSData* secHex = [input subdataWithRange:(NSRange) {4,1}];
224 NSData* typeHex = [input subdataWithRange:(NSRange) {5,1}];
225 NSData* sizeMSBHex = [input subdataWithRange:(NSRange) {6,4}];
226 NSData* sizeLSBHex = [input subdataWithRange:(NSRange) {10,4}];
227 NSData* nameHex = [input subdataWithRange:(NSRange) {14,95}];
228 // windows attributes here?
231 UInt16 u16_bigendian;
232 SInt32 s32_bigendian;
233 NSMutableDictionary* tfFile = [[NSMutableDictionary alloc] init];
234 [mjdHex getBytes:&u16_bigendian];
235 [tfFile setObject:[NSNumber numberWithInt:EndianU16_BtoN(u16_bigendian)] forKey:@"rawMJD"];
237 [tfFile setObject:[NSNumber numberWithChar:c] forKey:@"hour"];
238 [minHex getBytes:&c];
239 [tfFile setObject:[NSNumber numberWithChar:c] forKey:@"min"];
240 [secHex getBytes:&c];
241 [tfFile setObject:[NSNumber numberWithChar:c] forKey:@"sec"];
242 [typeHex getBytes:&c];
243 [tfFile setObject:[NSNumber numberWithChar:c] forKey:@"type"];
244 [sizeMSBHex getBytes:&s32_bigendian];
245 [tfFile setObject:[NSNumber numberWithLong:EndianS32_BtoN(s32_bigendian)] forKey:@"sizeMSB"];
246 [sizeLSBHex getBytes:&s32_bigendian];
247 [tfFile setObject:[NSNumber numberWithLong:EndianS32_BtoN(s32_bigendian)] forKey:@"sizeLSB"];
248 NSString* name = [[NSString alloc] initWithData:nameHex encoding:NSISOLatin1StringEncoding];
249 name = [name substringToIndex:[name rangeOfCharacterFromSet:[NSCharacterSet characterSetWithRange:(NSRange){0,1}]].location]; //trim anything past the 0x00
250 name = [name stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithRange:(NSRange){5,1}]]; //remove extraneous 0x05 on some peoples names.
251 [tfFile setObject:name forKey:@"name"];
252 // NSLog([tfFile description]);
256 - (NSDictionary*) extractAttributes:(NSDictionary*)fattrs {
257 NSMutableDictionary* tfFile = [[NSMutableDictionary alloc] init];
259 NSCalendarDate* date = [[NSCalendarDate alloc] initWithTimeInterval:0 sinceDate:[fattrs fileModificationDate]];
260 int min = [date minuteOfHour];
261 int sec = [date secondOfMinute];
262 int hour = [date hourOfDay];
264 NSCalendarDate *mjdref = [[[NSCalendarDate alloc] initWithYear:1858 month:11 day:17 hour:0 minute:0 second:0 timeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]] autorelease];
265 [date years:NULL months:NULL days:&MJDdate hours:NULL minutes:NULL seconds:NULL sinceDate:mjdref];
266 [tfFile setObject:[NSNumber numberWithInt:MJDdate] forKey:@"rawMJD"];
267 [tfFile setObject:[NSNumber numberWithInt:hour] forKey:@"hour"];
268 [tfFile setObject:[NSNumber numberWithInt:min] forKey:@"min"];
269 [tfFile setObject:[NSNumber numberWithInt:sec] forKey:@"sec"];
272 NSString* type = [fattrs fileType];
273 if ([type isEqualToString:@"NSFileTypeDirectory"])
274 [tfFile setObject:[NSNumber numberWithInt:1] forKey:@"type"];
276 [tfFile setObject:[NSNumber numberWithInt:2] forKey:@"type"];
279 long long size = [fattrs fileSize];
280 [tfFile setObject:[NSNumber numberWithLong:size/0xFFFFFFFF] forKey:@"sizeMSB"];
281 [tfFile setObject:[NSNumber numberWithLong:size%0xFFFFFFFF] forKey:@"sizeLSB"];
285 -(NSData*) getDataFromTFFile:(NSDictionary*) infile withName:(NSString*) inputName {
286 UInt16 u16_bigendian = EndianU16_NtoB([[infile objectForKey:@"rawMJD"] shortValue]);
287 NSMutableData* build = [NSMutableData dataWithBytes:&u16_bigendian length:2];
288 char c = [[infile objectForKey:@"hour"]charValue];
289 [build appendData:[NSData dataWithBytes:&c length:1]];
290 c = [[infile objectForKey:@"min"] charValue];
291 [build appendData:[NSData dataWithBytes:&c length:1]];
292 c = [[infile objectForKey:@"sec"] charValue];
293 [build appendData:[NSData dataWithBytes:&c length:1]];
294 c = [[infile objectForKey:@"type"] charValue];
295 [build appendData:[NSData dataWithBytes:&c length:1]];
296 SInt32 s32_bigendian = EndianS32_NtoB([[infile objectForKey:@"sizeMSB"] longValue]);
297 [build appendData:[NSData dataWithBytes:&s32_bigendian length:4]];
298 s32_bigendian = EndianS32_NtoB([[infile objectForKey:@"sizeLSB"] longValue]);
299 [build appendData:[NSData dataWithBytes:&s32_bigendian length:4]];
300 NSData * name = [inputName dataUsingEncoding:NSISOLatin1StringEncoding];
301 [build appendData:name];
302 if ([name length] < 95)
303 [build increaseLengthBy:95-[name length]];
304 // other file stuff (5 bytes) - maybe add this later?
305 [build increaseLengthBy:5];
309 - (void) convertRawDataToUseful:(NSMutableDictionary*) input {
311 //turn MJD and time into a useful object
312 if ([[input objectForKey:@"type"] intValue] == 1) { //folder
313 [input setObject:@"" forKey:@"date"];
314 [input setObject:[NSDate distantPast] forKey:@"sortdate"];
315 [input setObject:[NSImage imageNamed:@"folder.tif"] forKey:@"icon"];
316 if ([[input objectForKey:@"name"] isEqualToString:@".."])
317 [input setObject:@".. (Parent folder)" forKey:@"name"];
318 [input setObject:@"0000" forKey:@"suffix"];
320 if ([[input objectForKey:@"name"] hasSuffix:@".tgd"]) [input setObject:[NSImage imageNamed:@"tgd.tif"] forKey:@"icon"];
321 else if ([[input objectForKey:@"name"] hasSuffix:@".tap"]) [input setObject:[NSImage imageNamed:@"package.tif"] forKey:@"icon"];
322 else if ([[input objectForKey:@"name"] hasSuffix:@".mp3"]) [input setObject:[NSImage imageNamed:@"mp3.tif"] forKey:@"icon"];
323 else if ([[input objectForKey:@"name"] hasSuffix:@".txt"] || [[input objectForKey:@"name"] hasSuffix:@".ini"]) [input setObject:[NSImage imageNamed:@"txt.tif"] forKey:@"icon"];
324 else [input setObject:[NSImage imageNamed:@"file.tif"] forKey:@"icon"];
325 [input setObject:[[input objectForKey:@"name"] pathExtension] forKey:@"suffix"];
327 int daysSinceRef = [[input objectForKey:@"rawMJD"] intValue] - 51910; // ref date is 1/1/2001 51911??
328 float secsSinceRef = (((daysSinceRef * 24 + [[input objectForKey:@"hour"] intValue])* 60 + [[input objectForKey:@"min"] intValue]) * 60);
329 NSCalendarDate* tempDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:secsSinceRef];
330 //now adjust for timezone
331 int offset = [[NSTimeZone defaultTimeZone] secondsFromGMTForDate:tempDate];
332 //NSLog(@"TZ offset:%i td:%@", offset, [tempDate description]);
333 NSCalendarDate* finalDate = [tempDate dateByAddingYears:0 months:0 days:0 hours:0 minutes:0 seconds:-1*offset];
334 //NSLog(@"TZ td:%@", [finalDate description]);
335 [input setObject:finalDate forKey:@"date"];
336 [input setObject:finalDate forKey:@"sortdate"];
339 //turn size fields into a proper number
341 double big = pow( 256., 4. );
342 double lsb = [[input objectForKey:@"sizeLSB"] doubleValue];
343 double msb = [[input objectForKey:@"sizeMSB"] doubleValue];
345 lsb = lsb + pow( 256., 4. ); //rollover
347 msb = msb + pow( 256., 4. ); //rollover
348 size = msb * big + lsb;
349 [input setObject:[NSNumber numberWithDouble:size] forKey:@"fileSize"];
352 if( size == 0. ) ret = NSLocalizedString( @" - ", "no file size" );
353 else if( size > 0. && size < 1024. ) ret = [NSString stringWithFormat:NSLocalizedString( @"%.0f B", "file size measured in bytes" ), size];
354 else if( size >= 1024. && size < pow( 1024., 2. ) ) ret = [NSString stringWithFormat:NSLocalizedString( @"%.1f KB", "file size measured in kilobytes" ), ( size / 1024. )];
355 else if( size >= pow( 1024., 2. ) && size < pow( 1024., 3. ) ) ret = [NSString stringWithFormat:NSLocalizedString( @"%.2f MB", "file size measured in megabytes" ), ( size / pow( 1024., 2. ) )];
356 else if( size >= pow( 1024., 3. ) && size < pow( 1024., 4. ) ) ret = [NSString stringWithFormat:NSLocalizedString( @"%.2f GB", "file size measured in gigabytes" ), ( size / pow( 1024., 3. ) )];
357 else if( size >= pow( 1024., 4. ) ) ret = [NSString stringWithFormat:NSLocalizedString( @"%.4f TB", "file size measured in terabytes" ), ( size / pow( 1024., 4. ) )];
358 else ret = NSLocalizedString( @" ? ", "unknown file size" );
359 [input setObject:ret forKey:@"size"];
362 - (NSDictionary*) extractDataFromRecHeader:(NSString*)file forModel:(NSString*)model {
363 NSMutableDictionary* extracts = [NSMutableDictionary dictionaryWithCapacity:8];
364 NSData* fileData = [NSData dataWithContentsOfFile:file];
367 if ([model isEqualToString:@"TF5800"]) modelOffset = 4;
368 unsigned char c; //1byte
369 UInt16 u16_bigendian;
370 [[fileData subdataWithRange:(NSRange) {8,2}] getBytes:&u16_bigendian];
371 [extracts setObject:[NSNumber numberWithShort:EndianU16_BtoN(u16_bigendian)] forKey:@"duration"];
372 NSString* channel = [[NSString alloc] initWithData:[fileData subdataWithRange:(NSRange) {28,24}] encoding:NSISOLatin1StringEncoding];
373 NSRange r = [channel rangeOfCharacterFromSet:[NSCharacterSet characterSetWithRange:(NSRange){0,1}]]; //trim anything past the 0x00
374 if (r.location != NSNotFound)
375 channel = [channel substringToIndex:r.location];
376 channel = [channel stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithRange:(NSRange){5,1}]]; //remove extraneous 0x05 on some peoples names.
377 [extracts setObject:channel forKey:@"channel"];
378 [[fileData subdataWithRange:(NSRange) {76+modelOffset,2}] getBytes:&u16_bigendian];
379 [extracts setObject:[NSNumber numberWithInt:EndianU16_BtoN(u16_bigendian)] forKey:@"rawMJD"];
380 int daysSinceRef = [[extracts objectForKey:@"rawMJD"] intValue] - 51910; // ref date is 1/1/2001 51911??
381 [[fileData subdataWithRange:(NSRange) {78+modelOffset,1}] getBytes:&c];
382 NSNumber* hour = [NSNumber numberWithChar:c];
383 [[fileData subdataWithRange:(NSRange) {79+modelOffset,1}] getBytes:&c];
384 NSNumber* min = [NSNumber numberWithChar:c];
385 float secsSinceRef = (((daysSinceRef * 24 + [hour intValue])* 60 + [min intValue]) * 60);
386 NSCalendarDate* finalDate = [NSCalendarDate dateWithTimeIntervalSinceReferenceDate:secsSinceRef];
387 [extracts setObject:finalDate forKey:@"startTime"];
388 [[fileData subdataWithRange:(NSRange) {85+modelOffset,1}] getBytes:&c];
389 NSString* name = [[NSString alloc] initWithData:[fileData subdataWithRange:(NSRange) {87+modelOffset,c}] encoding:NSISOLatin1StringEncoding];
390 [extracts setObject:name forKey:@"name"];
391 NSString* desc = [[NSString alloc] initWithData:[fileData subdataWithRange:(NSRange) {87+c+modelOffset,255}] encoding:NSISOLatin1StringEncoding];
392 r = [desc rangeOfCharacterFromSet:[NSCharacterSet characterSetWithRange:(NSRange){0,1}]]; //trim anything past the 0x00
393 if (r.location != NSNotFound)
394 desc = [desc substringToIndex:r.location];
395 desc = [desc stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithRange:(NSRange){5,1}]]; //remove extraneous 0x05 on some peoples names.
396 [extracts setObject:desc forKey:@"description"];
397 [[fileData subdataWithRange:(NSRange) {362+modelOffset,2}] getBytes:&u16_bigendian];
398 NSString* extInfo = [[NSString alloc] initWithData:[fileData subdataWithRange:(NSRange) {369+modelOffset,EndianU16_BtoN(u16_bigendian)}] encoding:NSISOLatin1StringEncoding];
399 [extracts setObject:extInfo forKey:@"extInfo"];
400 //NSData* movieData = [fileData subdataWithRange:(NSRange) {1656,([fileData length]-1656)}];
401 //[movieData writeToFile:@"/Volumes/Tyr/cazlar/testMovie.ts" atomically:YES];
402 //NSLog([extracts description]);