Codebase list adun.app / HEAD UL / ULExportController.m
HEAD

Tree @HEAD (Download .tar.gz)

ULExportController.m @HEADraw · history · blame

  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
/* 
   Project: UL

   Copyright (C) 2007 Michael Johnston & Jordi Villa-Freixa

   Author: Michael Johnston

   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 application 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
   Library General Public License for more details.
 
   You should have received a copy of the GNU General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/
#include "ULExportController.h"
#include <AdunKernel/AdunFileSystemSimulationStorage.h>
#include <MolTalk/MolTalk.h>

id sharedExportController = nil;

/**
Category containing method wrappers around ULFramework functions
*/
@interface ULExportController (PrivateExportWrappers)
- (id) exportDataSetAsCSV: (id) anObject toFile: (NSString*) filename;
- (id) exportDataSourceAsPDB: (id) anObject toFile: (NSString*) filename;
- (id) exportTemplateAsPropertyList: (id) template toFile: (NSString*) fileName;
@end

@implementation ULExportController

+ (id) sharedExportController
{
	if(sharedExportController == nil)
		sharedExportController = [self new];

	return sharedExportController;
}

- (id) init
{
	if(sharedExportController != nil)
		return sharedExportController;

	if(self = [super init])
	{
		if([NSBundle loadNibNamed: @"CreateAttributePanel" owner: self] == NO)
		{
			NSWarnLog(@"Problem loading interface");
			return nil;
		}
	
		attributeDataSet = nil;
		exportPanel = [ULExportPanel exportPanel];
		pasteboard = [ULPasteboard appPasteboard];
		sharedExportController = self;
		knownFormats = [NSDictionary dictionaryWithObjectsAndKeys:
				[NSArray arrayWithObjects: 
					@"pdb",
					@"binary archive",
					nil],
				@"AdDataSource",
				[NSArray arrayWithObjects: 
					@"csv",
					@"binary archive",
					nil],
				@"AdDataSet",
				[NSArray arrayWithObject: @"binary archive"],
				@"AdSimulationData",
				[NSArray arrayWithObjects: 
					@"AdunCore template",
					@"binary archive",
					nil],
				@"ULTemplate", nil];
		[knownFormats retain];		
		displayStrings = [NSDictionary dictionaryWithObjectsAndKeys:
				@"System", @"AdDataSource",
				@"Simulation", @"AdSimulationData",
				@"DataSet", @"AdDataSet",
				@"Template", @"ULTemplate", nil];
		[displayStrings retain];	
		exportMethods = [NSMutableDictionary new];
		[exportMethods setObject: 
			[NSDictionary dictionaryWithObjectsAndKeys:
				NSStringFromSelector(@selector(exportDataSetAsCSV:toFile:)),
				@"csv", nil]	
			forKey: @"AdDataSet"];	
		[exportMethods setObject: 
			[NSDictionary dictionaryWithObjectsAndKeys:
				NSStringFromSelector(@selector(exportDataSourceAsPDB:toFile:)),
				@"pdb", nil]	
			forKey: @"AdDataSource"];	
		[exportMethods setObject: 
			[NSDictionary dictionaryWithObjectsAndKeys:
				NSStringFromSelector(@selector(exportTemplateAsPropertyList:toFile:)),
				@"AdunCore template", nil]	
			forKey: @"ULTemplate"];	

	}

	return self;
}

- (void) dealloc
{
	[knownFormats release];
	[displayStrings release];
	[exportMethods release];
	[super dealloc];
}

- (void) _exportObjectAsBinaryArchive: (id) anObject toFile: (NSString*) filename
{
	BOOL retVal;
	int selectedRow;
	NSError *error;
	NSMutableData *data;
	NSKeyedArchiver* archiver;
	NSString* storagePath, *destinationPath;

	//If its a simulation we also have to export the simulation
	//data directory. This involves copying the directory to the
	//chosen location. 	
	//FIXME: We should define path extensions for the different types 
	//of adun objects.
	
	if([anObject isKindOfClass: [AdSimulationData class]])
	{
		storagePath = [[anObject dataStorage] storagePath];
		destinationPath =  [filename stringByAppendingString: @"_Data"];
		retVal = [[NSFileManager defaultManager]
				copyPath: storagePath
				toPath: destinationPath
				handler: nil];

		if(!retVal)
		{
			//Abort
			NSRunAlertPanel(@"Error",
				@"Unable to extract simulation data - Aborting",
				@"Dismiss", 
				nil,
				nil);

			return;
		}	
	}
	data = [NSMutableData new];
	archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: data];
	[archiver setOutputFormat: NSPropertyListXMLFormat_v1_0];
	[archiver encodeObject: anObject forKey: @"root"];
	[archiver finishEncoding];
	[archiver release];
	
	retVal = [[ULIOManager appIOManager]
			writeObject: data 
			toFile: filename 
			error: &error];

	[data release];
	if(!retVal)
	{
		NSRunAlertPanel(@"Error",
			[[error userInfo] objectForKey:NSLocalizedDescriptionKey],
			@"Dismiss", 
			nil,
			nil);
	}
}

