Source

ooo340 / sw / source / filter / ascii / parasc.cxx

  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
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * 
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */


#include <tools/stream.hxx>
#include <hintids.hxx>
#include <rtl/tencinfo.h>
#include <sfx2/printer.hxx>
#include <editeng/fontitem.hxx>
#include <editeng/langitem.hxx>
#include <editeng/brkitem.hxx>
#include <editeng/scripttypeitem.hxx>
#include <shellio.hxx>
#include <doc.hxx>
#include <swtypes.hxx>
#include <ndtxt.hxx>
#include <pam.hxx>
#include <frmatr.hxx>
#include <fltini.hxx>
#include <pagedesc.hxx>
#include <breakit.hxx>
#include <swerror.h>
#ifndef _STATSTR_HRC
#include <statstr.hrc>          // ResId fuer Statusleiste
#endif
#include <mdiexp.hxx>           // ...Percent()
#include <poolfmt.hxx>

#define ASC_BUFFLEN 4096

class SwASCIIParser
{
	SwDoc* pDoc;
	SwPaM* pPam;
	SvStream& rInput;
	sal_Char* pArr;
	const SwAsciiOptions& rOpt;
	SfxItemSet* pItemSet;
	long nFileSize;
	USHORT nScript;
	bool bNewDoc;

	ULONG ReadChars();
	void InsertText( const String& rStr );

public:
	SwASCIIParser( SwDoc* pD, const SwPaM& rCrsr, SvStream& rIn,
							int bReadNewDoc, const SwAsciiOptions& rOpts );
	~SwASCIIParser();

	ULONG CallParser();
};


// Aufruf fuer die allg. Reader-Schnittstelle
ULONG AsciiReader::Read( SwDoc &rDoc, const String&, SwPaM &rPam, const String & )
{
	if( !pStrm )
	{
		ASSERT( !this, "ASCII-Read ohne Stream" );
		return ERR_SWG_READ_ERROR;
	}

	//JP 18.01.96: Alle Ueberschriften sind normalerweise ohne
	//              Kapitelnummer. Darum hier explizit abschalten
	//              weil das Default jetzt wieder auf AN ist.
	if( !bInsertMode )
		Reader::SetNoOutlineNum( rDoc );

	SwASCIIParser* pParser = new SwASCIIParser( &rDoc, rPam, *pStrm,
										!bInsertMode, aOpt.GetASCIIOpts() );
	ULONG nRet = pParser->CallParser();

	delete pParser;
	// after Read reset the options
	aOpt.ResetASCIIOpts();
	return nRet;
}

SwASCIIParser::SwASCIIParser(SwDoc* pD, const SwPaM& rCrsr, SvStream& rIn,
    int bReadNewDoc, const SwAsciiOptions& rOpts)
	: pDoc(pD), rInput(rIn), rOpt(rOpts), nScript(0), bNewDoc(bReadNewDoc)
{
	pPam = new SwPaM( *rCrsr.GetPoint() );
	pArr = new sal_Char [ ASC_BUFFLEN + 2 ];

	pItemSet = new SfxItemSet( pDoc->GetAttrPool(),
				RES_CHRATR_FONT,		RES_CHRATR_LANGUAGE,
				RES_CHRATR_CJK_FONT,	RES_CHRATR_CJK_LANGUAGE,
				RES_CHRATR_CTL_FONT,	RES_CHRATR_CTL_LANGUAGE,
				0 );

	// set defaults from the options
	if( rOpt.GetLanguage() )
	{
		SvxLanguageItem aLang( (LanguageType)rOpt.GetLanguage(),
						 		RES_CHRATR_LANGUAGE );
		pItemSet->Put( aLang );
		pItemSet->Put( aLang, RES_CHRATR_CJK_LANGUAGE );
		pItemSet->Put( aLang, RES_CHRATR_CTL_LANGUAGE );
	}
	if( rOpt.GetFontName().Len() )
	{
		bool bDelete = false;
		const SfxFont* pFnt = 0;
        if( pDoc->getPrinter( false ) )
            pFnt = pDoc->getPrinter( false )->GetFontByName( rOpt.GetFontName() );

		if( !pFnt )
		{
			pFnt = new SfxFont( FAMILY_DONTKNOW, rOpt.GetFontName() );
			bDelete = true;
		}
		SvxFontItem aFont( pFnt->GetFamily(), pFnt->GetName(),
                        aEmptyStr, pFnt->GetPitch(), pFnt->GetCharSet(), RES_CHRATR_FONT );
		pItemSet->Put( aFont );
		pItemSet->Put( aFont, RES_CHRATR_CJK_FONT );
		pItemSet->Put( aFont, RES_CHRATR_CTL_FONT );

		if( bDelete )
			delete (SfxFont*)pFnt;
	}
}

