summaryrefslogtreecommitdiffstats
path: root/src/softwareimporters.cpp
blob: ac8c043ae34ca7ad11add947f43fbfc4474a6015 (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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
/***************************************************************************
 *   Copyright (C) 2003 by Sébastien Laoût                                 *
 *   slaout@linux62.org                                                    *
 *                                                                         *
 *   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.             *
 ***************************************************************************/

#include <tqstring.h>
#include <tqdir.h>
#include <kstandarddirs.h>
#include <tdelocale.h>
#include <tdefiledialog.h>
#include <tqptrstack.h>
#include <tqlayout.h>
#include <tqvbuttongroup.h>
#include <tqradiobutton.h>
#include <tdemessagebox.h>
#include <tqtextedit.h>

#include "softwareimporters.h"
#include "basket.h"
#include "basketfactory.h"
#include "notefactory.h"
#include "global.h"
#include "bnpview.h"
#include "xmlwork.h"
#include "tools.h"

/** class TreeImportDialog: */

TreeImportDialog::TreeImportDialog(TQWidget *parent)
 : KDialogBase(KDialogBase::Swallow, i18n("Import Hierarchy"), KDialogBase::Ok | KDialogBase::Cancel,
               KDialogBase::Ok, parent, /*name=*/"ImportHierarchy", /*modal=*/true, /*separator=*/false)
{
	TQWidget *page = new TQWidget(this);
	TQVBoxLayout *topLayout = new TQVBoxLayout(page, /*margin=*/0, spacingHint());

	m_choices = new TQVButtonGroup(i18n("How to Import the Notes?"), page);
	new TQRadioButton(i18n("&Keep original hierarchy (all notes in separate baskets)"), m_choices);
	new TQRadioButton(i18n("&First level notes in separate baskets"),                   m_choices);
	new TQRadioButton(i18n("&All notes in one basket"),                                 m_choices);
	m_choices->setButton(0);
	topLayout->addWidget(m_choices);
	topLayout->addStretch(10);

	setMainWidget(page);
}

TreeImportDialog::~TreeImportDialog()
{
}

int TreeImportDialog::choice()
{
	return m_choices->selectedId();
}

/** class TextFileImportDialog: */

TextFileImportDialog::TextFileImportDialog(TQWidget *parent)
 : KDialogBase(KDialogBase::Swallow, i18n("Import Text File"), KDialogBase::Ok | KDialogBase::Cancel,
               KDialogBase::Ok, parent, /*name=*/"ImportTextFile", /*modal=*/true, /*separator=*/false)
{
	TQWidget *page = new TQWidget(this);
	TQVBoxLayout *topLayout = new TQVBoxLayout(page, /*margin=*/0, spacingHint());

	m_choices = new TQVButtonGroup(i18n("Format of the Text File"), page);
	new TQRadioButton(i18n("Notes separated by an &empty line"), m_choices);
	new TQRadioButton(i18n("One &note per line"),                m_choices);
	new TQRadioButton(i18n("Notes begin with a &dash (-)"),      m_choices);
	new TQRadioButton(i18n("Notes begin with a &star (*)"),      m_choices);
	m_anotherSeparator = new TQRadioButton(i18n("&Use another separator:"),           m_choices);

	TQWidget *indentedTextEdit = new TQWidget(m_choices);
	TQHBoxLayout *hLayout = new TQHBoxLayout(indentedTextEdit, /*margin=*/0, spacingHint());
	hLayout->addSpacing(20);
	m_customSeparator = new TQTextEdit(indentedTextEdit);
	m_customSeparator->setTextFormat(TQt::PlainText);
	hLayout->addWidget(m_customSeparator);
	m_choices->insertChild(TQT_TQOBJECT(indentedTextEdit));

	new TQRadioButton(i18n("&All in one note"),                  m_choices);
	m_choices->setButton(0);
	topLayout->addWidget(m_choices);

	connect( m_customSeparator, TQT_SIGNAL(textChanged()), this, TQT_SLOT(customSeparatorChanged()) );

	setMainWidget(page);
}

TextFileImportDialog::~TextFileImportDialog()
{
}

TQString TextFileImportDialog::separator()
{
	switch (m_choices->selectedId()) {
		default:
		case 0: return "\n\n";
		case 1: return "\n";
		case 2: return "\n-";
		case 3: return "\n*";
		case 4: return m_customSeparator->text();
		case 5: return "";
	}
}

void TextFileImportDialog::customSeparatorChanged()
{
	if (!m_anotherSeparator->isOn())
		m_anotherSeparator->toggle();
}

/** namespace SoftwareImporters: */

TQString SoftwareImporters::fromICS(const TQString &ics)
{
	TQString result = ics;

	// Remove escaped '\' characters and append the text to the body
	int pos = 0;
	while ( (pos = result.find('\\', pos)) != -1 ) {
		if ((uint)pos == result.length() - 1) // End of string
			break;
		if (result[pos+1] == 'n') {
			result.replace(pos, 2, '\n');
		} else if (result[pos+1] == 'r') {
			result.replace(pos, 2, '\r');
		} else if (result[pos+1] == 't') {
			result.replace(pos, 2, '\t');
		} else if (result[pos] == '\\') {
			result.remove(pos, 1); // Take care of "\\", "\,", "\;" and other escaped characters I haven't noticed
			++pos;
		}
	}

	return result;
}

TQString SoftwareImporters::fromTomboy(TQString tomboy)
{
	// The first line is the note title, and we already have it, so we remove it (yes, that's pretty stupid to duplicate it in the content...):
	tomboy = tomboy.mid(tomboy.find("\n")).stripWhiteSpace();

	// Font styles and decorations:
	tomboy.replace("<bold>",           "<b>");
	tomboy.replace("</bold>",          "</b>");
	tomboy.replace("<italic>",         "<i>");
	tomboy.replace("</italic>",        "</i>");
	tomboy.replace("<strikethrough>",  "<span style='text-decoration: line-through'>");
	tomboy.replace("</strikethrough>", "</span>");

	// Highlight not supported by TQTextEdit:
	tomboy.replace("<highlight>",      "<span style='color:#ff0080'>");
	tomboy.replace("</highlight>",     "</span>");

	// Font sizes:
	tomboy.replace("<size:small>",     "<span style='font-size: 7pt'>");
	tomboy.replace("</size:small>",    "</span>");
	tomboy.replace("<size:large>",     "<span style='font-size: 16pt'>");
	tomboy.replace("</size:large>",    "</span>");
	tomboy.replace("<size:huge>",      "<span style='font-size: 20pt'>");
	tomboy.replace("</size:huge>",     "</span>");

	// Internal links to other notes aren't supported yet by BasKet Note Pads:
	tomboy.replace("<link:internal>",  "");
	tomboy.replace("</link:internal>", "");

	// In the Tomboy file, new lines are "\n" and not "<br>":
	tomboy.replace("\n", "<br>\n");

	// Preserve consecutive spaces:
	return "<html><head><meta name=\"qrichtext\" content=\"1\" /></head><body>" + tomboy + "</body></html>";
}

Note* SoftwareImporters::insertTitledNote(Basket *parent, const TQString &title, const TQString &content, TQt::TextFormat format/* = TQt::PlainText*/, Note *parentNote/* = 0*/)
{
	Note *nGroup = new Note(parent);

	Note *nTitle = NoteFactory::createNoteText(title, parent);
	nTitle->addState(Tag::stateForId("title"));

	Note *nContent;
	if (format == TQt::PlainText)
		nContent = NoteFactory::createNoteText(content, parent);
	else
		nContent = NoteFactory::createNoteHtml(content, parent);

	if (parentNote == 0)
		parentNote = parent->firstNote(); // In the first column!
	parent->insertNote(nGroup,   parentNote, Note::BottomColumn, TQPoint(), /*animate=*/false);
	parent->insertNote(nTitle,   nGroup,     Note::BottomColumn, TQPoint(), /*animate=*/false);
	parent->insertNote(nContent, nTitle,     Note::BottomInsert, TQPoint(), /*animate=*/false);

	return nGroup;
}

void SoftwareImporters::finishImport(Basket *basket)
{
	// Unselect the last inserted group:
	basket->unselectAll();

	// Focus the FIRST note (the last inserted note is currently focused!):
	basket->setFocusedNote(basket->firstNoteShownInStack());

	// Relayout every notes at theire new place and simulate a load animation (because already loaded just after the creation).
	// Without a relayouting, notes on the bottom would comes from the top (because they were inserted on top) and clutter the animation load:
	basket->relayoutNotes(/*animate=*/false);
	basket->animateLoad();
	basket->save();
}



void SoftwareImporters::importKJots()
{
	TQString dirPath = locateLocal("appdata","") + "/../kjots/"; // I think the assumption is good
	TQDir dir(dirPath, TQString(), TQDir::Name | TQDir::IgnoreCase, TQDir::Files | TQDir::NoSymLinks);

	TQStringList list = dir.entryList();
	if (list.isEmpty())
		return;

	BasketFactory::newBasket(/*icon=*/"kjots", /*name=*/i18n("From KJots"), /*backgroundImage=*/"", /*backgroundColor=*/TQColor(), /*textColor=*/TQColor(), /*templateName=*/"1column", /*createIn=*/0);
	Basket *kjotsBasket = Global::bnpView->currentBasket();

	for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it ) { // For each file
		TQFile file(dirPath + *it);
		if (file.open(IO_ReadOnly)) {
			TQTextStream stream(&file);
			stream.setEncoding(TQTextStream::Locale);
			TQString buf = stream.readLine();

			// IT IS A NOTEBOOK FILE, AT THE VERION 0.6.x and older:
			if ( !buf.isNull() && buf.left(9) == "\\NewEntry") {

				// First create a basket for it:
				BasketFactory::newBasket(/*icon=*/"kjots", /*name=*/KURL(file.name()).fileName(), /*backgroundImage=*/"", /*backgroundColor=*/TQColor(), /*textColor=*/TQColor(), /*templateName=*/"1column", /*createIn=*/kjotsBasket);
				Basket *basket = Global::bnpView->currentBasket();
				basket->load();

				TQString title, body;
				bool haveAnEntry = false;
				while (1) {
					if (buf.left(9) == "\\NewEntry") {
						if (haveAnEntry) // Do not add note the first time
							insertTitledNote(basket, title, Tools::stripEndWhiteSpaces(body));
						title = buf.mid(10, buf.length());          // Problem : basket will be saved
						body = ""; // New note will then be created //  EACH time a note is imported
						haveAnEntry = true;
					} else if (buf.left(3) != "\\ID") { // Don't care of the ID
						// Remove escaped '\' characters and append the text to the body
						int pos = 0;
						while ( (pos = buf.find('\\', pos)) != -1 )
							if (buf[++pos] == '\\')
								buf.remove(pos, 1);
						body.append(buf + "\n");
					}
					buf = stream.readLine();
					if (buf.isNull()) // OEF
						break;
				}
				// Add the ending note (there isn't any other "\\NewEntry" to do it):
				if (haveAnEntry)
					insertTitledNote(basket, title, Tools::stripEndWhiteSpaces(body));
				finishImport(basket);

			// IT IS A NOTEBOOK XML FILE, AT THE VERION 0.7.0 and later:
			} else if ( (*it).endsWith(".book") /*&& !buf.isNull() && (buf.left(2) == "<!" / *<!DOCTYPE...* / || buf.left(2) == "<?" / *<?xml...* /)*/) {

				TQDomDocument *doc = XMLWork::openFile("KJots", dirPath + *it);
				if (doc == 0)
					continue;

				TQString bookTitle = XMLWork::getElementText(doc->documentElement(), "KJotsBook/Title");

				// First create a basket for it:
				BasketFactory::newBasket(/*icon=*/"kjots", /*name=*/bookTitle, /*backgroundImage=*/"", /*backgroundColor=*/TQColor(), /*textColor=*/TQColor(), /*templateName=*/"1column", /*createIn=*/kjotsBasket);
				Basket *basket = Global::bnpView->currentBasket();
				basket->load();

				TQDomElement docElem = XMLWork::getElement(doc->documentElement(), "KJotsBook");
				for ( TQDomNode n = docElem.firstChild(); !n.isNull(); n = n.nextSibling() ) {
					TQDomElement e = n.toElement();
					if ( (!e.isNull()) && e.tagName() == "KJotsPage" )
						insertTitledNote(basket, XMLWork::getElementText(e, "Title"), XMLWork::getElementText(e, "Text"));
				}
				finishImport(basket);

			}

			file.close();
		}
	}
}