- (void) export: (id) sender
{
	int result, index;
	id exportObject; //the actual unarchived object
	id savePanel;
	NSString* filename, *format, *type, *extension;

	//Get the type of the object to be exported
	
	type = [[pasteboard availableTypes] objectAtIndex: 0];
	[exportPanel setObjectType: [displayStrings objectForKey: type]];
	[exportPanel setChoices: [knownFormats objectForKey: type]];
	result = [exportPanel runModal];
	format = [exportPanel choice];

	if(result == NSOKButton)
	{
		savePanel = [NSSavePanel savePanel];	
		if([[exportPanel choice] isEqual: @"pdb"])
			[savePanel setRequiredFileType: @"pdb"];
			
		[savePanel setTitle: @"Export Data"];
		result = [savePanel runModal];
		filename = [savePanel filename];

		if(result == NSOKButton)
		{
			//Take any extension off filename 
			//This just makes it easier to work with it later
			extension = [filename pathExtension];
			exportObject = [pasteboard objectForType: type];
			[self exportObject: exportObject 
				toFile: filename
				format: format];
		}		
	}			
}

/*
As exportObject:toFile:format: except using ULExportType enum values to define the type
instead of a string.
Raises an NSInvalidArgumentException is type is invalid.
*/
- (void) exportObject: (id) anObject toFile: (NSString*) filename as: (ULExportType) type
{
	NSString* format;
	
	switch((int)type)
	{
		case ULBinaryArchiveExportType:
			format = @"binary archive";
			break;
		case ULPDBExportType:
			format = @"pdb";
			break;
		case ULCSVExportType:
			format = @"csv";
			break;
		case ULAdunCoreTemplateExportType:
			format = @"AdunCore template";
			break;
		default:
			[NSException raise: NSInvalidArgumentException
				format: @"Type id %d unknown - cannot export object", type];
	}
	
	[self exportObject: anObject toFile: filename format: format];
}

- (void) exportObject: (id) anObject toFile: (NSString*) filename format: (NSString*) format 
{
	SEL selector;
	NSString* selectorString;
	
	if([format isEqual: @"binary archive"])
		[self _exportObjectAsBinaryArchive: anObject toFile: filename];
	else
	{
		selectorString = [[exportMethods objectForKey: 
						NSStringFromClass([anObject class])]
					objectForKey: format];
		[self performSelector: NSSelectorFromString(selectorString)
			withObject: anObject
			withObject: filename];		
	}
}

/*
 Returns yes if the objects of class \e className can be exported as \e type.
 The valid values for type are given by the ULExportType enum.
 If \e type is not one of the above then an NSInvalidArgumentException is raised.
 */
- (BOOL) canExportObjectofClass: (NSString*) className  as: (ULExportType) type
{
	BOOL retval = NO;

	//everything can be exported as a binary archive
	if(type == ULBinaryArchiveExportType)
		return YES;

	if(type == ULPDBExportType)
	{
		if([className isEqual: @"AdDataSource"])
			retval = YES;
	}
	else if(type == ULCSVExportType)
	{
		if([className isEqual: @"AdDataSet"])
			retval = YES;
	}
	else
		[NSException raise: NSInvalidArgumentException
			format: @"Invalid export type - (%d)", type];
	
	return retval;
}

/*
 Returns yes if the current object on the pasteboard can be exported as \e type.
 If there is no object, or more than one object, on the pasteboard this method returns NO.
 The valid values for type are given by the ULExportType enum.
 If \e type is not one of the above then an NSInvalidArgumentException is raised.
 If there is no object on the pasteboard this method returns NO.
 */
- (BOOL) canExportCurrentPasteboardObjectAs: (ULExportType) type
{	
	BOOL retval = NO;
	NSString* className;
	NSArray* availableTypes;	
		
	availableTypes = [pasteboard availableTypes];
	if([availableTypes count] == 1)
	{
		className = [availableTypes objectAtIndex: 0];
		retval = [self canExportObjectofClass: className as: type];
	}

	return retval;
}

