File: mainPng.cpp

package info (click to toggle)
blahtexml 1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,092 kB
  • sloc: cpp: 10,929; xml: 402; python: 302; ansic: 282; makefile: 99
file content (210 lines) | stat: -rw-r--r-- 7,003 bytes parent folder | download
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
/*
blahtex: a TeX to MathML converter designed with MediaWiki in mind
blahtexml: an extension of blahtex with XML processing in mind
http://gva.noekeon.org/blahtexml

Copyright (c) 2006, David Harvey
Copyright (c) 2010, Gilles Van Assche
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the names of the authors nor the names of their affiliation may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "BlahtexCore/Misc.h"
#include "UnicodeConverter.h"
#include "md5Wrapper.h"
#include "mainPng.h"
#include <cerrno>
#include <sys/stat.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>

#include <unistd.h>

using namespace std;
using namespace blahtex;


// From main.cpp:
extern UnicodeConverter gUnicodeConverter;


// TemporaryFile manages a temporary file; it deletes the named file when
// the object goes out of scope.
class TemporaryFile
{
    string mFilename;
    
    // This flag might get set to false if we are in some kind of
    // debugging mode and want to keep temp files.
    bool mShouldDelete;

public:
    TemporaryFile(
        const string& filename,
        bool shouldDelete = true
    ) :
        mFilename(filename),
        mShouldDelete(shouldDelete)
    { }

    ~TemporaryFile()
    {
        if (mShouldDelete)
            unlink(mFilename.c_str());
    }
};


// Tests whether a file exists
bool FileExists(const string& filename)
{
    struct stat temp;
    return (stat(filename.c_str(), &temp) == 0);
}


// Attempts to run given command from the given directory.
// Returns true if the system() call was successful, otherwise false.
// Can throw a "CannotChangeDirectory" exception if problems occur.
bool Execute(
    const string& command,
    const string& directory = "./"
)
{
    char buffer[5000];

    bool NeedToChange = (directory != "" && directory != "./");

    if (NeedToChange)
    {
        if (getcwd(buffer, 5000) == NULL)
            throw blahtex::Exception(L"CannotChangeDirectory");

        if (chdir(directory.c_str()) != 0)
            throw blahtex::Exception(L"CannotChangeDirectory");
    }
    
    bool result = (system(command.c_str()) == 0);

    if (NeedToChange)
    {
        if (chdir(buffer) != 0)
            throw blahtex::Exception(L"CannotChangeDirectory");
    }

    return result;
}


PngInfo MakePngFile(
    const wstring& purifiedTex,
    const string& pngFilename,
    const PngParams& params
)
{
    PngInfo info;
    
    string purifiedTexUtf8 = gUnicodeConverter.ConvertOut(purifiedTex);
    
    // This md5 is used for the temp filenames.
    string md5 = ComputeMd5(purifiedTexUtf8);

    string pngActualFilename =
        pngFilename.empty() ? (md5 + ".png") : pngFilename;

    // Send output to tex file.
    {
        ofstream texFile(
            (params.tempDirectory + md5 + ".tex").c_str(),
            ios::out | ios::binary
        );
        if (!texFile)
            throw blahtex::Exception(
                L"CannotCreateTexFile"
            );
        texFile << purifiedTexUtf8;
        if (!texFile)
            throw blahtex::Exception(
                L"CannotWriteTexFile"
            );
    }

    // These are temporary files we want deleted when we're done.
    TemporaryFile  texTemp(params.tempDirectory + md5 + ".tex",  params.deleteTempFiles);
    TemporaryFile  auxTemp(params.tempDirectory + md5 + ".aux",  params.deleteTempFiles);
    TemporaryFile  logTemp(params.tempDirectory + md5 + ".log",  params.deleteTempFiles);
    TemporaryFile  dviTemp(params.tempDirectory + md5 + ".dvi",  params.deleteTempFiles);
    TemporaryFile dataTemp(params.tempDirectory + md5 + ".data", params.deleteTempFiles);


    if (!Execute(
            params.shellLatex + " " + md5 + ".tex >/dev/null 2>/dev/null",
            params.tempDirectory
        )
        ||
        !FileExists(params.tempDirectory + md5 + ".dvi")
    )
        throw blahtex::Exception(L"CannotRunLatex");


    if (!Execute(
            params.shellDvipng + " " + md5 + ".dvi " +
                "--picky --bg Transparent --gamma 1.3 -D 120 -q -T tight " +
                "--height --depth " +
                "-o \"" + pngActualFilename +
                "\" > " + md5 + ".data 2>/dev/null", 
            params.tempDirectory
        )
        ||
        !FileExists(params.tempDirectory + pngActualFilename)
    )
        throw blahtex::Exception(L"CannotRunDvipng");
        
    if (rename(
        (params.tempDirectory + pngActualFilename).c_str(),
        (params.pngDirectory + pngActualFilename).c_str()
    ))
        throw blahtex::Exception(L"CannotWritePngDirectory");


    // Read the height and depth of the image from dvipng's output.
    {
        ifstream dataFile(
            (params.tempDirectory + md5 + ".data").c_str(),
            ios::in | ios::binary
        );
        
        if (dataFile)
        {
            string line, temp;
            while (getline(dataFile, line))
            {
                string::size_type heightPos = line.find("height=");
                string::size_type depthPos = line.find("depth=");
                if (heightPos != string::npos && depthPos != string::npos)
                {
                    info.mDimensionsValid = true;
                    temp = line.substr(heightPos + 7, 1000);
                    istringstream(temp) >> info.mHeight;
                    string temp = line.substr(depthPos + 6, 1000);
                    istringstream(temp) >> info.mDepth;
                }
            }
        }
    }
    info.fullFileName = params.pngDirectory + pngActualFilename;
    info.mMd5 = md5;
    return info;
}

// end of file @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@