summaryrefslogtreecommitdiff
path: root/quacker/letterbox.cpp
blob: 399b73aa38f17275e5173f5ea523ae4119e28176 (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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
/*
 *  Quackle -- Crossword game artificial intelligence and analysis tool
 *  Copyright (C) 2005-2014 Jason Katz-Brown and John O'Laughlin.
 *
 *  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 3 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, see <http://www.gnu.org/licenses/>.
 */

#include <QtGui>

#include <quackleio/dictfactory.h>
#include <quackleio/util.h>

#include "letterbox.h"
#include "customqsettings.h"
#include "quackersettings.h"
#include "letterboxsettings.h"
#include "lister.h"

Letterbox *Letterbox::m_self = 0;
Letterbox *Letterbox::self()
{
	return m_self;
}

Letterbox::Letterbox(QWidget *parent, QAction *preferencesAction, ListerDialog *listerDialog)
	: QMainWindow(parent), m_initializationChuu(false), m_modified(false), m_mistakeMade(false), m_listerDialog(listerDialog), m_pauseMs(0), m_keystrokes(0), m_numberIterator(0), m_preferencesAction(preferencesAction)
{
	m_self = this;

	createWidgets();
	createMenu();
	loadSettings();

	setCaption(tr("No List"));

	QTimer::singleShot(0, this, SLOT(finishInitialization()));
}

Letterbox::~Letterbox()
{
	saveSettings();
}

void Letterbox::closeEvent(QCloseEvent *closeEvent)
{
	closeEvent->setAccepted(tryToClose());
}

bool Letterbox::tryToClose()
{
	pause(true);

	if (m_modified)
	{
		switch (askToSave())
		{
		case 0:
			qApp->processEvents();
			writeFile();

			// fall through

		case 1:
			return true;

		case 2:
			return false;
		}
	}

	return true;
}

void Letterbox::finishInitialization()
{
	// ensure no dangling iterators
	m_clueResultsIterator = m_clueResults.begin();
	m_answersIterator = m_answers.begin();
	m_queryIterator = m_list.begin();	

	m_timer = new QTimer(this);
	connect(m_timer, SIGNAL(timeout()), this, SLOT(timeout()));

	m_clueResults.clear();

	loadFile();

	if (m_filename.isEmpty())
	{
		statusBar()->showMessage(tr("[Paused]") + QString(" ") + tr("Enjoy your letterboxings."));
		loadExampleList();
	}
	else
	{
		statusBar()->showMessage(tr("[Paused]") + QString(" ") + tr("Enjoy your letterboxings on %1.").arg(m_filename.right(m_filename.length() - m_filename.lastIndexOf("/") - 1)));
	}
}

void Letterbox::open()
{
	pause(true);

	if (m_modified)
	{
		switch (askToSave())
		{
		case 0:
			writeFile();

		case 1:
			break;

		case 2:
			return;
		}
	}
	
	QString defaultFilter = defaultStudyListFileFilter();
	QString filename = QFileDialog::getOpenFileName(this, tr("Choose Letterbox file to open"), getInitialDirectory(), studyListFileFilters(), &defaultFilter);
	if (!filename.isEmpty())
	{
		setInitialDirectory(filename);
		m_filename = filename;
		loadFile();
		saveSettings();
	}
}

void Letterbox::openParticularFile(const QString &filename)
{
	if (!filename.isEmpty())
	{
		if (m_modified)
		{
			switch (askToSave())
			{
				case 0:
					writeFile();

				case 1:
					break;

				case 2:
					return;
			}
		}

		m_filename = filename;
		loadFile();
	}
}

void Letterbox::setCaption(const QString &text)
{
	if (!text.isNull())
		m_ourCaption = text;

	setWindowTitle(QString("%1[*] - Quackle Letterbox").arg(m_ourCaption));
}

void Letterbox::setModified(bool modified)
{
	m_modified = modified;
	setWindowModified(m_modified);
}

bool Letterbox::dictCheck()
{
	if (!QuackleIO::DictFactory::querier()->isLoaded())
	{
		QMessageBox::critical(this, tr("No Dictionary Loaded - Quackle Letterbox"), tr("Please open a dictionary with Settings->Set Dictionary."));
		return false;
	}

	return true;
}

int Letterbox::askToSave()
{
	return QMessageBox::warning(this, tr("Unsaved Results - Quackle Letterbox"), tr("There are unsaved results in the current Letterbox list. Save them?"), tr("&Save"), tr("&Discard"), tr("&Cancel"), 0, 2);
}

void Letterbox::generateList()
{
	pause(true);

	if (m_listerDialog)
	{
		m_listerDialog->show();
		m_listerDialog->raise();
	}
}

void Letterbox::loadFile()
{
	if (m_filename.isEmpty())
		return;

	QString filename(m_filename.right(m_filename.length() - m_filename.lastIndexOf("/") - 1));
	statusBar()->showMessage(tr("Loading %1...").arg(filename));
	qApp->processEvents();
	
	m_list.clear();
	m_answers.clear();
	m_clueResults.clear();

	QFile file(m_filename);
	if (!file.exists())
	{
		QMessageBox::critical(this, tr("Error Loading Letterbox List - Quackle Letterbox"), tr("Filename %1 does not exist").arg(m_filename));
		return;
	}

	if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		QMessageBox::critical(this, tr("Error Loading Letterbox List - Quackle Letterbox"), tr("%1 cannot be opened.").arg(filename));
		return;
	}

	int startAt = 0;

	QTextStream stream(&file);
	QString line;

	m_initializationChuu = true;

	bool firstLine = true;

	while (!stream.atEnd())
	{
		line = stream.readLine().trimmed().toUpper();

		if (firstLine)
		{
			if (line.left(10) == "\" RESUME: ")
				startAt = line.right(line.length() - 10).toInt();

			firstLine = false;
		}

		line.remove('#');

		QString letters = line;
		QString comment;

		int quoteMarkIndex = line.indexOf("\"");
		if (quoteMarkIndex >= 0)
		{
			letters = line.left(quoteMarkIndex).trimmed();
			comment = line.right(line.length() - quoteMarkIndex - 1).trimmed();
		}

		if (letters.isEmpty())
			continue;

		m_list += letters;

		m_clueResults.append(parseComment(comment));
		m_clueResults.last().clue = clueFor(letters);
	}

	file.close();

	if (!dictCheck())
		return;

	jumpTo(startAt);

	statusBar()->showMessage(tr("Loaded list `%1' of length %2.").arg(filename).arg(m_clueResults.count()));
	setCaption(filename);

	m_initializationChuu = false;
	setModified(false);

	prepareQuiz();
	pause(true);
}