void SoftwareImporters::importKNotes()
{
	TQString dirPath = locateLocal("appdata","") + "/../knotes/"; // I thing the assumption is good
	TQDir dir(dirPath, TQString(), TQDir::Name | TQDir::IgnoreCase, TQDir::Files | TQDir::NoSymLinks);

	TQStringList list = dir.entryList();
	for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it ) { // For each file
		if ( ! (*it).endsWith(".ics") ) // Don't process *.ics~ and otehr files
			continue;
		TQFile file(dirPath + *it);
		if (file.open(IO_ReadOnly)) {
			TQTextStream stream(&file);
			stream.setEncoding(TQTextStream::UnicodeUTF8);

			// First create a basket for it:
			BasketFactory::newBasket(/*icon=*/"knotes", /*name=*/i18n("From KNotes"), /*backgroundImage=*/"", /*backgroundColor=*/TQColor(), /*textColor=*/TQColor(), /*templateName=*/"1column", /*createIn=*/0);
			Basket *basket = Global::bnpView->currentBasket();
			basket->load();

			bool inVJournal    = false;
			bool inDescription = false;
			bool isRichText    = false;
			TQString title, body;
			TQString buf;
			while (1) {
				buf = stream.readLine();
				if (buf.isNull()) // OEF
					break;

				if ( !buf.isNull() && buf == "BEGIN:VJOURNAL") {
					inVJournal = true;
				} else if (inVJournal && buf.startsWith("SUMMARY:")) {
					title = buf.mid(8, buf.length());
				} else if (inVJournal && buf.startsWith("DESCRIPTION:")) {
					body = buf.mid(12, buf.length());
					inDescription = true;
				} else if (inDescription && buf.startsWith(" ")) {
					body += buf.mid(1, buf.length());
				} else if (buf.startsWith("X-TDE-KNotes-RichText:")) {
					isRichText = XMLWork::trueOrFalse(buf.mid(22, buf.length() - 22).stripWhiteSpace(), "false");
				} else if (buf == "END:VJOURNAL") {
					insertTitledNote(basket, fromICS(title), fromICS(body), (isRichText ? TQt::RichText : TQt::PlainText));
					inVJournal    = false;
					inDescription = false;
					isRichText    = false;
					title = "";
					body = "";
				} else
					inDescription = false;
			}

			// Bouh : duplicate code
			// In case of unvalide ICAL file!
			if ( ! body.isEmpty() ) // Add the ending note
				insertTitledNote(basket, fromICS(title), fromICS(body), (isRichText ? TQt::RichText : TQt::PlainText));
			file.close();
			finishImport(basket);
		}
	}
}