SwASCIIParser::~SwASCIIParser()
{
	delete pPam;
	delete [] pArr;
	delete pItemSet;
}


// Aufruf des Parsers
ULONG SwASCIIParser::CallParser()
{
	rInput.Seek(STREAM_SEEK_TO_END);
	rInput.ResetError();

	nFileSize = rInput.Tell();
	rInput.Seek(STREAM_SEEK_TO_BEGIN);
	rInput.ResetError();

	::StartProgress( STR_STATSTR_W4WREAD, 0, nFileSize, pDoc->GetDocShell() );

	SwPaM* pInsPam = 0;
	xub_StrLen nSttCntnt = 0;
	if (!bNewDoc)
	{
		const SwNodeIndex& rTmp = pPam->GetPoint()->nNode;
		pInsPam = new SwPaM( rTmp, rTmp, 0, -1 );
		nSttCntnt = pPam->GetPoint()->nContent.GetIndex();
	}

    SwTxtFmtColl *pColl = 0;

    if (bNewDoc)
    {
        pColl = pDoc->GetTxtCollFromPool(RES_POOLCOLL_HTML_PRE, false);
        if (!pColl)
            pColl = pDoc->GetTxtCollFromPool(RES_POOLCOLL_STANDARD,false);
        if (pColl)
            pDoc->SetTxtFmtColl(*pPam, pColl);
    }

	ULONG nError = ReadChars();

	if( pItemSet )
	{
		// set only the attribute, for scanned scripts.
		if( !( SCRIPTTYPE_LATIN & nScript ))
		{
			pItemSet->ClearItem( RES_CHRATR_FONT );
			pItemSet->ClearItem( RES_CHRATR_LANGUAGE );
		}
		if( !( SCRIPTTYPE_ASIAN & nScript ))
		{
			pItemSet->ClearItem( RES_CHRATR_CJK_FONT );
			pItemSet->ClearItem( RES_CHRATR_CJK_LANGUAGE );
		}
		if( !( SCRIPTTYPE_COMPLEX & nScript ))
		{
			pItemSet->ClearItem( RES_CHRATR_CTL_FONT );
			pItemSet->ClearItem( RES_CHRATR_CTL_LANGUAGE );
		}
		if( pItemSet->Count() )
		{
			if( bNewDoc )
			{
                if (pColl)
                {
				    // Using the pool defaults for the font causes significant
				    // trouble for the HTML filter, because it is not able
				    // to export the pool defaults (or to be more precice:
				    // the HTML filter is not able to detect whether a pool
				    // default has changed or not. Even a comparison with the
				    // HTMLi template does not work, because the defaults are
				    // not copied when a new doc is created. The result of
				    // comparing pool defaults therfor would be that the
				    // defaults are exported always if the have changed for
				    // text documents in general. That's not sensible, as well
				    // as it is not sensible to export them always.
				    sal_uInt16 aWhichIds[4] =
                    {
                        RES_CHRATR_FONT, RES_CHRATR_CJK_FONT,
                        RES_CHRATR_CTL_FONT, 0
                    };
				    sal_uInt16 *pWhichIds = aWhichIds;
				    while (*pWhichIds)
				    {
				        const SfxPoolItem *pItem;
					    if (SFX_ITEM_SET == pItemSet->GetItemState(*pWhichIds,
                            false, &pItem))
					    {
                            pColl->SetFmtAttr( *pItem );
						    pItemSet->ClearItem( *pWhichIds );
					    }
					    ++pWhichIds;
				    }
                }
				if (pItemSet->Count())
					pDoc->SetDefault(*pItemSet);
			}
			else if( pInsPam )
			{
				// then set over the insert range the defined attributes
				*pInsPam->GetMark() = *pPam->GetPoint();
				pInsPam->GetPoint()->nNode++;
				pInsPam->GetPoint()->nContent.Assign(
									pInsPam->GetCntntNode(), nSttCntnt );

				// !!!!!
				ASSERT( !this, "Have to change - hard attr. to para. style" );
                pDoc->InsertItemSet( *pInsPam, *pItemSet, 0 );
			}
		}
		delete pItemSet, pItemSet = 0;
	}

	if( pInsPam )
		delete pInsPam;

	::EndProgress( pDoc->GetDocShell() );
	return nError;
}