void Letterbox::loadExampleList()
{
	// TODO; load an interesting list, like sixes in playability order
}

void Letterbox::writeFile()
{
	outputResults();

	setModified(false);
	statusBar()->showMessage(tr("Saved results to file."));
}

void Letterbox::jumpTo()
{
	pause(true);

	bool ok;
	int index = QInputDialog::getInteger(this, tr("Jump to word - Quackle Letterbox"), tr("Index to which to jump:"), m_numberIterator + 1, 1, m_clueResults.count(), 1, &ok);
	if (ok)
	{
		jumpTo(index);
	}

	prepareQuiz();
	pause(true);
}

void Letterbox::jumpTo(int index)
{
	if (m_numberIterator != index)
		setModified(true);

	m_numberIterator = index;

	if (index >= m_clueResults.size())
	{
		m_answersIterator = m_answers.end();
		m_clueResultsIterator = m_clueResults.end();
		m_queryIterator = m_list.end();
		return;
	}

	while (m_answers.count() <= m_numberIterator)
	{
		m_answers.append(answersFor(m_list.at(m_answers.count())));
		m_clueResults[m_answers.count() - 1].setWordList(m_answers.at(m_answers.count() - 1));
	}

	m_clueResultsIterator = m_clueResults.begin();
	m_answersIterator = m_answers.begin();
	for (int i = 0; i < index; ++i)
	{
		++m_clueResultsIterator;
		++m_answersIterator;
	}
	(*m_clueResultsIterator).resetStats();

	m_queryIterator = m_list.begin();
	for (int i = 0; i < index + 1; ++i)
	{
		++m_queryIterator;
	}
}

ClueResult Letterbox::parseComment(const QString &comment)
{
	if (comment.isEmpty())
		return ClueResult();

	QStringList items = comment.split(" ", QString::SkipEmptyParts);

	ClueResult ret;
		
	for (QStringList::iterator it = items.begin(); it != items.end(); ++it)
	{
		WordResult word;
		word.word = *it;

		++it;
		word.time = (*it).toInt();

		++it;
		word.keystrokes = (*it).toInt();
		word.missed = (word.time == 0);

		ret.words.append(word);
	}

	return ret;
}

void Letterbox::increment()
{
	jumpTo(m_numberIterator + 1);

    if (m_numberIterator >= m_clueResults.size())
    { 
		updateViews();
        listFinished();
		m_timer->stop();
        return;
    }

    prepareQuiz();
}   

void Letterbox::pause(bool paused)
{
	timerControl(paused);

	if (m_pauseAction->isChecked() != paused)
		m_pauseAction->setChecked(paused);

	if (!paused)
		m_lineEdit->setFocus();

	if (paused)
	{
		m_pauseTime.start();
		statusBar()->showMessage(tr("Paused on #%1 of %2 total.").arg(m_numberIterator + 1).arg(m_clueResults.count()));
	}
	else
	{
		m_pauseMs += m_pauseTime.elapsed();
		statusBar()->showMessage(tr("Resuming..."));
	}
}

