File: ODi_Abi_Data.cpp

package info (click to toggle)
abiword 3.0.7~dfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 64,700 kB
  • sloc: cpp: 477,933; ansic: 16,754; makefile: 5,834; xml: 3,993; yacc: 1,818; lex: 1,104; perl: 812; python: 413; php: 183; sh: 169
file content (336 lines) | stat: -rw-r--r-- 10,547 bytes parent folder | download | duplicates (7)
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
/* AbiSource
 * 
 * Copyright (C) 2005 Daniel d'Andrada T. de Carvalho
 * <daniel.carvalho@indt.org.br>
 * 
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
 * 02110-1301 USA.
 */
 
// Class definition include
#include "ODi_Abi_Data.h"

// AbiWord includes
#include <pd_Document.h>
#include <pt_Types.h>
#include <ie_impGraphic.h>
#include <fg_GraphicRaster.h>
#include "ie_math_convert.h"

// External includes
#include <glib-object.h>
#include <gsf/gsf-input-stdio.h>
#include <gsf/gsf-infile.h>
#include <gsf/gsf-infile-zip.h>


/**
 * Constructor
 */
ODi_Abi_Data::ODi_Abi_Data(PD_Document* pDocument, GsfInfile* pGsfInfile) :
    m_pAbiDocument (pDocument), m_pGsfInfile (pGsfInfile) {
}


/**
 * Adds an data item (<d> tag) in the AbiWord document for the specified image.
 * 
 * Code mainly from Dom Lachowicz and/or Robert Staudinger.
 * 
 * @param rDataId Receives the id that has been given to the added data item.
 * @param ppAtts The attributes of a <draw:image> element.
 */
bool ODi_Abi_Data::addImageDataItem(UT_String& rDataId, const gchar** ppAtts) {
    
    const gchar* pHRef = UT_getAttribute ("xlink:href", ppAtts);
    UT_return_val_if_fail(pHRef,false);

    // If we have a string smaller then this we are in trouble. File corrupted?
    UT_return_val_if_fail((strlen(pHRef) >= 10 /*10 == strlen("Pictures/a")*/), false);

    UT_Error error = UT_OK;
    UT_ByteBuf img_buf;
    GsfInfile* pPictures_dir;
    FG_Graphic* pFG = NULL;
    const UT_ByteBuf* pPictData = NULL;
    UT_uint32 imageID;
    
    // The subdirectory that holds the picture. e.g: "ObjectReplacements" or "Pictures"
    UT_String dirName;
    
    // The file name of the picture. e.g.: "Object 1" or "10000201000000D100000108FF0E3707.png" 
    UT_String fileName;
    
    const std::string id = m_href_to_id[pHRef];
    if (!id.empty()) {
        // This image was already added.
        // Use the existing data item id.
        rDataId = id;
        return true;
    }
    
    
    // Get a new, unique, ID.
    imageID = m_pAbiDocument->getUID(UT_UniqueId::Image);
    UT_String_sprintf(rDataId, "%d", imageID);
    
    // Add this id to the list
    UT_DebugOnly<href_id_map_t::iterator> iter = m_href_to_id
		.insert(m_href_to_id.begin(),
			href_id_map_t::value_type(pHRef, 
						  rDataId.c_str()));
    UT_ASSERT((href_id_map_t::iterator)iter != m_href_to_id.end());

    _splitDirectoryAndFileName(pHRef, dirName, fileName);

    pPictures_dir =
        GSF_INFILE(gsf_infile_child_by_name(m_pGsfInfile, dirName.c_str()));

    UT_return_val_if_fail(pPictures_dir, false);

    // Loads img_buf
    error = _loadStream(pPictures_dir, fileName.c_str(), img_buf);
    g_object_unref (G_OBJECT (pPictures_dir));

    if (error != UT_OK) {
        return false;
    }


    // Builds pImporter from img_buf
    error = IE_ImpGraphic::loadGraphic (img_buf, IEGFT_Unknown, &pFG);
    if ((error != UT_OK) || !pFG) {
        // pictData is already freed in ~FG_Graphic
      return false;
    }

    // Builds pPictData from pFG
    // TODO: can we get back a vector graphic?
    pPictData = pFG->getBuffer();

    if (!pPictData) {
        // i don't think that this could ever happen, but...
        UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
        return false;
    }

    //
    // Create the data item.
    //

    if (!m_pAbiDocument->createDataItem(rDataId.c_str(),
                                        false,
                                        pPictData,
                                        pFG->getMimeType(),
                                        NULL)) {
            
        UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
        return false;
    }    

    return true;
}

/**
 * Adds an data item (<d> tag) in the AbiWord document for the specified image.
 * 
 * Code mainly from Dom Lachowicz and/or Robert Staudinger.
 * 
 * @param rDataId Receives the id that has been given to the added data item.
 * @param ppAtts The attributes of a <draw:image> element.
 */
