summaryrefslogtreecommitdiffstats
path: root/part/kxedocument.cpp
blob: 52394fa872c635de7d8f188ff8228a30abf0ce9a (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
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//
// C++ Implementation: kxedocument
//
// Description:
//
//
// Author: Adam Charytoniuk <[email protected]>, (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "kxedocument.h"

#include "kxmleditorfactory.h"
#include "kxeconfiguration.h"
#include "kxenewfilesettings.h"
#include "kxearchiveextssettings.h"
#include "kxeprintsettings.h"
#include "kxetextviewsettings.h"
#include "kxechoosestringdialog.h"
#include "kxeattachdialogbase.h"
#include "kxespecprocinstrdialog.h"
#include "kxefilenewdialog.h"
#include "commands_file.h"


#include <kfile.h>
#include <ktar.h>
#include <kzip.h>
#include <kfilterdev.h>
#include <ktempfile.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kcommand.h>
#include <kaction.h>
#include <kurl.h>
#include <kurlrequester.h>

#include <tqcombobox.h>
#include <tqbuffer.h>
#include <tqregexp.h>
#include <tqtextcodec.h>
#include <tqlabel.h>
#include <tqcheckbox.h>

KXEDocument::KXEDocument(TQObject *parent, const char *name)
	:TQObject (parent,name),
	TQDomDocument(),
	KXMLGUIClient()
{
	m_bDocIsCompressed = false;
	m_bIsModified = false;
	m_strCompressedTarEntryName = "";
	m_url = "";
		
	//setXMLFile("kxedocument.rc");
}


KXEDocument::~KXEDocument()
{
}


bool KXEDocument::save(const TQString  &strFileName)
{
	if (this->documentElement().isNull() &&
	    KMessageBox::warningContinueCancel(0,
		i18n("Your file doesn't have root element defined. \n\
		Continue saving?"))==KMessageBox::Cancel )
		{
			return false;
		}

	TQString strXML;

	TQTextStream streamXML(&strXML, IO_WriteOnly);
	int iIndent = KXMLEditorFactory::configuration()->textview()->indentSteps();
	((TQDomDocument*)this)->save(streamXML, iIndent);

	TQString strEncoding;
	TQTextCodec *pTextCodec;

  // find encoding info
  if(strXML.left(5) == "<?xml")
     { int iStart, iEnd;
       if((iStart = strXML.find("encoding", 0)) > 0)
       {
         // info about encoding found;
         iStart += 8; // skip encoding

         // search " or ' after encoding
         if((iStart = strXML.find(TQRegExp("[\"']"), iStart)) > 0)
         {
           TQChar ch = strXML[iStart];
           iStart++; // skip ch
           if((iEnd = strXML.find(ch, iStart)) > 0)
           {
             strEncoding = strXML.mid(iStart, iEnd - iStart);
           }
         }
       }
     }

	if(strEncoding.length() <= 0)
    pTextCodec = TQTextCodec::codecForLocale(); // default
  else
    pTextCodec = TQTextCodec::codecForName(strEncoding);

	if(pTextCodec == 0)
		{ if(KMessageBox::questionYesNo(0, i18n("Codec for encoding %1 not found ! Continue saving ?").arg(strEncoding)) != KMessageBox::Yes)
					return false;
		}

	TQCString strDecoded;
	if(pTextCodec)
		{ strDecoded = pTextCodec->fromUnicode(strXML);
		}

  // save string to file
	if(!m_bDocIsCompressed)
	    { TQFile file(strFileName);
	      if(file.open(IO_WriteOnly) == true)
	        { file.writeBlock(strDecoded, strDecoded.length());
	  				file.flush();
	  				file.close();
	  			}
	  		else
					{ KMessageBox::error(0,
												 i18n("Can't create file %1").arg(strFileName),
												 i18n("Write error !"));
					}
	  	}
	else
	  	{ // obtain file extension -----------------------------------------
				TQString strExtension;
			
				int iPos = strFileName.findRev('.');
			
				if(iPos > 0)
					{ strExtension = strFileName.mid(iPos + 1);
					}
					
				if(strExtension == "svgz")
				{
					KMessageBox::sorry(0,
												 "Saving *.svgz not implemented yet",
												 "sory");
					return false;
				}
				else
				{
					KZip	tarGzFile(strFileName); // New KOffice use KZip instead of KTarGz for storing files
					if(tarGzFile.open(IO_WriteOnly))
						{ tarGzFile.writeFile(m_strCompressedTarEntryName, "user", "group", strDecoded.length(), strDecoded);
							tarGzFile.close();
						}
					else
						{ KMessageBox::error(0,
													i18n("Can't create archive %1").arg(strFileName),
													i18n("Write error !"));
						}
				}
			}

	return true;
}

bool KXEDocument::open(const TQString &strFileName)
{
  TQString strCompressedTarEntryName;

  kdDebug() << "KXEDocument::open: opening file " << strFileName << endl;

  // obtain file extension -----------------------------------------
	TQString strExtension;

	int iPos = strFileName.findRev('.');

	if(iPos > 0)
		{ strExtension = strFileName.mid(iPos + 1);
		}

	TQString strTmpfileName;

	if ( KXMLEditorFactory::configuration()->archexts()->extensions().contains(strExtension) )
		{ 
		  
			KTempFile tmp;
			if (tmp.status() != 0)
			{
				kdError() << "Couldn't open temp file" << endl;
				KMessageBox::sorry(0, i18n("Couldn't open temp file !"));
				return false;
			}
		
			tmp.setAutoDelete(false);
			TQFile &fileTemporary = *(tmp.file());
			
						
			if(strExtension == "svgz")
				{ 
					//----------------------- It is gzip compressed file -----------------------
				
					m_strCompressedTarEntryName = strFileName.left(strFileName.length() - 5); // For SVG compressed icons strip extension, e.g. "kate.svgz" has entry "kate" etc
				
					iPos = m_strCompressedTarEntryName.findRev('/');

					if(iPos > 0)
						{ m_strCompressedTarEntryName = m_strCompressedTarEntryName.mid(iPos + 1);
						}
					
				  TQIODevice *pIODevice = KFilterDev::deviceForFile(strFileName, "application/x-gzip");
				  
					if(pIODevice->open( IO_ReadOnly ))
					{
							TQTextStream stream(pIODevice);
							TQString line;
							//int i = 1;
							while ( !stream.atEnd() ) 
							{
									line = stream.readLine(); // line of text excluding '\n'
									//printf( "%3d: %s\n", i++, line.latin1() );
									fileTemporary.writeBlock(line, line.length());
							}
							pIODevice->close();
					}
				}
			else 
				{
					//----------------------- It is zip archive file ---------------------------
				  								
					KZip tarGzFile(strFileName); // new KOffice use KZip instead of KTarGz for storing files
					
					tarGzFile.open(IO_ReadOnly);
					fileTemporary.open(IO_WriteOnly);
		
					const KTarDirectory *root = tarGzFile.directory();
					if(!root)
						{
							return false;
						}
		
					// For KOffice files let user to choose maindoc or documentinfo
					if(strCompressedTarEntryName.length() == 0)
					{ KXEChooseStringDialog dlgChooseString(0, 0, i18n("Choose file"), i18n("File:"));
						dlgChooseString.m_pComboBox->insertItem("maindoc.xml");
						dlgChooseString.m_pComboBox->insertItem("documentinfo.xml");
	
						if(dlgChooseString.exec() != KXEChooseStringDialog::Accepted)
							{ return false;
							}
						m_strCompressedTarEntryName = dlgChooseString.m_strChoosedText;
					}
					else
					{ 
						m_strCompressedTarEntryName = strCompressedTarEntryName;
					}
							
					const KArchiveEntry *entry = root->entry(m_strCompressedTarEntryName);
		
					if(entry && entry->isFile())
						{ const KArchiveFile *pTarFile = static_cast <const KArchiveFile *> (entry);
		
							TQBuffer buffer(pTarFile->data());
							buffer.open(IO_ReadOnly);
		
							fileTemporary.writeBlock(buffer.buffer(), buffer.size());
						}
					else
						m_strCompressedTarEntryName.truncate(0);
		
					tarGzFile.close();
				}
			
			strTmpfileName = fileTemporary.name();
			fileTemporary.close();
					
			m_bDocIsCompressed = true;
		}
	else
		m_bDocIsCompressed = false;


	// ( 1.) parse the file and fill our document
	TQFile file(m_bDocIsCompressed ? strTmpfileName : strFileName);
	if(! file.open(IO_ReadOnly))
	{
		kdDebug() << "KXEDocument::openFile: Can't open file." << endl;
		return false;
	}

  // auxiliary file for obtaining encoding info
  TQFile fileAux(m_bDocIsCompressed ? strTmpfileName : strFileName);
	if(! fileAux.open(IO_ReadOnly))
	{
		kdDebug() << "KXEDocument::openFile: Can't open file." << endl;
		return false;
	}

	TQTextStream txtStreamLocal( & file );

  // Lookup at XML document encoding -----------------------------------------------
  TQTextStream txtStreamAux( & fileAux );
  TQString strFirstLine = txtStreamAux.readLine();
  fileAux.close();
  int iStart, iEnd;
  if((iStart = strFirstLine.find("encoding", 0)) > 0)
  {
    TQString strEncoding;
    // info about encoding found;
    iStart += 8; // skip encoding

    // search " or ' after encoding
    if((iStart = strFirstLine.find(TQRegExp("[\"']"), iStart)) > 0)
    {
      TQChar ch = strFirstLine[iStart];
      iStart++; // skip ch
      if((iEnd = strFirstLine.find(ch, iStart)) > 0)
      {
        strEncoding = strFirstLine.mid(iStart, iEnd - iStart);

        TQTextCodec *pTextCodec = TQTextCodec::codecForName(strEncoding);
        if(pTextCodec)
          txtStreamLocal.setCodec(pTextCodec);
        else
        {
          KMessageBox::sorry(0, i18n("Codec for encoding %1 not found ! Using locale encoding for load.").arg(strEncoding));
          txtStreamLocal.setEncoding(TQTextStream::Locale);
        }
      }
    }
  }
  else
  {
    // XML documment dont have info about encoding, set default UTF-8
    txtStreamLocal.setCodec(TQTextCodec::codecForName("UTF-8"));
  }


  //--------------------------------------------------------------------------------
  TQString strFileContents = txtStreamLocal.read();
	file.close();

  if(m_bDocIsCompressed)
    {
      TQDir dir;
      dir.remove(strTmpfileName);
    }

  //-- Set string with XML to TQDomDocument ------------------------------------------
	TQString strErrorMsg;
  int iErrorLine, iErrorColumn;
	TQDomDocument * pNewDoc = new TQDomDocument; // first try with a new document

 	if( ! pNewDoc->setContent(strFileContents, true, &strErrorMsg, &iErrorLine, &iErrorColumn) )
 		{ kdDebug() << "KXEDocument::openFile: Failed parsing the file." << endl;

			KMessageBox::error(0,
												 i18n("%1 in line %2, column %3").arg(strErrorMsg).arg(iErrorLine).arg(iErrorColumn),
												 i18n("Parsing error !"));

			delete pNewDoc; // remove the new document, because it's useless
			return false;
 		}

// The following commented code is performance wise buggy, because the string
// gets parsed a second time. I replaced it with this code.
	// copy the content of the parsed document to this one
	TQDomNode e = pNewDoc->removeChild( pNewDoc->documentElement() );
	TQDomDocument::operator=( *pNewDoc );
	appendChild( e );
// Here comes the "buggy" code.
	//this->setContent(pNewDoc->toString(),true,0,0); // and take the new one
	//delete pNewDoc;    // remove the former document
// To test/see the difference in loading time, you can switch the commented 
// codeblocks above and compare the loading-time-differences measured in 
// KXMLEditorPart::openFile.
//                                             Olaf
// TODO: remove the comments above later

	emit sigOpened();
	
	return true;
}

void KXEDocument::setModified(bool value)
{
	m_bIsModified = value;
	emit sigModified(value);
}

void KXEDocument::setURL(KURL url)
{
	m_url = url;
	emit sigURLChanged(url);
}

void KXEDocument::updateNodeCreated(const TQDomNode & node)
{
	emit sigNodeCreated(node);
	setModified();
}

void KXEDocument::updateNodeDeleted(const TQDomNode & node)
{
	emit sigNodeDeleted(node);
	setModified();
}

void KXEDocument::updateNodeChanged( const TQDomElement & domElement )
{
	emit sigNodeChanged(domElement);
	setModified();
}

void KXEDocument::updateNodeChanged( const TQDomCharacterData & node )
{
	emit sigNodeChanged(node);
	setModified();
}

void KXEDocument::updateNodeChanged( const TQDomProcessingInstruction &domProcInstr )
{
	emit sigNodeChanged(domProcInstr);
	setModified();
}

void KXEDocument::updateNodeMoved( const TQDomNode & node )
{
	emit sigNodeMoved(node);
	setModified();
}

void KXEDocument::attachStylesheet(const KURL& stylesheet)
{
	setSpecProcInstr("xml-stylesheet",TQString("type = 'text/xsl' href = '")+stylesheet.url()+"' ");
}

void KXEDocument::detachStylesheet()
{
	removeSpecProcInstr("xml-stylesheet");
}

void KXEDocument::attachSchema(const KURL& schema)
{
	TQDomElement domElement = documentElement();
	if (!domElement.isNull())
	{
		domElement.setAttributeNS(SCHEMA_NAMESPACE,
								SCHEMA_ATTRIBUTE_XSI,
								schema.url());
		// refresh views
		updateNodeChanged(domElement);
		setModified();
	}
}

void KXEDocument::detachSchema()
{
	TQDomElement domElement = this->documentElement();
	if (!domElement.isNull())
	{
		domElement.removeAttributeNS(SCHEMA_NAMESPACE,SCHEMA_ATTRIBUTE);
		// refresh views
		updateNodeChanged(domElement);
		setModified();
	}
}

void KXEDocument::setSpecProcInstr(const TQString& target, const TQString& data)
{
	// removing old one
	removeSpecProcInstr(target);
	// create new one
	if (!data.isEmpty())
	{
		TQDomProcessingInstruction domProcInstr = this->createProcessingInstruction(target,data);

		TQDomNode node = getSpecProcInstr("xml");
		if (!node.isNull())
			// if there is already xml instruction, then put that one below it
			this->insertAfter(domProcInstr,node);
		else
			// otherwise put it always on the top
			this->insertBefore(domProcInstr,this->firstChild());

		updateNodeCreated(domProcInstr);
	}
	setModified();
}

void KXEDocument::removeSpecProcInstr(const TQString &target)
{
	TQDomNode domNode = getSpecProcInstr(target);
	if (!domNode.isNull())
	{
		updateNodeDeleted(domNode);
		((TQDomDocument*)this)->removeChild(domNode);
		setModified();
	}
}

TQDomNode KXEDocument::getSpecProcInstr(const TQString& target)
{
	TQDomNode result;
	TQDomNodeList domNodeList = this->childNodes();
	for (uint i=0;i<domNodeList.count();i++)
		if (domNodeList.item(i).isProcessingInstruction())
		{
			TQDomProcessingInstruction domProcInstr = domNodeList.item(i).toProcessingInstruction();
			if (domProcInstr.target()==target)
				return domNodeList.item(i);
		}
	return result;
}

void KXEDocument::newFile()
{
	switch ( KXMLEditorFactory::configuration()->newfile()->newFileCreaBehav() )
	{
		case KXENewFileSettings::CreateEmptyFile:
			break;         // nothing to do in this case

		case KXENewFileSettings::CreateWithAssistance:
		{

			KXEFileNewDialog dlg( 0L);
			dlg.fillDialog( KXMLEditorFactory::configuration()->newfile()->dfltVersion(),
			                KXMLEditorFactory::configuration()->newfile()->dfltEncoding() );
			if( dlg.exec() )
			{                    // if the dialog has been accepted (OK pressed)
				setSpecProcInstr( "xml", dlg.getData() );

				// if the dialog shouldn't be shown anymore, the settings have to be changed
				if ( dlg.m_pDontShowAgain->isChecked() )
					KXMLEditorFactory::configuration()->newfile()->setNewFileCreaBehav( KXENewFileSettings::UseDefaults, instance()->config() );
			}

			break;
		}

		case KXENewFileSettings::UseDefaults:
			setSpecProcInstr( "xml", TQString( "version='%1' encoding='%2'" ).arg(KXMLEditorFactory::configuration()->newfile()->dfltVersion()).arg(KXMLEditorFactory::configuration()->newfile()->dfltEncoding()) );
			break;
	}
	emit sigOpened();
	setModified();
}

//------------- SLOTS, called from Part --------------------------------

KCommand * KXEDocument::actDetachStylesheet()
{
	TQDomNode domNode = getSpecProcInstr("xml-stylesheet");
	if (!domNode.isNull())
	{
		KCommand *pCmd = new KXEStylesheetDetachCommand(this,domNode.toProcessingInstruction().data());
		return pCmd;
	}
	return 0L;
}

KCommand * KXEDocument::actAttachStylesheet()
{
	KXEAttachDialogBase dlg;
	dlg.Label->setText(i18n("Stylesheet URL:"));
	if (dlg.exec())
	{
		TQDomNode domNode = getSpecProcInstr("xml-stylesheet");
		TQString data = "";
		if (!domNode.isNull())
			data = domNode.toProcessingInstruction().data();
		KCommand *pCmd = new KXEStylesheetAttachCommand(this,data,dlg.attachURI->url());
		return pCmd;
	}
	return 0L;
}

KCommand * KXEDocument::actDetachSchema()
{
	if (!documentElement().isNull())		// just for sure...
	{
		KCommand *pCmd = new KXESchemaDetachCommand(this,
													documentElement().attributeNS(SCHEMA_NAMESPACE,
																			SCHEMA_ATTRIBUTE,"")
													);
		return pCmd;
	}
	return 0L;
}

KCommand * KXEDocument::actAttachSchema()
{
	KXEAttachDialogBase dlg;
	dlg.Label->setText(i18n("Schema URL:"));
	if (dlg.exec())
	{
		if (!documentElement().isNull())		// just for sure...
		{
			KCommand *pCmd = new KXESchemaAttachCommand(this,dlg.attachURI->url(),
													documentElement().attributeNS(SCHEMA_NAMESPACE,SCHEMA_ATTRIBUTE,""));
			return pCmd;
		}
	}
	return 0L;
}

// Instert or edit special processing instruction <?xml ... ?>
KCommand * KXEDocument::actVersionEncoding()
{
	TQDomNode node = getSpecProcInstr("xml");
	KXESpecProcInstrDialog dlg;

	if(!node.isNull())
		dlg.fillDialog(node.toProcessingInstruction().data());
	else
		dlg.fillDialog( KXMLEditorFactory::configuration()->newfile()->dfltVersion(),
		                KXMLEditorFactory::configuration()->newfile()->dfltEncoding() );

	if(dlg.exec())
	{
		TQString strOldData = "";
		if (!node.isNull())
			strOldData = node.toProcessingInstruction().data();
		KCommand *pCmd = new KXEVersionEncodingCommand(this,strOldData,dlg.getData());
		return pCmd;
	}
	return 0L;
}

#include "kxedocument.moc"