void Letterbox::timerControl(bool paused)
{
	if (paused)
	{
		m_timer->stop();
	}
	else if (isInQuiz())
	{
		m_timer->setSingleShot(true);
		m_timer->start(timerLength());
	}
}

void Letterbox::markLastAsMissed()
{
	ClueResultList::iterator it(m_clueResultsIterator);
	(*(--it)).resetStats();

	if (!m_pauseAction->isChecked())
	{
		// reset clock
		timerControl(true);
		timerControl(false);
	}

	statusBar()->showMessage(tr("%1 marked as missed.").arg((*it).clue.clueString));
}

void Letterbox::skip()
{
	for (WordResultList::iterator it = (*m_clueResultsIterator).words.begin(); it != (*m_clueResultsIterator).words.end(); ++it)
	{
		(*it).missed = false;
		(*it).keystrokes = (*it).word.length();
		(*it).time = timerLength();
	}

	m_mistakeMade = false;
	increment();
}

void Letterbox::prepareQuiz()
{
	updateViews();
	
	m_submittedAnswers.clear();

	m_lineEdit->clear();

	m_mistakeMade = false;

	if (m_numberIterator == m_clueResults.count())
	{
		statusBar()->clearMessage();
		return;
	}

	m_lineEdit->setFocus();
	m_pauseAction->setChecked(false);

	statusBar()->showMessage(tr("Word #%1 of %2 total.").arg(m_numberIterator + 1).arg(m_clueResults.count()));

	timerControl(true);
	timerControl(false);

	m_time.start();
	m_keystrokes = 0;
	m_pauseMs = 0;
}

int Letterbox::timerLength()
{
	if (!isInQuiz())
		return 0;

	return LetterboxSettings::self()->msecWaitBase + LetterboxSettings::self()->msecWaitExtraPerSolution * (*m_answersIterator).count();
}

void Letterbox::listFinished()
{
	writeFile();
	statusBar()->showMessage(tr("List is finished, results saved."));
	m_timer->stop();
}

bool Letterbox::isInQuiz() const
{
    return m_clueResults.size() > 0 && m_numberIterator < m_clueResults.size();
}

void Letterbox::outputResults()
{
	QFile file(m_filename);
	 
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
	{        
		QMessageBox::critical(this, tr("Error Writing File - Quackle Letterbox"), tr("Could not open %1 for writing.").arg(m_filename));        
		return;    
	}    

	QTextStream stream(&file);

	if (m_numberIterator < m_clueResults.count())
		stream << "\" Resume: " << m_numberIterator << "\n";

	ClueResultList::iterator end = m_clueResults.end();
	QStringList::iterator listIt = m_list.begin();
    for (ClueResultList::iterator it = m_clueResults.begin(); it != end; ++it)
	{
		stream << *listIt;

		if ((*it).words.count() > 0)
		{
			stream << " \"";
			for (WordResultList::iterator word = (*it).words.begin(); word != (*it).words.end(); ++word)
				stream << " " << (*word).word << " " << (*word).time << " " << (*word).keystrokes;
		}

		stream << "\n";

		++listIt;
	}

	file.close();

	if (LetterboxSettings::self()->newMissesFile)
	{
		QString missesFilename = m_filename + QString("-misses");
		QFile missesFile(missesFilename);
		 
		if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
		{        
			QMessageBox::critical(this, tr("Error writing misses file"), tr("Could not open %1 for writing.").arg(missesFilename));        
			return;    
		}    

		QTextStream stream(&missesFile);

    	for (ClueResultList::iterator it = m_clueResults.begin(); it != m_clueResults.end(); ++it)
		{
			for (WordResultList::iterator word = (*it).words.begin(); word != (*it).words.end(); ++word)
			{
				if ((*word).time == 0)
				{
					stream << (*it).clue.clueString << "\n";
					break;
				}
			}
		}

		missesFile.close();
	}
}

int Letterbox::chewScore(const QString & /*word*/, const QString & /*steal*/)
{
	int ret = 0;

	/*
	int wordpairs[26][26];
	for (int i = 0; i < 26; i++)
		for (int j = 0; j < 26; j++)
			wordpairs[i][j] = 0;

	if ((word.length() < 2) || (steal.length() < word.length()))
		return 0;

	for (unsigned int i = 0; i < word.length() - 1; i++)
	{
		int a = word.at(i).latin1() - 'A';
		int b = word.at(i + 1).latin1() - 'A';
		if ((a >= 0) && (a < 26) && (b >= 0) && (b < 26))
			wordpairs[a][b]++;
	}

	for (unsigned int i = 0; i < steal.length() - 1; i++)
	{
		int a = steal.at(i).latin1() - 'A';
		int b = steal.at(i + 1).latin1() - 'A';
		if ((a >= 0) && (a < 26) && (b >= 0) && (b < 26))
		{	
			if (wordpairs[a][b] == 0)
				ret++;
			else
				wordpairs[a][b]--;
		}
	}

*/
	return ret;
}

