Hide variables inside TFUSBController.m.
[MacTF.git] / DataHandler.m
blob03a7231ea08266e8556769c8e7b8e3257f944d8a
1 // MacTF Copyright 2004 Nathan Oates
3 /* 
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.
9  *
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.
14  *
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.
18  */
20 /* This file was modified by Kalle Olavi Niemitalo on 2007-10-18.  */
23 #import "DataHandler.h"
24 #import "UIElements.h"
26 @implementation DataHandler
28 #pragma mark -
29 #pragma mark Startup and Shutdown
31 - (id) init
33     if (self = [super init])
34     {
35         fileList = [[NSMutableArray alloc] init];
36                 searchList = [[NSMutableArray alloc] init];
37     }
38     return self;
41 - (void) dealloc
43     [fileList release];
44     [searchList release];
45     [super dealloc];
50 #pragma mark -
51 #pragma mark Simple Accessors
53 - (NSMutableArray *) fileList
55     return fileList;
58 - (NSMutableArray *) displayedList
60     if (searchIsActive) return searchList;
61         else return fileList;
64 - (void) setFileList: (NSArray *)newFileList
66     if (fileList != newFileList)
67     {
68         [fileList autorelease];
69         fileList = [[NSMutableArray alloc] initWithArray: newFileList];
70     }
73 - (void) setSearchList: (NSArray *)newSearchList
75     if (searchList != newSearchList)
76     {
77         [searchList autorelease];
78         searchList = [[NSMutableArray alloc] initWithArray: newSearchList];
79     }
82 -(void)awakeFromNib
84         searchIsActive = NO;
89 -(id)tableView:(NSTableView *)aTableView
90 objectValueForTableColumn:(NSTableColumn *)aTableColumn
91            row:(int)rowIndex
93     id theRecord, theValue;
94         if (searchIsActive)     theRecord = [searchList objectAtIndex:rowIndex];
95     else theRecord = [fileList objectAtIndex:rowIndex];
96     theValue = [theRecord objectForKey:[aTableColumn identifier]];
97     return theValue;
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:@""]) {
114                 searchIsActive = NO;
115                 [self reloadTable];
116         } else {
117                 NSArray *searchTerms = [searchString componentsSeparatedByString:@" "];
118                 NSEnumerator *enumerator = [searchTerms objectEnumerator];
119                 id anObject;
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];
125                                 if (firstToken) 
126                                         results = [fileList filteredArrayUsingPredicate:pred];
127                                 else
128                                         results = [results filteredArrayUsingPredicate:pred];
129                                 firstToken = NO;
130                         }
131                 }
132                 [self setSearchList:results];
133                 searchIsActive = YES; 
134                 [self reloadTable];
135         }
139 // Drag n Drop methods
140 /*- (BOOL)tableView:(NSTableView *)aTableView writeRows:(NSArray*)rows toPasteboard:(NSPasteboard*)pboard {
141      id list;
142         if (searchIsActive) 
143                 list = searchList;
144         else
145                 list = seqs;
146         NSMutableArray *tempArray = [NSMutableArray array];
147     movedRows = [[NSMutableArray alloc] init];
148     NSNumber *index;
149     id tempObject;
150     NSEnumerator *enumerator = [rows objectEnumerator];
151     while ( (index = [enumerator nextObject]) ) {
152         tempObject = [list objectAtIndex:[index intValue]];
153         [tempArray addObject:tempObject];
154     }
155     movedRows = tempArray;
156     NSData *data = [NSArchiver archivedDataWithRootObject: tempArray];
157     [pboard declareTypes: [NSArray arrayWithObject: @"NSGeneralPboardType"] owner: nil];
158     [pboard setData: data forType: @"NSGeneralPboardType"];
159     return YES;
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
167     {
168                 NSData *carriedData = [pboard dataForType:desiredType];
169                 if (nil == carriedData)
170                 {
171                         //the operation failed for some reason
172                         NSRunAlertPanel(@"Paste Error", @"Sorry, but the paste operation failed", nil, nil, nil);
173                         return NO;
174                 } else {
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];
179                                 id currentSelected;
180                                 while (currentSelected = [selected nextObject]) {
181                                         NSLog(@"Upload:%@ to %@", currentSelected, [NSString stringWithString:[UIEl currentPath]]);
182                                         [UIEl uploadPath:currentSelected toPath:[NSString stringWithString:[UIEl currentPath]]];
183                                 }
184                         } else {
185                                 //this can't happen
186                                 NSAssert(NO, @"This can't happen");
187                                 return NO;
188                         }
189                         return YES;
190                 }
191     } else if (aTableView == [info draggingSource]) { // From self
192         return YES;        
193     }
194     // From other documents
195         return YES;    
198     - (NSDragOperation) tableView: (NSTableView *) view
199 validateDrop: (id <NSDraggingInfo>) info
200 proposedRow: (int) row
201 proposedDropOperation: (NSTableViewDropOperation) operation
202     {
203         
204         if (nil == [info draggingSource]) // From other application
205     {
206                 [view setDropRow: row dropOperation: NSTableViewDropAbove];
207         return NSDragOperationCopy;
208     }
209     else if (tableView == [info draggingSource]) // From self
210     {
211          return NSDragOperationNone;
212     }
213         return NSDragOperationNone;
216 // Delegate methods for tableview 
218 - (NSMutableDictionary*) getTFFileFromSwappedHexData:(NSData*) input {
219         
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?
229         
230         unsigned char c;
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"];
236         [hrHex getBytes:&c];
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]);
253         return tfFile;
256 - (NSDictionary*) extractAttributes:(NSDictionary*)fattrs {
257         NSMutableDictionary* tfFile = [[NSMutableDictionary alloc] init];
258         //dates
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];
263         int MJDdate;
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"];
270         
271         //types
272         NSString* type = [fattrs fileType];
273         if ([type isEqualToString:@"NSFileTypeDirectory"]) 
274                 [tfFile setObject:[NSNumber numberWithInt:1] forKey:@"type"];
275         else
276                 [tfFile setObject:[NSNumber numberWithInt:2] forKey:@"type"];
277         
278         //sizes
279         long long size = [fattrs fileSize];
280         [tfFile setObject:[NSNumber numberWithLong:size/0xFFFFFFFF] forKey:@"sizeMSB"];
281         [tfFile setObject:[NSNumber numberWithLong:size%0xFFFFFFFF] forKey:@"sizeLSB"];
282         return tfFile;
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];
306         return build;
309 - (void) convertRawDataToUseful:(NSMutableDictionary*) input {
310         
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"];
319         } else {
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"];
326                 
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"];
337         }
339         //turn size fields into a proper number
340         double size;
341         double big =  pow( 256., 4. );
342         double lsb = [[input objectForKey:@"sizeLSB"] doubleValue];
343         double msb = [[input objectForKey:@"sizeMSB"] doubleValue];
344         if (lsb < 0) 
345                 lsb = lsb + pow( 256., 4. ); //rollover
346         if (msb < 0) 
347                 msb = msb + pow( 256., 4. ); //rollover
348         size = msb * big + lsb;
349         [input setObject:[NSNumber numberWithDouble:size] forKey:@"fileSize"];
350         
351         NSString* ret = nil;
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];
365         
366         int modelOffset = 0;
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]);
403         return extracts;
408 @end