void SoftwareImporters::importStickyNotes()
{
	// Sticky Notes file is usually located in ~/.gnome2/stickynotes_applet
	// We will search all directories in "~/" that contain "gnome" in the name,
	// and will search for "stickynotes_applet" file (that should be XML file with <stickynotes> root.
	TQDir dir(TQDir::home().absPath(), TQString(), TQDir::Name | TQDir::IgnoreCase,
	         TQDir::Dirs | TQDir::NoSymLinks | TQDir::Hidden);
	TQStringList founds;

	TQStringList list = dir.entryList();
	for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it ) { // For each folder
		if ( (*it).contains("gnome", false) ) {
			TQString fullPath = TQDir::home().absPath() + "/" + (*it) + "/stickynotes_applet";
			if (dir.exists(fullPath))
				founds += fullPath;
		}
	}

	for ( TQStringList::Iterator it = founds.begin(); it != founds.end(); ++it ) { // For each file
		TQFile file(*it);
		TQDomDocument *doc = XMLWork::openFile("stickynotes", *it);
		if (doc == 0)
			continue;

		// First create a basket for it:
		BasketFactory::newBasket(/*icon=*/"gnome", /*name=*/i18n("From Sticky Notes"), /*backgroundImage=*/"", /*backgroundColor=*/TQColor(), /*textColor=*/TQColor(), /*templateName=*/"1column", /*createIn=*/0);
		Basket *basket = Global::bnpView->currentBasket();
		basket->load();

		TQDomElement docElem = doc->documentElement();
		for ( TQDomNode n = docElem.firstChild(); !n.isNull(); n = n.nextSibling() ) {
			TQDomElement e = n.toElement();
			if ( (!e.isNull()) && e.tagName() == "note" )
				insertTitledNote(basket, e.attribute("title"), e.text());
		}
		finishImport(basket);
	}
}