bool ODi_Abi_Data::addObjectDataItem(UT_String& rDataId, const gchar** ppAtts, int& pto_Type) {
    
    const gchar* pHRef = UT_getAttribute ("xlink:href", ppAtts);
    UT_return_val_if_fail(pHRef,false);

    // If we have a string smaller then this we are in trouble. File corrupted?
    UT_return_val_if_fail((strlen(pHRef) >= 9 /*9 == strlen("Object a/")*/), false);

    UT_Error error = UT_OK;
    UT_ByteBuf *object_buf;
    GsfInfile* pObjects_dir;
    UT_uint32 objectID;

    // The subdirectory that holds the picture. e.g: "ObjectReplacements" or "Pictures"
    UT_String dirName;
    
    // The file name of the picture. e.g.: "Object 1" or "10000201000000D100000108FF0E3707.png" 
    UT_String fileName;

    const std::string id = m_href_to_id[pHRef];
    if (!id.empty()) {
        // This object was already added.
        // Use the existing data item id.
        rDataId = id;
        return true;
    }

    // Get a new, unique, ID.
    objectID = m_pAbiDocument->getUID(UT_UniqueId::Math);
    UT_String_sprintf(rDataId, "MathLatex%d", objectID);

    std::string rLatexId;
    rLatexId.assign("LatexMath");
    rLatexId.append((rDataId.substr(9,rDataId.length()-8)).c_str());
    // Add this id to the list
    UT_DebugOnly<href_id_map_t::iterator> iter = m_href_to_id
		.insert(m_href_to_id.begin(),
			href_id_map_t::value_type(pHRef, 
						  rDataId.c_str()));
    UT_ASSERT((href_id_map_t::iterator)iter != m_href_to_id.end());

    _splitDirectoryAndFileName(pHRef, dirName, fileName);

    if (fileName.empty ())
      fileName = "content.xml";

    pObjects_dir =
        GSF_INFILE(gsf_infile_child_by_name(m_pGsfInfile, dirName.c_str()));


    UT_return_val_if_fail(pObjects_dir, false);

    // Loads object_buf
    object_buf = new UT_ByteBuf ();
    error = _loadStream(pObjects_dir, fileName.c_str(), *object_buf);
    g_object_unref (G_OBJECT (pObjects_dir));

    if (error != UT_OK) {
	delete object_buf;
        return false;
    }

    // check to ensure that we're seeing math. this can probably be made smarter.
    // changed the math_header to include the simple math tag, as DOC_TYPE has become obsolete
    static const char math_header[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<math";

    // keepin an option for old documents as well which might have DOC_TYPE
    static const char math_header_old[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE math:math";

    // for math from odt generated in MS Word
    static const char math_ms[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<mml:math";
     
    if (((object_buf->getLength () > strlen (math_header)) && (strncmp ((const char*)object_buf->getPointer (0), math_header, strlen (math_header)) != 0)) && ((object_buf->getLength () > strlen (math_header_old)) && (strncmp ((const char*)object_buf->getPointer (0), math_header_old, strlen (math_header_old)) != 0)) && ((object_buf->getLength () > strlen (math_ms)) && (strncmp ((const char*)object_buf->getPointer (0), math_ms, strlen (math_ms)) != 0)))
    {
    	delete object_buf;
        return false;
    }

    //
    // Create the data item.
    //

    UT_ByteBuf latexBuf;
    UT_UTF8String PbMathml = (const char*)(object_buf->getPointer(0));
    UT_UTF8String PbLatex,Pbitex;
	
    if (!m_pAbiDocument->createDataItem(rDataId.c_str(), false, object_buf,"application/mathml+xml", NULL))
    {            
        UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
        return false;
    }  

    if(convertMathMLtoLaTeX(PbMathml, PbLatex) && convertLaTeXtoEqn(PbLatex,Pbitex))
    {
        
	// Conversion of MathML to LaTeX and the Equation Form suceeds
	latexBuf.ins(0,reinterpret_cast<const UT_Byte *>(Pbitex.utf8_str()),static_cast<UT_uint32>(Pbitex.size()));
	if(!m_pAbiDocument->createDataItem(rLatexId.c_str(), false,&latexBuf,"", NULL))		
	{
	    UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
	    return false;
	}
    }

    pto_Type = PTO_Math;
    return true;
}


/**
 * Code from Dom Lachowicz and/or Robert Staudinger.
 */
UT_Error ODi_Abi_Data::_loadStream (GsfInfile* oo,
                                   const char* stream,
                                   UT_ByteBuf& buf ) {
    guint8 const *data = NULL;
    size_t len = 0;
    static const size_t BUF_SZ = 4096;
  
    buf.truncate (0);
    GsfInput * input = gsf_infile_child_by_name(oo, stream);

    if (!input){
    	return UT_ERROR;
    }
  
    if (gsf_input_size (input) > 0) {
        while ((len = gsf_input_remaining (input)) > 0) {
            len = UT_MIN (len, BUF_SZ);
            if (NULL == (data = gsf_input_read (input, len, NULL))) {
                g_object_unref (G_OBJECT (input));
                return UT_ERROR;
            }
            buf.append ((const UT_Byte *)data, len);
        }
    }
  
    g_object_unref (G_OBJECT (input));
    return UT_OK;
}

/**
 * Takes a string like "./ObjectReplacements/Object 1" and split it into
 * subdirectory name ("ObjectReplacements") and file name ("Object 1").
 */
void ODi_Abi_Data::_splitDirectoryAndFileName(const gchar* pHRef, UT_String& dirName, UT_String& fileName) const {
    UT_String href = pHRef;

    int iStart;
    // Get the directory name
    UT_String str = href.substr(0, 2);
    if (str == "./") {
        iStart = 2;
    } else {
        iStart = 0;
    }

    int nChars = 0;
    int len = href.length();
    for (int i = iStart; i < len; i++) {
        if (href[i] == '/') {
            break;
        } else {
            nChars++;
        }
    }

    dirName = href.substr(iStart, nChars);

    if (nChars == len - 1)
    {
        fileName = "";
    }
    else
    {
        UT_ASSERT (nChars > 0 && nChars < len);
        // Get the file name
        iStart = iStart + nChars + 1;
        nChars = len - iStart;
        UT_ASSERT (nChars); // The file name must have at least one char.
        fileName = href.substr(iStart, nChars);
    }
}