void Letterbox::updateDuringQuery()
{
	update();
}

Clue Letterbox::mathClue(const QString &clue)
{
	Dict::WordList clueWords = QuackleIO::DictFactory::querier()->query(clue);
	QString word = (*clueWords.begin()).word;

	int bestChew = 0;
	QString ret;

	for (int i = 0; i < word.length(); i++)
	{
		QString query = word.left(i) + word.right(word.length() - i - 1);
		Dict::WordList words = QuackleIO::DictFactory::querier()->query(query);
		for (Dict::WordList::iterator it = words.begin(); it != words.end(); ++it)
		{
			int chew = chewScore((*it).word, word);
			if (chew > bestChew)
			{
				bestChew = chew;
				ret = (*it).word + " + " + word.at(i);
			}
		}
	}

	if (bestChew > 2)
		return Clue(ret);

	return Clue(arrangeLettersForUser(word));
}

QString Letterbox::alphagram(const QString &word) 
{
	return QuackleIO::Util::alphagram(word);
}

QString Letterbox::arrangeLettersForUser(const QString &word) 
{
	return QuackleIO::Util::arrangeLettersForUser(word);
}

Clue Letterbox::clueFor(const QString &word)
{
	if (word.isNull())
		return Clue(QString::null);

	if (LetterboxSettings::self()->mathMode)
		return mathClue(word);

	return Clue(arrangeLettersForUser(word));
}

Dict::WordList Letterbox::answersFor(const QString &word)
{
	Dict::WordList results;

	if (word.isNull())
		return results;

	// no updates during initialization of lists, but with extensions
	results = QuackleIO::DictFactory::querier()->query(word, (m_initializationChuu? Dict::Querier::None : Dict::Querier::CallUpdate) | Dict::Querier::WithExtensions);

	return results;
}

void Letterbox::mistakeDetector(const QString &text)
{
	m_keystrokes++;

	QString upperText(text.toUpper());

	if (upperText.length() == 0)
		return;

	for (Dict::WordList::iterator it = (*m_answersIterator).begin(); it != (*m_answersIterator).end(); ++it)
	{
		if (LetterboxSettings::self()->spaceComplete)
		{
			if (upperText[0] == ' ')
			{
				if (!m_submittedAnswers.contains((*it).word))
				{
					processAnswer((*it).word);
					return;
				}
			}
		}
		else
		{
			if ((*it).word.startsWith(upperText) && !m_submittedAnswers.contains((*it).word))
			{
				if (m_mistakeMade)
					statusBar()->clearMessage();

				if (LetterboxSettings::self()->autoCompleteLength > 0)  
					if (upperText.length() == LetterboxSettings::self()->autoCompleteLength)
						processAnswer((*it).word);

				return;
			}
		}
	}

	m_mistakeMade = true;	
	
	statusBar()->showMessage(tr("MISTAKE DETECTED!"), /* show for 2 seconds */ 2000);
}

void Letterbox::lineEditReturnPressed()
{
	processAnswer(m_lineEdit->text());
}

void Letterbox::processAnswer(const QString &answer)
{
	if (!isInQuiz())
		return;

	QString upperAnswer(answer.toUpper());

	if (m_submittedAnswers.contains(upperAnswer) > 0)
	{
		statusBar()->showMessage(tr("You already submitted %1.").arg(upperAnswer));
		m_lineEdit->clear();
		return;
	}

	for (WordResultList::iterator it = (*m_clueResultsIterator).words.begin(); it != (*m_clueResultsIterator).words.end(); ++it)
	{
		if ((*it).word == upperAnswer)
		{
			(*it).missed = false;
			(*it).keystrokes = m_keystrokes;
			(*it).time = m_time.elapsed() - m_pauseMs;
		}
	}

	for (Dict::WordList::iterator it = (*m_answersIterator).begin(); it != (*m_answersIterator).end(); ++it)
	{
		if ((*it).word == upperAnswer)
		{
			m_submittedAnswers.append(upperAnswer);
			m_lineEdit->clear();
			m_mistakeMade = false;

			if (m_submittedAnswers.count() >= (*m_answersIterator).count())
			{
				increment();
				return;
			}
			else
			{
				statusBar()->showMessage(tr("%1 is correct.").arg(upperAnswer));
				m_solutionsView->addSubmission(upperAnswer);
				break;
			}
		}
	}

	m_lineEdit->clear();
	m_keystrokes = 0;
	m_pauseMs = 0;
}