// TODO: FIXME: Code duplicated from notecontent.cpp but with UTF-8 encoding.
// TODO: FIXME: Later, merge!
TQString loadUtf8FileToString(const TQString &fileName)
{
	TQFile file(fileName);
	if (file.open(IO_ReadOnly)) {
		TQTextStream stream(&file);
		stream.setEncoding(TQTextStream::UnicodeUTF8);
		TQString text;
		text = stream.read();
		file.close();
		return text;
	} else
		return "";
}


void SoftwareImporters::importTomboy()
{
	TQString dirPath = TQDir::home().absPath() + "/.tomboy/"; // I thing the assumption is good
	TQDir dir(dirPath, TQString(), TQDir::Name | TQDir::IgnoreCase, TQDir::Files | TQDir::NoSymLinks);

	Basket *basket = 0; // Create the basket ONLY if we found at least one note to add!

	TQStringList list = dir.entryList();
	for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it ) { // For each file
		if ( ! (*it).endsWith(".note") )
			continue;
		TQDomDocument *doc = XMLWork::openFile("note", dirPath + *it);
		if (doc == 0)
			continue;

		if (basket == 0) {
			// First create a basket for it:
			BasketFactory::newBasket(/*icon=*/"tomboy", /*name=*/i18n("From Tomboy"), /*backgroundImage=*/"", /*backgroundColor=*/TQColor(), /*textColor=*/TQColor(), /*templateName=*/"1column", /*createIn=*/0);
			basket = Global::bnpView->currentBasket();
			basket->load();
		}

		TQDomElement docElem = doc->documentElement();
		TQString title = XMLWork::getElementText(docElem, "title");

		// DOES NOT REALLY WORKS:
		//TQDomElement contentElement = XMLWork::getElement(docElem, "text/note-content");
		//TQString content = XMLWork::innerXml(contentElement);

		// Isolate "<note-content version="0.1">CONTENT</note-content>"!
		TQString xml = loadUtf8FileToString(dirPath + *it);
		xml = xml.mid(xml.find("<note-content "));
		xml = xml.mid(xml.find(">") + 1);
		xml = xml.mid(0, xml.find("</note-content>"));

		if (!title.isEmpty() && !/*content*/xml.isEmpty())
			insertTitledNote(basket, title, fromTomboy(xml/*content*/), TQt::RichText);
	}

	if (basket)
		finishImport(basket);
}

