summaryrefslogtreecommitdiffstats
path: root/kate/xmlcheck/plugin_katexmlcheck.cpp
blob: 65a8b7c9864d360490ab2e505b18cfb8b42a5096 (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
/***************************************************************************
                           plugin_katexmlcheck.cpp - checks XML files using xmllint
                           -------------------
	begin                : 2002-07-06
	copyright            : (C) 2002 by Daniel Naber
	email                : daniel.naber@t-online.de
 ***************************************************************************/

/***************************************************************************
 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.
 ***************************************************************************/

/*
-fixme: show dock if "Validate XML" is selected (doesn't currently work when Kate
 was just started and the dockwidget isn't yet visible)
-fixme(?): doesn't correctly disappear when deactivated in config
*/

#include "plugin_katexmlcheck.h"
#include "plugin_katexmlcheck.moc"

#include <cassert>

#include <config.h>
#include <tqfile.h>
#include <tqinputdialog.h>
#include <tqregexp.h>
#include <tqstring.h>
#include <tqtextstream.h>

#include <tdeaction.h>
#include <kcursor.h>
#include <kdebug.h>
#include <kdockwidget.h>
#include <kinstance.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kstandarddirs.h>
#include <tdetempfile.h>
#include <kate/toolviewmanager.h>
#include <kgenericfactory.h>

K_EXPORT_COMPONENT_FACTORY( katexmlcheckplugin, KGenericFactory<PluginKateXMLCheck>( "katexmlcheck" ) )

PluginKateXMLCheck::PluginKateXMLCheck( TQObject* parent, const char* name, const TQStringList& )
	: Kate::Plugin ( (Kate::Application *)parent, name )
{
}


PluginKateXMLCheck::~PluginKateXMLCheck()
{
}


void PluginKateXMLCheck::addView(Kate::MainWindow *win)
{
  Kate::ToolViewManager *viewmanager = win->toolViewManager();
	TQWidget *dock = viewmanager->createToolView("kate_plugin_xmlcheck_ouputview", Kate::ToolViewManager::Bottom, SmallIcon("misc"), i18n("XML Checker Output"));

	PluginKateXMLCheckView *view = new PluginKateXMLCheckView (dock,win,"katexmlcheck_outputview");
	view->dock = dock;

	win->guiFactory()->addClient(view);
	view->win = win;

	m_views.append(view);
}


void PluginKateXMLCheck::removeView(Kate::MainWindow *win)
{
	for (uint z=0; z < m_views.count(); z++) {
		if (m_views.at(z)->win == win) {
			PluginKateXMLCheckView *view = m_views.at(z);
			m_views.remove (view);
			win->guiFactory()->removeClient (view);
			delete view->dock; // this will delete view, too
		}
	}
}


//---------------------------------
PluginKateXMLCheckView::PluginKateXMLCheckView(TQWidget *parent,Kate::MainWindow *mainwin,const char* name)
	:TQListView(parent,name),KXMLGUIClient(),win(mainwin)
{
	m_tmp_file=0;
	m_proc=0;
	(void) new TDEAction ( i18n("Validate XML"), 0, TQT_TQOBJECT(this),
		TQT_SLOT( slotValidate() ), actionCollection(), "xml_check" );
	// TODO?:
	//(void)  new TDEAction ( i18n("Indent XML"), 0, this,
	//	TQT_SLOT( slotIndent() ), actionCollection(), "xml_indent" );

	setInstance(new TDEInstance("kate"));
	setXMLFile("plugins/katexmlcheck/ui.rc");


	setFocusPolicy(TQ_NoFocus);
	addColumn(i18n("#"), -1);
	addColumn(i18n("Line"), -1);
	setColumnAlignment(1, AlignRight);
	addColumn(i18n("Column"), -1);
	setColumnAlignment(2, AlignRight);
	addColumn(i18n("Message"), -1);
	setAllColumnsShowFocus(true);
	setResizeMode(TQListView::LastColumn);
	connect(this, TQT_SIGNAL(clicked(TQListViewItem *)), TQT_SLOT(slotClicked(TQListViewItem *)));

/* TODO?: invalidate the listview when document has changed
	Kate::View *kv = application()->activeMainWindow()->viewManager()->activeView();
	if( ! kv ) {
		kdDebug() << "Warning: no Kate::View" << endl;
		return;
	}
	connect(kv, TQT_SIGNAL(modifiedChanged()), this, TQT_SLOT(slotUpdate()));
*/

	m_proc_stderr = "";
	m_proc = new TDEProcess();
	connect(m_proc, TQT_SIGNAL(processExited(TDEProcess*)), this, TQT_SLOT(slotProcExited(TDEProcess*)));
	// we currently only want errors:
	//connect(m_proc, TQT_SIGNAL(receivedStdout(TDEProcess*,char*,int)),
	//	this, TQT_SLOT(receivedProcStdout(TDEProcess*, char*, int)));
	connect(m_proc, TQT_SIGNAL(receivedStderr(TDEProcess*,char*,int)),
		this, TQT_SLOT(slotReceivedProcStderr(TDEProcess*, char*, int)));

}


PluginKateXMLCheckView::~PluginKateXMLCheckView()
{
	delete m_proc;
	delete m_tmp_file;
}




void PluginKateXMLCheckView::slotReceivedProcStderr(TDEProcess *, char *result, int len)
{
	m_proc_stderr += TQString::fromLocal8Bit( TQCString(result, len+1) );
}


void PluginKateXMLCheckView::slotProcExited(TDEProcess*)
{
	// FIXME: doesn't work correct the first time:
	//if( m_dockwidget->isDockBackPossible() ) {
	//	m_dockwidget->dockBack();
//	}

	kdDebug() << "slotProcExited()" << endl;
	//kdDebug() << "output: " << endl << m_proc_stderr << endl << endl;
	TQApplication::restoreOverrideCursor();
	m_tmp_file->unlink();
	clear();
	uint list_count = 0;
	uint err_count = 0;
	if( ! m_validating ) {
		// no i18n here, so we don't get an ugly English<->Non-english mixup:
		TQString msg;
		if( m_dtdname.isEmpty() ) {
			msg = "No DOCTYPE found, will only check well-formedness.";
		} else {
			msg = "'" + m_dtdname + "' not found, will only check well-formedness.";
		}
		(void)new TQListViewItem(this, TQString("1").rightJustify(4,' '), "", "", msg);
		list_count++;
	}
	if( ! m_proc_stderr.isEmpty() ) {
		TQStringList lines = TQStringList::split("\n", m_proc_stderr);
		TQListViewItem *item = 0;
		TQString linenumber, msg;
		uint line_count = 0;
		for(TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it) {
			TQString line = *it;
			line_count++;
			int semicolon_1 = line.find(':');
			int semicolon_2 = line.find(':', semicolon_1+1);
			int semicolon_3 = line.find(':', semicolon_2+2);
			int caret_pos = line.find('^');
			if( semicolon_1 != -1 && semicolon_2 != -1 && semicolon_3 != -1 ) {
				linenumber = line.mid(semicolon_1+1, semicolon_2-semicolon_1-1).stripWhiteSpace();
				linenumber = linenumber.rightJustify(6, ' ');	// for sorting numbers
				msg = line.mid(semicolon_3+1, line.length()-semicolon_3-1).stripWhiteSpace();
			} else if( caret_pos != -1 || line_count == lines.size() ) {
				// TODO: this fails if "^" occurs in the real text?!
				if( line_count == lines.size() && caret_pos == -1 ) {
					msg = msg+"\n"+line;
				}
				TQString col = TQString::number(caret_pos);
				if( col == "-1" ) {
					col = "";
				}
				err_count++;
				list_count++;
				item = new TQListViewItem(this, TQString::number(list_count).rightJustify(4,' '), linenumber, col, msg);
				item->setMultiLinesEnabled(true);
			} else {
				msg = msg+"\n"+line;
			}
		}
		sort();	// TODO?: insert in right order
	}
	if( err_count == 0 ) {
		TQString msg;
		if( m_validating ) {
			msg = "No errors found, document is valid.";	// no i18n here
		} else {
			msg = "No errors found, document is well-formed.";	// no i18n here
		}
		(void)new TQListViewItem(this, TQString::number(list_count+1).rightJustify(4,' '), "", "", msg);
	}
}


void PluginKateXMLCheckView::slotClicked(TQListViewItem *item)
{
	kdDebug() << "slotClicked" << endl;
	if( item ) {
		bool ok = true;
		uint line = item->text(1).toUInt(&ok);
		bool ok2 = true;
		uint column = item->text(2).toUInt(&ok);
		if( ok && ok2 ) {
			Kate::View *kv = win->viewManager()->activeView();
			if( ! kv ) {
				kdDebug() << "Warning (slotClicked()): no Kate::View" << endl;
				return;
			}
			kv->setCursorPositionReal(line-1, column);
		}
	}
}


void PluginKateXMLCheckView::slotUpdate()
{
	kdDebug() << "slotUpdate() (not implemented yet)" << endl;
}


bool PluginKateXMLCheckView::slotValidate()
{
	kdDebug() << "slotValidate()" << endl;

	win->toolViewManager()->showToolView (this);

	m_proc->clearArguments();
	m_proc_stderr = "";
	m_validating = false;
	m_dtdname = "";

	Kate::View *kv = win->viewManager()->activeView();
	if( ! kv ) {
		kdDebug() << "Error (slotValidate()): no Kate::View" << endl;
		return false;
	}
	if( ! kv->getDoc() ) {
		kdDebug() << "Error (slotValidate()): no kv->getDoc()" << endl;
		return false;
	}
	Kate::Document *doc = (Kate::Document*)kv->document();

	m_tmp_file = new KTempFile();
	if( m_tmp_file->status() != 0 ) {
		kdDebug() << "Error (slotValidate()): could not create '" << m_tmp_file->name() << "': " << m_tmp_file->status() << endl;
		KMessageBox::error(0, i18n("<b>Error:</b> Could not create "
			"temporary file '%1'.").arg(m_tmp_file->name()));
		delete m_tmp_file;
		m_tmp_file=0L;
		return false;
	}
	TQTextStream *s = m_tmp_file->textStream();
	*s << kv->getDoc()->text();
	bool removed = m_tmp_file->close();
	if( ! removed ) {
		kdDebug() << "Warning (slotValidate()): temp file '" << m_tmp_file->name() << "' not deleted: " << m_tmp_file->status() << endl;
	}

	TQString exe = TDEStandardDirs::findExe("xmllint");
	if( exe.isEmpty() ) {
		exe = locate("exe", "xmllint");
	}

	// use catalogs for KDE docbook:
	if( ! getenv("SGML_CATALOG_FILES") ) {
    	TDEInstance ins("katexmlcheckplugin");
		TQString catalogs;
		catalogs += ins.dirs()->findResource("data", "ksgmltools2/customization/catalog");
		catalogs += ":";
		catalogs += ins.dirs()->findResource("data", "ksgmltools2/docbook/xml-dtd-4.1.2/docbook.cat");
		kdDebug() << "catalogs: " << catalogs << endl;
		setenv("SGML_CATALOG_FILES", TQFile::encodeName( catalogs ).data(), 1);
	}
	//kdDebug() << "**catalogs: " << getenv("SGML_CATALOG_FILES") << endl;

	*m_proc << exe << "--catalogs" << "--noout";

	// heuristic: assume that the doctype is in the first 10,000 bytes:
	TQString text_start = kv->getDoc()->text().left(10000);
	// remove comments before looking for doctype (as a doctype might be commented out
	// and needs to be ignored then):
	TQRegExp re("<!--.*-->");
	re.setMinimal(true);
	text_start.replace(re, "");
	TQRegExp re_doctype("<!DOCTYPE\\s+(.*)\\s+(?:PUBLIC\\s+[\"'].*[\"']\\s+[\"'](.*)[\"']|SYSTEM\\s+[\"'](.*)[\"'])", false);
	re_doctype.setMinimal(true);

	if( re_doctype.search(text_start) != -1 ) {
		TQString dtdname;
		if( ! re_doctype.cap(2).isEmpty() ) {
			dtdname = re_doctype.cap(2);
		} else {
			dtdname = re_doctype.cap(3);
		}
		if( !dtdname.startsWith("http:") ) {		// todo: u_dtd.isLocalFile() doesn't work :-(
			// a local DTD is used
			m_validating = true;
			*m_proc << "--valid";
		} else {
			m_validating = true;
			*m_proc << "--valid";
		}
	} else if( text_start.find("<!DOCTYPE") != -1 ) {
		// DTD is inside the XML file
		m_validating = true;
		*m_proc << "--valid";
	}
	*m_proc << m_tmp_file->name();

	if( ! m_proc->start(TDEProcess::NotifyOnExit, TDEProcess::AllOutput) ) {
		KMessageBox::error(0, i18n("<b>Error:</b> Failed to execute xmllint. Please make "
			"sure that xmllint is installed. It is part of libxml2."));
		return false;
	}
	TQApplication::setOverrideCursor(KCursor::waitCursor());
	return true;
}