void Letterbox::timeout()
{
	increment();
}

void Letterbox::updateViews()
{
	m_solutionsView->setWords(m_answers.begin(), m_answersIterator);
	m_upcomingView->setWords(m_clueResultsIterator, m_clueResults.end());
}

void Letterbox::createMenu()
{
	QMenu *file = menuBar()->addMenu(tr("&File"));
	QMenu *go = menuBar()->addMenu(tr("&Go"));
	QMenu *settings = menuBar()->addMenu(tr("&Settings"));
	QMenu *help = menuBar()->addMenu(tr("&Help"));

	QAction *generateAction = new QAction(tr("&Generate new list..."), this);
	generateAction->setShortcut(tr("Ctrl+L"));
	file->addAction(generateAction);
	connect(generateAction, SIGNAL(activated()), this, SLOT(generateList()));

	QAction *openAction = new QAction(tr("&Open..."), this);
	openAction->setShortcut(tr("Ctrl+O"));
	file->addAction(openAction);
	connect(openAction, SIGNAL(activated()), this, SLOT(open()));

	QAction *saveAction = new QAction(tr("&Save"), this);
	saveAction->setShortcut(tr("Ctrl+S"));
	file->addAction(saveAction);
	connect(saveAction, SIGNAL(activated()), this, SLOT(writeFile()));

	file->addSeparator();

	QAction *printAction = new QAction(tr("&Print"), this);
	file->addAction(printAction);
	connect(printAction, SIGNAL(activated()), this, SLOT(print()));

	QAction *printStudyAction = new QAction(tr("&Print Study Sheet"), this);
	file->addAction(printStudyAction);
	connect(printStudyAction, SIGNAL(activated()), this, SLOT(printStudy()));

	file->addSeparator();

	QAction *quitAction = new QAction(tr("&Close"), this);
	quitAction->setShortcut(tr("Ctrl+W"));
	file->addAction(quitAction);
	connect(quitAction, SIGNAL(activated()), this, SLOT(close()));

	QAction *jumpAction = new QAction(tr("&Jump to..."), this);
	jumpAction->setShortcut(tr("Ctrl+J"));
	go->addAction(jumpAction);
	connect(jumpAction, SIGNAL(activated()), this, SLOT(jumpTo()));

	QAction *markAsMissedAction = new QAction(tr("Mark last as &missed"), this);
	markAsMissedAction->setShortcut(tr("Ctrl+M"));
	go->addAction(markAsMissedAction);
	connect(markAsMissedAction, SIGNAL(activated()), this, SLOT(markLastAsMissed()));

	QAction *skipAction = new QAction(tr("S&kip"), this);
	skipAction->setShortcut(tr("Ctrl+K"));
	go->addAction(skipAction);
	connect(skipAction, SIGNAL(activated()), this, SLOT(skip()));

	go->addSeparator();

	m_pauseAction = new QAction(tr("&Pause"), this);
	m_pauseAction->setShortcut(tr("Ctrl+P"));
	m_pauseAction->setCheckable(true);
	go->addAction(m_pauseAction);
	connect(m_pauseAction, SIGNAL(toggled(bool)), this, SLOT(pause(bool)));

	QAction *focusAction = new QAction(tr("&Focus entry widget"), this);
	focusAction->setShortcut(tr("Ctrl+F"));
	go->addAction(focusAction);
	connect(focusAction, SIGNAL(activated()), m_lineEdit, SLOT(setFocus()));

	settings->addAction(m_preferencesAction);

	settings->addSeparator();

	QAction *aboutAction = new QAction(tr("&About Letterbox"), this);
	help->addAction(aboutAction);
	connect(aboutAction, SIGNAL(activated()), this, SLOT(about()));
}

void Letterbox::createWidgets()
{
	QWidget *centralWidget = new QWidget(this);
	QVBoxLayout *centralLayout = new QVBoxLayout(centralWidget);

	setCentralWidget(centralWidget);

	WordView *solutionsView = new WordView(centralWidget);
	WordView *upcomingView = new WordView(centralWidget);

	m_lineEdit = new QLineEdit(centralWidget);
	m_lineEdit->setAlignment(Qt::AlignHCenter);
	m_lineEdit->setValidator(new InputValidator(m_lineEdit));
	connect(m_lineEdit, SIGNAL(returnPressed()), this, SLOT(lineEditReturnPressed()));
	connect(m_lineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(mistakeDetector(const QString &)));

	centralLayout->addWidget(solutionsView);
	centralLayout->addWidget(m_lineEdit);
	centralLayout->addWidget(upcomingView);

	centralLayout->setStretchFactor(solutionsView, 3);

	m_solutionsView = solutionsView;
	m_upcomingView = upcomingView;
}