void SoftwareImporters::importTextFile()
{
	TQString fileName = KFileDialog::getOpenFileName(":ImportTextFile",  "*|All files");
	if (fileName.isEmpty())
		return;

	TextFileImportDialog dialog;
	if (dialog.exec() == TQDialog::Rejected)
		return;
	TQString separator = dialog.separator();

	TQFile file(fileName);
	if (file.open(IO_ReadOnly)) {
		TQTextStream stream(&file);
		stream.setEncoding(TQTextStream::Locale);
		TQString content = stream.read();
		TQStringList list = (separator.isEmpty()
			? TQStringList(content)
			: TQStringList::split(separator, content, /*allowEmptyEntries=*/false)
		);

		// First create a basket for it:
		TQString title = i18n("From TextFile.txt", "From %1").arg(KURL(fileName).fileName());
		BasketFactory::newBasket(/*icon=*/"text-plain", title, /*backgroundImage=*/"", /*backgroundColor=*/TQColor(), /*textColor=*/TQColor(), /*templateName=*/"1column", /*createIn=*/0);
		Basket *basket = Global::bnpView->currentBasket();
		basket->load();

		// Import every notes:
		for (TQStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
			Note *note = NoteFactory::createNoteFromText((*it).stripWhiteSpace(), basket);
			basket->insertNote(note, basket->firstNote(), Note::BottomColumn, TQPoint(), /*animate=*/false);
		}

		// Finish the export:
		finishImport(basket);
	}
}

