/
PKQuickLookItem.m
103 lines (84 loc) · 2.67 KB
/
PKQuickLookItem.m
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
//
// Created by Phillip Kessels on 10.06.13.
// Copyright (c) 2013 phikes mobile&desktop. All rights reserved.
//
// To change the template use AppCode | Preferences | File Templates.
//
#import "PKQuickLookItem.h"
#import "PKQuickLookHelper.h"
@implementation PKQuickLookItem {
}
- (id)initWithData:(NSData *)data fileExtension:(NSString*)fileExtension
{
self = [super init];
if(self)
{
_data = data;
_extension = [@"." stringByAppendingString: fileExtension];
_helper = [PKQuickLookHelper sharedHelper];
_busy = NO;
}
return self;
}
#pragma mark QLPreviewItem
- (NSString *)previewItemTitle
{
return self.title;
}
- (NSURL *)previewItemURL
{
NSURL* ret = nil;
if(!_busy)
{
if(_tempFileURL)
{
ret = _tempFileURL;
}
else
{
[[_helper queue] addOperationWithBlock:^{
_busy = YES;
[self createTempFile];
_busy = NO;
[[QLPreviewPanel sharedPreviewPanel] refreshCurrentPreviewItem];
}];
}
}
return ret;
}
- (void)createTempFile
{
NSString* template = [NSTemporaryDirectory() stringByAppendingString:[[PKQuickLookHelper sharedHelper] template]];
template = [template stringByAppendingString:@"XXXXXX"];
const char* templateCString = [template fileSystemRepresentation];
char *tempFileNameCString = (char*) malloc(strlen(templateCString) + 1);
strcpy(tempFileNameCString, templateCString);
PKLog(@"Creating temporary file.");
_fileDescriptor = mkstemp(tempFileNameCString);
if(_fileDescriptor == -1)
{
PKLog(@"Could not create temporary file. Aborting.");
return;
}
NSString* file = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:tempFileNameCString
length:strlen(tempFileNameCString)];
PKLog(@"Created temporary file at %@", file);
NSFileHandle* fileHandle = [[NSFileHandle alloc] initWithFileDescriptor:_fileDescriptor];
NSError* err;
[[NSFileManager defaultManager] moveItemAtPath:file
toPath:[file stringByAppendingString:_extension] error:&err];
if(err)
{
PKLog(@"Unable to process temporary file. Aborting.");
}
file = [file stringByAppendingString:_extension];
PKLog(@"Renamed file to %@", file);
//write the file
PKLog(@"Writing data to file: %@", file);
[fileHandle seekToEndOfFile];
[fileHandle writeData:_data];
[fileHandle closeFile];
free(tempFileNameCString);
_tempFileURL = [NSURL fileURLWithPath:file];
}
@end