/*
 Exports the current pasteboard object as \e type. 
 Runs an NSSavePanel to prompt for the file name.
 Raises NSInvalidArgumentException if the current pasteboard object cannot be
 export as type.
 */
- (void) exportCurrentPasteboardObjectAs: (ULExportType) type
{
	int result;
	NSString* className, *filename, *extension;
	NSArray* availableTypes;
	NSSavePanel* savePanel;
	id exportObject;
	
	availableTypes = [pasteboard availableTypes];
	if([availableTypes count] == 1)
	{
		className = [availableTypes objectAtIndex: 0];
		if([self canExportObjectofClass: className as: type])
		{	
			//Run panel to get the filename
			savePanel = [NSSavePanel savePanel];	
			if([[exportPanel choice] isEqual: @"pdb"])
				[savePanel setRequiredFileType: @"pdb"];
			
			[savePanel setTitle: @"Export Data"];
			[savePanel setDirectory: nil];
			result = [savePanel runModal];
			filename = [savePanel filename];
			
			if(result == NSOKButton)
			{
				//Take any extension off filename 
				//This just makes it easier to work with it later
				extension = [filename pathExtension];
				exportObject = [pasteboard objectForType: className];
				[self exportObject: exportObject 
					    toFile: filename
					    as: type];
			}		
		}			
		else
			[NSException raise: NSInvalidArgumentException
				format: @"Cannot export objects of class %@ as type %d", 
					className, type];
	}
}

@end

@implementation ULExportController (PrivateExportWrappers)

- (id) exportDataSetAsCSV: (id) dataSet toFile: (NSString*) filename
{
	int i;
	NSArray* dataMatrices;
	AdDataMatrix* matrix;
	id name, cvsString;

	dataMatrices = [dataSet dataMatrices];
	//Remove any path extension specified so we can add the filenumber.
	filename = [filename stringByDeletingPathExtension];
	for(i=0; i<(int)[dataMatrices count];i++)
	{
		name = [NSString stringWithFormat: @"%@%d.csv", filename, i+1];
		matrix = [dataMatrices objectAtIndex: i];
		cvsString = [matrix stringRepresentation];
		[cvsString writeToFile: name atomically: NO];
	}

	return nil;
}

- (id) exportDataSourceAsPDB: (id) dataSource toFile: (NSString*) filename
{
	id structure;
	MTFileStream* fileStream;

 	structure = ULConvertDataSourceToPDBStructure(dataSource);		
	fileStream = [MTFileStream streamToFile: 
			[NSString stringWithFormat: @"%@", filename]];
	[structure writePDBToStream: fileStream];
	[fileStream close];

	return nil;
}

- (id) exportTemplateAsPropertyList: (id) template toFile: (NSString*) filename
{
	[[template coreRepresentation] writeToFile: filename
		atomically: NO];

	return nil;	
}

@end


@implementation ULExportController (ChimeraAttributeFileCreation)

- (void) _saveAttributeFile: (NSMutableString*) string
{
	int result;
	NSSavePanel* savePanel;
	NSString* filename;
	NSError* error = nil;
	
	savePanel = [NSSavePanel savePanel];	
	[savePanel setTitle: @"Save Attribute File"];
	result = [savePanel runModal];
	filename = [savePanel filename];
	
	if(result == NSOKButton)
	{
	
//Gnustep base pre 0.16	
#if defined GNUSTEP && GS_API_VERSION(0, 011600) 
		[string writeToFile: filename 
			 atomically: NO];
#else
		[string writeToFile: filename 
			 atomically: NO 
			   encoding: NSUTF8StringEncoding 
			      error: &error];
		
		if(error != nil)
			ULRunErrorPanel(error);	  
#endif		
	
	}		
}

- (void) openAttributeWindow: (id) sender
{
	NSArray* matrixNames, *headers;

	//Get rid of old data
	if(attributeDataSet != nil)
		[attributeDataSet release];
		
	[matrixList removeAllItems];
	[attributeColumnList removeAllItems];
	[residueColumnList removeAllItems];
	[atomColumnList removeAllItems];
	
	//Get data
	attributeDataSet = [pasteboard objectForType: @"AdDataSet"];
	[attributeDataSet retain];
	
	//Populate lists
	matrixNames = [[attributeDataSet dataMatrices] valueForKey: @"name"];
	[matrixList addItemsWithTitles: matrixNames];
	
	//Default choose first matrix
	headers = [[[attributeDataSet dataMatrices] objectAtIndex: 0] columnHeaders];
	[residueColumnList addItemsWithTitles: headers];
	[atomColumnList addItemsWithTitles: headers];
	[attributeColumnList addItemsWithTitles: headers];
	
	//A defaults number scheme for the recipient
	[residueColumnList addItemWithTitle: @"Numbered"];
	
	[attributeWindow center];
	[attributeWindow makeKeyAndOrderFront: self];
}