/** @author Petri Damsten <petri.damsten@iki.fi>
  */
void SoftwareImporters::importKnowIt()
{
	KURL url = KFileDialog::getOpenURL(":ImportKnowIt",
	                                   "*.kno|KnowIt files\n*|All files");
	if (!url.isEmpty())
	{
		TQFile file(url.path());
		TQFileInfo info(url.path());
		Basket* basket = 0;
		TQPtrStack<Basket> baskets;
		TQString text;
		int hierarchy = 0;

		TreeImportDialog dialog;
		if (dialog.exec() == TQDialog::Rejected)
			return;

		hierarchy = dialog.choice();

		BasketFactory::newBasket(/*icon=*/"knowit",
		                         /*name=*/info.baseName(),
		                         /*backgroundImage=*/"",
		                         /*backgroundColor=*/TQColor(),
		                         /*textColor=*/TQColor(),
		                         /*templateName=*/"1column",
		                         /*createIn=*/0);
		basket = Global::bnpView->currentBasket();
		basket->load();
		baskets.push(basket);

		if(file.open(IO_ReadOnly))
		{
			TQTextStream stream(&file);
			uint level = 0;
			TQString name;
			TQString line;
			TQStringList links;
			TQStringList descriptions;

			stream.setEncoding(TQTextStream::UnicodeUTF8);
			while(1)
			{
				line = stream.readLine();

				if(line.startsWith("\\NewEntry") ||
				   line.startsWith("\\CurrentEntry") || stream.atEnd())
				{
					while(level + 1 < baskets.count())
						baskets.pop();
					if(level + 1 > baskets.count())
						baskets.push(basket);

					if(!name.isEmpty())
					{
						if((level == 0 && hierarchy == 1) ||
							(hierarchy == 0))
						{
							BasketFactory::newBasket(/*icon=*/"knowit",
							                         /*name=*/name,
							                         /*backgroundImage=*/"",
							                         /*backgroundColor=*/TQColor(),
							                         /*textColor=*/TQColor(),
							                         /*templateName=*/"1column",
							                         /*createIn=*/baskets.top());
							basket = Global::bnpView->currentBasket();
							basket->load();
						}

						if(!text.stripWhiteSpace().isEmpty() ||
							hierarchy == 2 ||
							(hierarchy == 1 && level > 0))
						{
							insertTitledNote(basket, name, text, TQt::RichText);
						}
						for(uint j = 0; j < links.count(); ++j)
						{
							Note* link;
							if(descriptions.count() < j+1 || descriptions[j].isEmpty())
								link = NoteFactory::createNoteLink(links[j], basket);
							else
								link = NoteFactory::createNoteLink(links[j],
							descriptions[j], basket);
							basket->insertCreatedNote(link);
						}
						finishImport(basket);
					}
					if(stream.atEnd())
						break;

					int i = line.find("Entry") + 6;
					int n = line.find(' ', i);
					level = line.mid(i, n - i).toInt();
					name = line.mid(n+1);
					text = "";
					links.clear();
					descriptions.clear();
				}
				else if(line.startsWith("\\Link"))
				{
					links.append(line.mid(6));
				}
				else if(line.startsWith("\\Descr"))
				{
					while(descriptions.count() < links.count() - 1)
						descriptions.append("");
					descriptions.append(line.mid(7));
				}
				else
				{
					text += line + "\n";
				}
			}
			file.close();
		}
	}
}