void Letterbox::print()
{
	pause(true);

	QString filename = QFileDialog::getSaveFileName(this, tr("Choose HTML file to which to save pretty word list"), m_filename + ".html", "*.html");

	if (filename.isEmpty())
		return;

	QFile file(filename);
	 
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
	{        
		QMessageBox::critical(this, tr("Error Writing File - Quackle Letterbox"), tr("Could not open %1 for writing.").arg(filename));        
		return;    
	}

	HTMLRepresentation printer;

	bool wasModified = m_modified;
	int previousNumber = m_numberIterator;
	statusBar()->showMessage(tr("Generating HTML..."));
	jumpTo(m_clueResults.size() - 1);

	printer.setWords(m_answers.begin(), m_answers.end());

	jumpTo(previousNumber);
	setModified(wasModified);

	QTextStream stream(&file);
	stream << printer.html() << "\n";

	file.close();

	statusBar()->showMessage(tr("%1 written.").arg(filename));
}

void Letterbox::printStudy()
{
	pause(true);

	QString filename = QFileDialog::getSaveFileName(this, tr("Choose file to which to save study sheet"), m_filename + "-study");

	if (filename.isEmpty())
		return;

	QFile file(filename);
	 
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
	{        
		QMessageBox::critical(this, tr("Error Writing File - Quackle Letterbox"), tr("Could not open %1 for writing.").arg(filename));        
		return;    
	}

	bool wasModified = m_modified;
	int previousNumber = m_numberIterator;
	statusBar()->showMessage(tr("Generating study sheet..."));
	jumpTo(m_clueResults.size() - 1);

	QTextStream stream(&file);
	stream << generateStudySheet(m_answers.begin(), m_answers.end()) << "\n";

	file.close();

	jumpTo(previousNumber);
	setModified(wasModified);

	statusBar()->showMessage(tr("%1 written.").arg(filename));
}

QString Letterbox::generateStudySheet(Dict::WordListList::ConstIterator start, Dict::WordListList::ConstIterator end)
{
	QString ret;

	int prevLengthOfExtensions = LetterboxSettings::self()->lengthOfExtensions;
	LetterboxSettings::self()->lengthOfExtensions = 1;

	for (Dict::WordListList::ConstIterator it = start; it != end; ++it) 
	{
		int length = (*it).front().word.length();
		QString pad = "  ";
		for (int i = 0; i < length; ++i)
			pad += " ";

		ret += arrangeLettersForUser((*it).front().word) + " ";
		bool first = true;
		for (Dict::WordList::ConstIterator wit = (*it).begin(); wit != (*it).end(); ++wit)
		{
			if (first)
			{
				first = false;
			}
			else
			{
				ret += pad;
			}

			ret += HTMLRepresentation::prettyExtensionList((*wit).getFrontExtensionList(), false);
			ret += " ";
			ret += (*wit).word;
			ret += " ";
			ret += HTMLRepresentation::prettyExtensionList((*wit).getBackExtensionList(), false);
			ret += "\n";
		}
	}

	LetterboxSettings::self()->lengthOfExtensions = prevLengthOfExtensions;
	
	return ret;
}

void Letterbox::about()
{
	QMessageBox::about(this, tr("About Quackle Letterbox"), "<p><b>Letterbox</b> is a lexical study tool, that is now part of Quackle.</p><p>Copyright 2005-2007 by<ul><li>John O'Laughlin &lt;olaughlin@gmail.com&gt;</li><li>Jason Katz-Brown &lt;jasonkatzbrown@gmail.com&gt;</li></ul>");
}

void Letterbox::saveSettings()
{
	LetterboxSettings::self()->writeSettings();

	CustomQSettings settings;

	settings.setValue("quackle/letterbox/most-recent-list", m_filename);
	settings.setValue("quackle/letterbox/window-size", size());
}

void Letterbox::loadSettings()
{
	LetterboxSettings::self()->readSettings();

	CustomQSettings settings;
	m_filename = settings.value("quackle/letterbox/most-recent-list", QString("")).toString();
	resize(settings.value("quackle/letterbox/window-size", QSize(800, 600)).toSize());
}

//////////

WordResult::WordResult()
{
	resetStats();
}

WordResult::WordResult(QString w)
{
	word = w;
	resetStats();
}

void WordResult::resetStats()
{
	missed = true;
	keystrokes = 0;
	time = 0;
}

//////////

ClueResult::ClueResult()
{
}

ClueResult::ClueResult(const QString &newClue)
	: clue(newClue)
{
}

void ClueResult::setWordList(Dict::WordList answers)
{
	for (Dict::WordList::iterator it = answers.begin(); it != answers.end(); ++it)
	{
		bool isAnswerInOurWords = false;
		for (WordResultList::iterator wrIt = words.begin(); wrIt != words.end(); ++wrIt)
		{
			if ((*it).word == (*wrIt).word)
			{
				isAnswerInOurWords = true;
				break;
			}
		}

		if (!isAnswerInOurWords)
			words.append(WordResult((*it).word));	
	}
}