ULONG SwASCIIParser::ReadChars()
{
	sal_Unicode *pStt = 0, *pEnd = 0, *pLastStt = 0;
	long nReadCnt = 0, nLineLen = 0;
	sal_Unicode cLastCR = 0;
    bool bSwapUnicode = false;

    const SwAsciiOptions *pUseMe=&rOpt;
    SwAsciiOptions aEmpty;
    if (nFileSize >= 2 &&
        aEmpty.GetFontName() == rOpt.GetFontName() &&
        aEmpty.GetCharSet() == rOpt.GetCharSet() &&
        aEmpty.GetLanguage() == rOpt.GetLanguage() &&
        aEmpty.GetParaFlags() == rOpt.GetParaFlags())
    {
        ULONG nLen, nOrig;
        nOrig = nLen = rInput.Read(pArr, ASC_BUFFLEN);
        CharSet eCharSet;
        bool bRet = SwIoSystem::IsDetectableText(pArr, nLen, &eCharSet, &bSwapUnicode);
        ASSERT(bRet, "Autodetect of text import without nag dialog must "
            "have failed");
        if (bRet && eCharSet != RTL_TEXTENCODING_DONTKNOW)
        {
            aEmpty.SetCharSet(eCharSet);
            rInput.SeekRel(-(long(nLen)));
        }
        else
            rInput.SeekRel(-(long(nOrig)));
        pUseMe=&aEmpty;
    }

	rtl_TextToUnicodeConverter hConverter=0;
	rtl_TextToUnicodeContext hContext=0;
	CharSet currentCharSet = pUseMe->GetCharSet();
	if (RTL_TEXTENCODING_UCS2 != currentCharSet)
	{
		if( currentCharSet == RTL_TEXTENCODING_DONTKNOW )
	            currentCharSet = RTL_TEXTENCODING_ASCII_US;
		hConverter = rtl_createTextToUnicodeConverter( currentCharSet );
		ASSERT( hConverter, "no string convert avaiable" );
		if (!hConverter)
            return ERROR_SW_READ_BASE;
		bSwapUnicode = false;
		hContext = rtl_createTextToUnicodeContext( hConverter );
	}
	else if (pUseMe != &aEmpty)  //Already successfully figured out type
	{
		rInput.StartReadingUnicodeText();
		bSwapUnicode = rInput.IsEndianSwap();
	}

	String sWork;
	ULONG nArrOffset = 0;

	do {
		if( pStt >= pEnd )
		{
			if( pLastStt != pStt )
				InsertText( String( pLastStt ));

			// lese einen neuen Block ein
			ULONG lGCount;
			if( SVSTREAM_OK != rInput.GetError() || 0 == (lGCount =
						rInput.Read( pArr + nArrOffset,
									 ASC_BUFFLEN - nArrOffset )))
				break;		// aus der WHILE-Schleife heraus

            /*
            #98380#
            If there was some unconverted bytes on the last cycle then they
            were put at the beginning of the array, so total bytes available
            to convert this cycle includes them. If we found 0 following bytes
            then we ignore the previous partial character.
            */
            lGCount+=nArrOffset;

			if( hConverter )
			{
				sal_uInt32 nInfo;
				sal_Size nNewLen = lGCount, nCntBytes;
                sal_Unicode* pBuf = sWork.AllocBuffer( static_cast< xub_StrLen >(nNewLen) );

				nNewLen = rtl_convertTextToUnicode( hConverter, hContext,
								pArr, lGCount, pBuf, nNewLen,
								(
								RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_DEFAULT |
								RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_DEFAULT |
								RTL_TEXTTOUNICODE_FLAGS_INVALID_DEFAULT |
                                RTL_TEXTTOUNICODE_FLAGS_GLOBAL_SIGNATURE
								),
								&nInfo,
								&nCntBytes );
				if( 0 != ( nArrOffset = lGCount - nCntBytes ) )
					memmove( pArr, pArr + nCntBytes, nArrOffset );
                sWork.ReleaseBufferAccess( static_cast< xub_StrLen >(nNewLen) );

				pStt = pLastStt = sWork.GetBufferAccess();
				pEnd = pStt + nNewLen;
			}
			else
			{
				pStt = pLastStt = (sal_Unicode*)pArr;
				pEnd = (sal_Unicode*)(pArr + lGCount);

				if( bSwapUnicode )
				{
					sal_Char* pF = pArr, *pN = pArr + 1;
					for( ULONG n = 0; n < lGCount; n += 2, pF += 2, pN += 2 )
					{
						sal_Char c = *pF;
						*pF = *pN;
						*pN = c;
					}
				}
			}

			*pEnd = 0;
			nReadCnt += lGCount;

			::SetProgressState( nReadCnt, pDoc->GetDocShell() );

			if( cLastCR )
			{
				if( 0x0a == *pStt && 0x0d == cLastCR )
					pLastStt = ++pStt;
				cLastCR = 0;
				nLineLen = 0;
				// JP 03.04.96: das letze am Ende nehmen wir nicht
				if( !rInput.IsEof() || !(pEnd == pStt ||
					( !*pEnd && pEnd == pStt+1 ) ) )
					pDoc->SplitNode( *pPam->GetPoint(), false );
			}
		}

		bool bIns = true, bSplitNode = false;
		switch( *pStt )
		{
//JP 12.11.2001: task 94636 - don't ignore all behind the zero character,
//							  change it to the default "control character"
//		case 0:
//					pEnd = pStt;
//					bIns = false ;
//					break;

		case 0x0a:	if( LINEEND_LF == pUseMe->GetParaFlags() )
					{
						bIns = false;
						*pStt = 0;
						++pStt;

						// JP 03.04.96: das letze am Ende nehmen wir nicht
						if( !rInput.IsEof() || pEnd != pStt )
							bSplitNode = true;
					}
					break;

		case 0x0d:	if( LINEEND_LF != pUseMe->GetParaFlags() )
					{
						bIns = false;
						*pStt = 0;
						++pStt;

						bool bChkSplit = false;
						if( LINEEND_CRLF == pUseMe->GetParaFlags() )
						{
							if( pStt == pEnd )
								cLastCR = 0x0d;
							else if( 0x0a == *pStt )
							{
								++pStt;
								bChkSplit = true;
							}
						}
						else
							bChkSplit = true;

							// JP 03.04.96: das letze am Ende nehmen wir nicht
						if( bChkSplit && ( !rInput.IsEof() || pEnd != pStt ))
							bSplitNode = true;
					}
					break;

		case 0x0c:
					{
						// dann mal einen harten Seitenumbruch einfuegen
						*pStt++ = 0;
						if( nLineLen )
						{
							// Change to charset system!!!!
							//rOpt.GetCharSet();
							InsertText( String( pLastStt ));
						}
						pDoc->SplitNode( *pPam->GetPoint(), false );
                        pDoc->InsertPoolItem( *pPam, SvxFmtBreakItem(
                                    SVX_BREAK_PAGE_BEFORE, RES_BREAK ), 0);
						pLastStt = pStt;
						nLineLen = 0;
						bIns = false;
					}
					break;

		case 0x1a:
					if( nReadCnt == nFileSize && pStt+1 == pEnd )
						*pStt = 0;
					else
						*pStt = '#';        // Ersatzdarstellung
					break;

		case '\t':	break;

		default:
			if( ' ' > *pStt )
					// Ctrl-Zchn gefunden ersetze durch '#'
				*pStt = '#';
			break;
		}

		if( bIns )
		{
			if( ( nLineLen >= MAX_ASCII_PARA - 100 ) &&
				( ( *pStt == ' ' ) || ( nLineLen >= MAX_ASCII_PARA - 1 ) ) )
			{
				sal_Unicode c = *pStt;
				*pStt = 0;
				InsertText( String( pLastStt ));
				pDoc->SplitNode( *pPam->GetPoint(), false );
				pLastStt = pStt;
				nLineLen = 0;
				*pStt = c;
			}
			++pStt;
			++nLineLen;
		}
		else if( bSplitNode )
		{
			// es wurde ein CR/LF erkannt, also speichere den Text

			InsertText( String( pLastStt ));
			pDoc->SplitNode( *pPam->GetPoint(), false );
			pLastStt = pStt;
			nLineLen = 0;
		}
	} while(true);

	if( hConverter )
	{
		rtl_destroyTextToUnicodeContext( hConverter, hContext );
		rtl_destroyTextToUnicodeConverter( hConverter );
	}
	return 0;
}

void SwASCIIParser::InsertText( const String& rStr )
{
    pDoc->InsertString( *pPam, rStr );
    pDoc->UpdateRsid( *pPam, rStr.Len() );
    pDoc->UpdateParRsid( pPam->GetPoint()->nNode.GetNode().GetTxtNode() );
	
	if( pItemSet && pBreakIt && nScript != ( SCRIPTTYPE_LATIN |
											 SCRIPTTYPE_ASIAN |
											 SCRIPTTYPE_COMPLEX ) )
		nScript |= pBreakIt->GetAllScriptsOfText( rStr );
}

/* vi:set tabstop=4 shiftwidth=4 expandtab: */