summaryrefslogtreecommitdiff
path: root/src/linux/PreviewRenderer.m
blob: 5333d6544ace718ba0e36723e51e1cec52d59735 (plain)
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
/*
 * Copyright 2011  Alex Merry <dev@randomguy3.me.uk>
 *
 * This program 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "PreviewRenderer.h"
#import "CairoRenderContext.h"

@implementation PreviewRenderer

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

- (id) initWithPreambles:(Preambles*)p {
    self = [super init];

    if (self) {
        document = nil;
        preambles = [p retain];
        pdfDocument = NULL;
        pdfPage = NULL;
    }

    return self;
}

- (BOOL) update {
    NSError *error = nil;
    BOOL result = [self updateWithError:&error];
    if (error) {
        logError (error, @"Could not update preview");
        if ([error code] == TZ_ERR_TOOL_FAILED) {
            NSLog (@"Output: %@", [[error userInfo] objectForKey:TZToolOutputErrorKey]);
        }
    }
    return result;
}

- (BOOL) updateWithError:(NSError**)error {
    if (document == nil) {
        if (error) {
            *error = [NSError errorWithMessage:@"No document given" code:TZ_ERR_BADSTATE];
        }
        if (pdfDocument) {
            g_object_unref (pdfDocument);
            pdfDocument = NULL;
        }
        if (pdfPage) {
            g_object_unref (pdfPage);
            pdfPage = NULL;
        }
        return NO;
    }

    NSString *tex = [NSString stringWithFormat:@"%@%@%@",
                        [preambles currentPreamble],
                        [document tikz],
                        [preambles currentPostamble]];

    NSString *tempDir = [[NSFileManager defaultManager] createTempDirectoryWithError:error];
    if (!tempDir) {
        if (error) {
            *error = [NSError errorWithMessage:@"Could not create temporary directory" code:TZ_ERR_IO cause:*error];
        }
        return NO;
    }

    // write tex code to temporary file
    NSString *texFile = [NSString stringWithFormat:@"%@/tikzit.tex", tempDir];
    NSString *pdfFile = [NSString stringWithFormat:@"file://%@/tikzit.pdf", tempDir];
    [tex writeToFile:texFile atomically:YES];

    // run pdflatex in a bash shell
    NSTask *latexTask = [[NSTask alloc] init];
    [latexTask setCurrentDirectoryPath:tempDir];
    [latexTask setLaunchPath:@"/bin/bash"];

    // This assumes the user has $PATH set up to find pdflatex
    // This should be improved to take other path setups into account
    // and to be customisable.
    NSString *latexCmd = [NSString stringWithFormat:
        @"pdflatex -interaction=nonstopmode -halt-on-error '%@'\n",
        texFile];

    NSPipe *pout = [NSPipe pipe];
    NSPipe *pin = [NSPipe pipe];
    [latexTask setStandardOutput:pout];
    [latexTask setStandardInput:pin];

    NSFileHandle *latexIn = [pin fileHandleForWriting];
    NSFileHandle *latexOut = [pout fileHandleForReading];

    [latexTask launch];
    [latexIn writeData:[latexCmd dataUsingEncoding:NSUTF8StringEncoding]];
    [latexIn closeFile];
    [latexTask waitUntilExit];

    NSData *data = [latexOut readDataToEndOfFile];
    NSString *str = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];

    BOOL success = NO;

    if ([latexTask terminationStatus] != 0) {
        if (error) {
            NSMutableDictionary *errorDetail = [NSMutableDictionary dictionaryWithCapacity:2];
            [errorDetail setValue:@"Generating a PDF file with pdflatex failed" forKey:NSLocalizedDescriptionKey];
            [errorDetail setValue:str forKey:TZToolOutputErrorKey];
            *error = [NSError errorWithDomain:TZErrorDomain code:TZ_ERR_TOOL_FAILED userInfo:errorDetail];
        }
    } else {
        // load pdf document
        GError* gerror = NULL;
        pdfDocument = poppler_document_new_from_file([pdfFile UTF8String], NULL, &gerror);
        if (!pdfDocument) {
            if (error) {
                *error = [NSError errorWithMessage:[NSString stringWithFormat:@"Could not load PDF document", pdfFile]
                                              code:TZ_ERR_IO
                                             cause:[NSError errorWithGError:gerror]];
            }
            g_error_free(gerror);
        } else {
            pdfPage = poppler_document_get_page(pdfDocument, 0);
            if(!pdfPage) {
                if (error) {
                    *error = [NSError errorWithMessage:@"Could not open first page of PDF document"
                                                  code:TZ_ERR_OTHER];
                }
                g_object_unref(pdfDocument);
            } else {
                success = YES;
            }
        }
    }

    // remove all temporary files
    [[NSFileManager defaultManager] removeFileAtPath:tempDir handler:NULL];

    return success;
}

- (BOOL) isValid {
    return pdfPage ? YES : NO;
}

- (Preambles*) preambles {
    return preambles;
}

- (TikzDocument*) document {
    return document;
}

- (void) setDocument:(TikzDocument*)doc {
    [doc retain];
    [document release];
    document = doc;
}

- (double) width {
    double w = 0.0;
    if (pdfPage)
        poppler_page_get_size(pdfPage, &w, NULL);
    return w;
}

- (double) height {
    double h = 0.0;
    if (pdfPage)
        poppler_page_get_size(pdfPage, NULL, &h);
    return h;
}

- (void) renderWithContext:(id<RenderContext>)c onSurface:(id<Surface>)surface {
    if (document != nil) {
        CairoRenderContext *context = (CairoRenderContext*)c;

        [context saveState];
        [context applyTransform:[surface transformer]];

        // white-out
        [context paintWithColor:WhiteRColor];

        poppler_page_render (pdfPage, [context cairoContext]);

        [context restoreState];
    }
}

@end

// vim:ft=objc:ts=8:et:sts=4:sw=4