void ClueResult::resetStats()
{
	for (WordResultList::iterator wrIt = words.begin(); wrIt != words.end(); ++wrIt)
		(*wrIt).resetStats();
}

Clue::Clue()
{
}

Clue::Clue(const QString &newClueString)
	: clueString(newClueString)
{
}

//////////

InputValidator::InputValidator(QObject *parent) : QValidator(parent)
{
}

InputValidator::~InputValidator()
{
}

QValidator::State InputValidator::validate(QString & /* input */, int &) const
{
	return Acceptable;
}

/////////

WordView::WordView(QWidget *parent)
	: QTextEdit(parent)
{
	m_shownSolutions = 16;
	m_shownClues = 30;
	m_tablePadding = 0;
	m_tableSpacing = 0;

	setReadOnly(true);

	setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

	// TODO(jasonkb) background/foreground colors
	//setPaper(QBrush(QColor(LetterboxSettings::self()->backgroundColor)));
	//setColor(LetterboxSettings::self()->foregroundColor);
}

WordView::~WordView()
{
}

void WordView::htmlUpdated(ContentType type)
{
	setText(html());

	switch (type)
	{
	case Content_Upcoming:
		scrollToAnchor("top");
		break;

	case Content_Solutions:
		QTextCursor cursor = textCursor();
		cursor.movePosition(QTextCursor::End);
		setTextCursor(cursor);
		ensureCursorVisible();
		break;
	}
}

////////

HTMLRepresentation::HTMLRepresentation()
	: m_shownSolutions(INT_MAX), m_shownClues(INT_MAX), m_tablePadding(4), m_tableSpacing(0)
{
}

HTMLRepresentation::~HTMLRepresentation()
{
}

void HTMLRepresentation::htmlUpdated(ContentType /* type */ )
{
}

void HTMLRepresentation::setHTML(const QString &text, ContentType type)
{
	m_html = text;
	htmlUpdated(type);
}

QString HTMLRepresentation::html()
{
	return m_html;
}

void HTMLRepresentation::setWords(ClueResultList::ConstIterator start, ClueResultList::ConstIterator end, bool revers)
{
	QString html("<a name=top>");
	
	int shown = 0;

	html += "<center>";

	if (revers)
	{
		ClueResultList::ConstIterator it = end;
		while (shown < m_shownClues)
		{
			if (it == start)
				break;

			--it;

			if (shown == 0)
				html += "<font size=6>";
			else
				html += "<font size=6>";

			html += htmlForPlainWord((*it).clue.clueString) + "<br>";

			html += "</font>";

			shown++;
		}
	}
	else
	{
		for (ClueResultList::ConstIterator it = start; (it != end) && (shown < 30); ++it) 
		{
			if (shown == 0)
				html += "<font size=6>";
			else
				html += "<font size=6>";

			html += htmlForPlainWord((*it).clue.clueString) + "<br>";

			if (shown == 0)
				html += "</font>";

			shown++;
		}
	}

	html += "</center>";

	setHTML(html, Content_Upcoming);
}

void HTMLRepresentation::setWords(Dict::WordListList::ConstIterator start, Dict::WordListList::ConstIterator end, bool revers)
{
    Dict::WordListList::ConstIterator newStart = end;
	for (int i = 0; i < m_shownSolutions; i++)
		if (newStart != start)
			newStart--;
	start = newStart;

	QString html("<a name=top>");

	if (revers)
	{
		Dict::WordListList::ConstIterator it = end;
		while (true)
		{
			if (it == start)
				break;

			--it;
			html += htmlForWordList(*it);
		}
	}
	else
	{
		for (Dict::WordListList::ConstIterator it = start; it != end; ++it)
			html += htmlForWordList(*it);
	}

	setHTML(html, Content_Solutions);
}

QString HTMLRepresentation::htmlForWordList(const Dict::WordList &wordList)
{
	if (wordList.isEmpty())
		return QString::null;

	QString html = QString("<center><table border=1 cellspacing=%1 cellpadding=%2>").arg(m_tableSpacing).arg(m_tablePadding);

	bool hasFrontExtensionColumn = false;
	bool hasBackExtensionColumn = false;

	Dict::WordList::ConstIterator end = wordList.end();
	for (Dict::WordList::ConstIterator it = wordList.begin(); it != end; ++it)
	{
		if (!(tableOfExtensions((*it).getFrontExtensionList()).isEmpty()))		
			hasFrontExtensionColumn = true;
		if (!(tableOfExtensions((*it).getBackExtensionList()).isEmpty()))		
			hasBackExtensionColumn = true;
	}

	for (Dict::WordList::ConstIterator it = wordList.begin(); it != end; ++it)
	{
		html += "<tr>";

		if (hasFrontExtensionColumn)
			html += "<td align=right>" + tableOfExtensions((*it).getFrontExtensionList()) + "</td>";

		html += "<td align=center>" + htmlForSolution(*it) + "</td>";

		if (hasBackExtensionColumn)
			html += "<td align=left>" + tableOfExtensions((*it).getBackExtensionList()) + "</td>";

		html += "</tr>";
	}
	html += "</table></center><font size=\"-7\"><br></font>\n";
     	
	return html;
}