void SoftwareImporters::importTuxCards()
{
	TQString fileName = KFileDialog::getOpenFileName(":ImportTuxCards",  "*|All files");
	if (fileName.isEmpty())
		return;

	TreeImportDialog dialog;
	if (dialog.exec() == TQDialog::Rejected)
		return;

	int hierarchy = dialog.choice();

	TQDomDocument *document = XMLWork::openFile("tuxcards_data_file"/*"InformationCollection"*/, fileName);
	if (document == 0) {
		KMessageBox::error(0, i18n("Can not import that file. It is either corrupted or not a TuxCards file."), i18n("Bad File Format"));
		return;
	}

	TQDomElement collection = document->documentElement();
	int remainingHierarchy = (hierarchy == 0 ? 65000 : 3 - hierarchy);
	importTuxCardsNode(collection, /*parentBasket=*/0, /*parentNote=*/0, remainingHierarchy);
}

// TODO: <InformationElement isOpen="true" isEncripted="false"

void SoftwareImporters::importTuxCardsNode(const TQDomElement &element, Basket *parentBasket, Note *parentNote, int remainingHierarchy)
{
	for (TQDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling()) {
		TQDomElement e = n.toElement();
		if (e.isNull() || e.tagName() != "InformationElement") // Cannot handle that!
			continue;

		TQString icon        = e.attribute("iconFileName");
		TQString name        = XMLWork::getElementText(e, "Description");
		TQString content     = XMLWork::getElementText(e, "Information");
		bool    isRichText  = (e.attribute("informationFormat") == "RTF");
		bool    isEncrypted = (e.attribute("isEncripted") == "true");
		if (icon.isEmpty() || icon == "none")
			icon = "tuxcards";
		Note *nContent;

		if (isEncrypted) {
			KMessageBox::information(0, i18n("A note is encrypted. The importer does not yet support encrypted notes. Please remove the encryption with TuxCards and re-import the file."), i18n("Encrypted Notes not Supported Yet"));
			isRichText = true;
			content = i18n("<font color='red'><b>Encrypted note.</b><br>The importer do not support encrypted notes yet. Please remove the encryption with TuxCards and re-import the file.</font>");
		}

		if (remainingHierarchy > 0) {
			BasketFactory::newBasket(icon, name, /*backgroundImage=*/"", /*backgroundColor=*/TQColor(), /*textColor=*/TQColor(), /*templateName=*/"1column", parentBasket);
			Basket *basket = Global::bnpView->currentBasket();
			basket->load();

			if (isRichText)
				nContent = NoteFactory::createNoteHtml(content, basket);
			else
				nContent = NoteFactory::createNoteText(content, basket);
			basket->insertNote(nContent, basket->firstNote(), Note::BottomColumn, TQPoint(), /*animate=*/false);

			importTuxCardsNode(e, basket, 0, remainingHierarchy - 1);
			finishImport(basket);
		} else {
			Note *nGroup = insertTitledNote(parentBasket, name, content, (isRichText ? TQt::RichText : TQt::PlainText), parentNote);
			importTuxCardsNode(e, parentBasket, nGroup, remainingHierarchy - 1);
		}
	}
}

#include "softwareimporters.moc"