- (void) changedMatrixSelection: (id) sender
{
	NSString* matrixName;
	NSArray* headers;

	[attributeColumnList removeAllItems];
	[residueColumnList removeAllItems];
	[atomColumnList removeAllItems];
	
	matrixName = [matrixList titleOfSelectedItem];
	headers = [[attributeDataSet dataMatrixWithName: matrixName] 
			columnHeaders];
			
	[residueColumnList addItemsWithTitles: headers];
	[atomColumnList addItemsWithTitles: headers];
	[attributeColumnList addItemsWithTitles: headers];
	
	[residueColumnList addItemWithTitle: @"Numbered"];
	
	[attributeWindow display];
}

- (void) createAttributeFile: (id) sender
{
	BOOL valid, useAtoms=NO;
	int i;
	NSRange numRange;
	NSMutableString* string = [NSMutableString new];
	NSString* name, *matrixName, *residueColName, *atomColName, *version;
	NSArray* attributeColumn,  *atomColumn;
	NSEnumerator* attributeEnum;
	AdDataMatrix* matrix;
	id attribute, residueColumn;
	
	matrixName = [matrixList titleOfSelectedItem];
	
#ifdef GNUSTEP
	version = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"ApplicationVersion"],
#else

	version = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"CFBundleVersion"],
#endif
	[string appendFormat: 
		@"#Chimera attribute file created by Adun %@ on %@\n", version, [NSDate date]];

	[string appendFormat: @"#Created using matrix %@ of data set %@\n", 
		matrixName, [attributeDataSet name]];

	name = [nameField stringValue];
	name = [name lowercaseString];
	
	valid = NO;
	while(!valid && ([name length] > 1))
	{
		if([[name substringToIndex:1] isEqual: @"_"])
		{
			name = [name substringFromIndex: 1];
			valid = NO;
		}
		else
			valid = YES;	
		
		numRange = [name rangeOfCharacterFromSet: 
				[NSCharacterSet decimalDigitCharacterSet]];
		if(numRange.location == 0)
		{
			valid = NO;
			name = [name substringFromIndex: 1];
		}
		else
			valid = YES;
	}
	
	[string appendFormat: @"attribute: %@\n", name];
	[string appendFormat: @"match mode: %@\n", [relationshipList titleOfSelectedItem]];
	
	//We need the residue column no matter what.
	residueColName = [residueColumnList titleOfSelectedItem];
	
	//Find the exact recipient
	if([atomButton state])
	{
		useAtoms = YES;
		[string appendString: @"recipient: atoms\n"];
		atomColName = [atomColumnList titleOfSelectedItem];
	}
	else
		[string appendString: @"recipient: residues\n"];
	
	matrix = [attributeDataSet dataMatrixWithName: matrixName];
	attributeColumn = [matrix columnWithHeader: 
				[attributeColumnList titleOfSelectedItem]];
				
	if([residueColName isEqual: @"Numbered"])	
	{		
		residueColumn = [NSMutableArray array];
		for(i=0; i<[attributeColumn count]; i++)
			[residueColumn addObject: [NSNumber numberWithInt: i]];
		
	}	
	else
		residueColumn = [matrix columnWithHeader: residueColName];
	
	if(!useAtoms)
	{
		for(i=0; i<[residueColumn count]; i++)
		{
			[string appendFormat: @"\t:%@\t%@\n", 
				[residueColumn objectAtIndex: i],
				[attributeColumn objectAtIndex: i]];
		}
	}
	else
	{
		atomColumn =  [matrix columnWithHeader: 
			       [atomColumnList titleOfSelectedItem]];

		for(i=0; i<[residueColumn count]; i++)
		{
			[string appendFormat: @"\t:%@@%@\t%@\n", 
			 [residueColumn objectAtIndex: i],
			 [atomColumn objectAtIndex: i],
			 [attributeColumn objectAtIndex: i]];
		}		
	}
	
	[string appendFormat: @"\n"];
	[attributeWindow close];
	[self _saveAttributeFile: string];
	
	[string release];
}

- (BOOL) validateCreateAttribute: (id) sender
{
	if([pasteboard countOfObjectsForType: @"AdDataSet"] == 0)
		return NO;
	
	return YES;		
}

@end