QString HTMLRepresentation::htmlForPlainWord(const QString &word)
{
	QString fontArgs("color=\"%1\"");

	QString html("<font " + fontArgs.arg(LetterboxSettings::self()->foregroundColor) + ">%1</font>");

	return html.arg(word);
}

QString HTMLRepresentation::htmlForSolution(const Dict::Word &word)
{
	QString fontArgs("size=\"+5\" color=\"%1\"");

	QString html("<b><font " + fontArgs.arg(word.british? LetterboxSettings::self()->sowpodsColor : LetterboxSettings::self()->foregroundColor) + ">%1</font></b>");
	
	return html.arg(word.word + (word.british? "#" : ""));
}

QString HTMLRepresentation::tableOfExtensions(const Dict::ExtensionList &list)
{
	QString html;

	bool first = true;

	for (int i = 1; i <= LetterboxSettings::self()->lengthOfExtensions; ++i)
	{
		Dict::ExtensionList extensions(Dict::Word::extensionsByLength(i, list));
		if (extensions.count() > 0)
		{
			QString extensionHtml = HTMLRepresentation::prettyExtensionList(extensions);
			
			if (!extensionHtml.isEmpty())
			{
				if (!first)
					html += "<br>";
				else
					first = false;
			
				if (i == 1)
				{
					html += "<font size=5>";
				}
				else
				{
					html += "<font size=3>";
				}

				html += htmlForPlainWord(extensionHtml);

				html += "</font>";
			}
		}
	}

	return html;
}

void HTMLRepresentation::addSubmission(const QString &submission)
{
	QString newHtml(html());
	QString item(QString("%1").arg(submission));

	if (newHtml.endsWith("</p>"))
		newHtml.insert(newHtml.length() - 4, QString("<br>") + item);
	else
		newHtml += QString("<center><h2>%1</h2><p>%2</p>").arg(qApp->tr("Correct Answers")).arg(item);

	setHTML(newHtml, Content_Solutions);
}

QString HTMLRepresentation::prettyExtensionList(const Dict::ExtensionList &list, bool make_html)
{
	QString ret;

	int extensionChars = 0;
	QString space = make_html? "&nbsp;" : " ";

	for (Dict::ExtensionList::ConstIterator it = list.begin(); it != list.end(); ++it)
	{
		QString fontArgs("color=\"%1\"");

		QString color = (*it).british? LetterboxSettings::self()->sowpodsColor : LetterboxSettings::self()->foregroundColor;
  
		QString html;
		
		if (make_html)
			html += "<font " + fontArgs.arg(color) + ">%1</font>";
		else
			html += "%1";

		QString wordHtml;

		if (LetterboxSettings::self()->numExtensionChars > 0)
		{
			if (extensionChars >= LetterboxSettings::self()->numExtensionChars)
			{
				int numExtensions = 0;
				numExtensions = list.size();
				
				ret += QString("...%1(%2)").arg(space).arg(numExtensions);
				return ret;
			}
		}

		wordHtml += (*it).word;
		extensionChars += (*it).word.length();

		// this is super clumsy, working around the fact that it doesn't show leading nbsps
		bool displayableTokensRemain = false;
	
		for (Dict::ExtensionList::ConstIterator lookAhead = it; lookAhead != list.end(); ++lookAhead)
		{
			if (lookAhead == it)
				continue;

			displayableTokensRemain = true;
		}

		if (displayableTokensRemain)
			wordHtml += space;
		
		ret += html.arg(wordHtml);
		
		if (!displayableTokensRemain)
			return ret;
	}

	return ret;
}

QString Letterbox::getInitialDirectory() const
{
	return m_initialDirectory.isEmpty()? QDir::homePath() : m_initialDirectory;
}

void Letterbox::setInitialDirectory(const QString &filename)
{
	QFileInfo file(filename);
	m_initialDirectory = file.path();
}

QString Letterbox::studyListFileFilters() const
{
	return tr("Letterbox files (%1);;All files (*)").arg("*.letterbox");
}

QString Letterbox::defaultStudyListFileFilter() const
{
	return "*.letterbox";
}