File: AsciiOpenDlg.cpp

package info (click to toggle)
cloudcompare 2.11.3-7.1
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 58,224 kB
  • sloc: cpp: 229,982; ansic: 30,723; makefile: 84; sh: 20
file content (1346 lines) | stat: -rw-r--r-- 42,676 bytes parent folder | download
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
//##########################################################################
//#                                                                        #
//#                              CLOUDCOMPARE                              #
//#                                                                        #
//#  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; version 2 or later of the License.      #
//#                                                                        #
//#  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.                          #
//#                                                                        #
//#          COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI)             #
//#                                                                        #
//##########################################################################

//GUIs generated by Qt Designer
#include <ui_openAsciiFileDlg.h>

//Local
#include "AsciiOpenDlg.h"
#include "FileIOFilter.h"

//qCC_db
#include <ccPointCloud.h>

//Qt
#include <QComboBox>
#include <QDialogButtonBox>
#include <QFile>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QSpinBox>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QTextStream>
#include <QToolButton>
#include <QDesktopWidget>

//system
#include <cassert>
#include <cstdio>
#include <cstring>

//Semi-persistent value for max. cloud size
static double s_maxCloudSizeDoubleSpinBoxValue = (CC_MAX_NUMBER_OF_POINTS_PER_CLOUD / 1.0e6);

//Max number of points/lines to detect a column as 'labels'
static unsigned s_maxLabelCount = 256;

//! Dialog 'context'
struct AsciiOpenContext
{
	//! Default initializer
	AsciiOpenContext()
		: separator(' ')
		, extractSFNameFrom1stLine(false)
		, maxPointCountPerCloud(0)
		, skipLines(0)
		, applyAll(false)
		, commaDecimal(false)
	{}

	//! Saves state
	void save(Ui_AsciiOpenDialog* ui)
	{
		extractSFNameFrom1stLine = ui->extractSFNamesFrom1stLineCheckBox->isChecked();
		maxPointCountPerCloud = ui->maxCloudSizeDoubleSpinBox->value();
		separator = ui->lineEditSeparator->text().at(0);
		skipLines = ui->spinBoxSkipLines->value();
		commaDecimal = ui->commaDecimalCheckBox->isChecked();
	}

	//! Restores state
	void load(Ui_AsciiOpenDialog* ui) const
	{
		ui->extractSFNamesFrom1stLineCheckBox->setChecked(extractSFNameFrom1stLine);
		ui->maxCloudSizeDoubleSpinBox->setValue(maxPointCountPerCloud);
		ui->lineEditSeparator->blockSignals(true);
		ui->lineEditSeparator->setText(separator);
		ui->lineEditSeparator->blockSignals(false);
		ui->spinBoxSkipLines->blockSignals(true);
		ui->spinBoxSkipLines->setValue(skipLines);
		ui->spinBoxSkipLines->blockSignals(false);
		ui->commaDecimalCheckBox->blockSignals(true);
		ui->commaDecimalCheckBox->setChecked(commaDecimal);
		ui->commaDecimalCheckBox->setEnabled(separator != ',');
		ui->commaDecimalCheckBox->blockSignals(false);
	}

	AsciiOpenDlg::Sequence sequence;
	QChar separator;
	bool extractSFNameFrom1stLine;
	double maxPointCountPerCloud;
	int skipLines;
	bool applyAll;
	bool commaDecimal;
};
//! Semi-persistent loading context
static AsciiOpenContext s_asciiOpenContext;

AsciiOpenDlg::AsciiOpenDlg(QWidget* parent)
	: QDialog(parent)
	, m_ui(new Ui_AsciiOpenDialog)
	, m_skippedLines(0)
	, m_separator(' ')
	, m_averageLineSize(-1.0)
	, m_columnsCount(0)
{
	m_ui->setupUi(this);

	//spinBoxSkipLines->setValue(0);
	m_ui->commentLinesSkippedLabel->hide();

	connect(m_ui->applyButton,		&QPushButton::clicked,		this, &AsciiOpenDlg::apply);
	connect(m_ui->applyAllButton,	&QPushButton::clicked,		this, &AsciiOpenDlg::applyAll);
	connect(m_ui->cancelButton,		&QPushButton::clicked,		this, &AsciiOpenDlg::reject);
	connect(m_ui->lineEditSeparator, &QLineEdit::textChanged,	this, &AsciiOpenDlg::onSeparatorChange);
	connect(m_ui->commaDecimalCheckBox, &QCheckBox::toggled,	this, &AsciiOpenDlg::commaDecimalCheckBoxToggled);
	connect(m_ui->spinBoxSkipLines,	static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &AsciiOpenDlg::setSkippedLines);

	//shortcut buttons
	connect(m_ui->toolButtonShortcutSpace,		&QToolButton::clicked, this, &AsciiOpenDlg::shortcutButtonPressed);
	connect(m_ui->toolButtonShortcutComma,		&QToolButton::clicked, this, &AsciiOpenDlg::shortcutButtonPressed);
	connect(m_ui->toolButtonShortcutSemicolon,	&QToolButton::clicked, this, &AsciiOpenDlg::shortcutButtonPressed);

	m_ui->maxCloudSizeDoubleSpinBox->setMaximum(CC_MAX_NUMBER_OF_POINTS_PER_CLOUD / 1.0e6);
	m_ui->maxCloudSizeDoubleSpinBox->setValue(s_maxCloudSizeDoubleSpinBoxValue);

	QSize screenSize = QApplication::desktop()->screenGeometry().size();
	setMaximumSize(screenSize);
}

AsciiOpenDlg::~AsciiOpenDlg()
{
	delete m_ui;
	m_ui = nullptr;
}

void AsciiOpenDlg::setFilename(const QString &filename)
{
	m_filename = filename;
	m_ui->lineEditFileName->setText(m_filename);

	autoFindBestSeparator();
}

void AsciiOpenDlg::autoFindBestSeparator()
{
	const QList<QChar> separators{	QChar(' '),
									QChar(','),
									QChar(';')
								 };

	//We try all default separators...
	size_t maxValidColumnCount = 0;
	QChar bestSep = separators.front();
	for (QChar sep : separators)
	{
		setSeparator(sep); //this eventually calls 'updateTable'

		//...until we find one that gives us at least 3 valid colums
		size_t validColumnCount = 0;
		for (ColumnType type : m_columnType)
		{
			if (type != TEXT)
			{
				++validColumnCount;
			}
		}

		if (validColumnCount > 2)
		{
			return;
		}
		else if (validColumnCount > maxValidColumnCount)
		{
			maxValidColumnCount = validColumnCount;
			bestSep = sep;
		}
	}

	//if we are here, it means that we couldn't find a configuration
	//with 3 valid columns (we use the best guess in this case)
	setSeparator(bestSep); //this eventually calls 'updateTable'
}

void AsciiOpenDlg::setSkippedLines(int linesCount)
{
	if (linesCount < 0)
		return;

	m_skippedLines = static_cast<unsigned>(linesCount);

	updateTable();
}

static bool CouldBeX (const QString& colHeader) { return colHeader.startsWith(AsciiHeaderColumns::X().toUpper()); }
static bool CouldBeY (const QString& colHeader) { return colHeader.startsWith(AsciiHeaderColumns::Y().toUpper()); }
static bool CouldBeZ (const QString& colHeader) { return colHeader.startsWith(AsciiHeaderColumns::Z().toUpper()); }
static bool CouldBeRf(const QString& colHeader) { return colHeader == AsciiHeaderColumns::Rf().toUpper(); }
static bool CouldBeGf(const QString& colHeader) { return colHeader == AsciiHeaderColumns::Gf().toUpper(); }
static bool CouldBeBf(const QString& colHeader) { return colHeader == AsciiHeaderColumns::Bf().toUpper(); }
static bool CouldBeAf(const QString& colHeader) { return colHeader == AsciiHeaderColumns::Af().toUpper(); }
static bool CouldBeR (const QString& colHeader) { return colHeader == AsciiHeaderColumns::R().toUpper() || colHeader.contains("RED"); }
static bool CouldBeG (const QString& colHeader) { return colHeader == AsciiHeaderColumns::G().toUpper() || colHeader.contains("GREEN"); }
static bool CouldBeB (const QString& colHeader) { return colHeader == AsciiHeaderColumns::B().toUpper() || colHeader.contains("BLUE"); }
static bool CouldBeA (const QString& colHeader) { return colHeader == AsciiHeaderColumns::A().toUpper() || colHeader.contains("ALPHA"); }
static bool CouldBeNx(const QString& colHeader) { return colHeader.startsWith(AsciiHeaderColumns::Nx().toUpper()) || (colHeader.contains("NORM") && colHeader.contains("X")); }
static bool CouldBeNy(const QString& colHeader) { return colHeader.startsWith(AsciiHeaderColumns::Ny().toUpper()) || (colHeader.contains("NORM") && colHeader.contains("Y")); }
static bool CouldBeNz(const QString& colHeader) { return colHeader.startsWith(AsciiHeaderColumns::Nz().toUpper()) || (colHeader.contains("NORM") && colHeader.contains("Z")); }

static bool CouldBeGrey(const QString& colHeader) { return colHeader == AsciiHeaderColumns::Grey().toUpper(); }
static bool CouldBeRGBi(const QString& colHeader) { return colHeader == AsciiHeaderColumns::RGB32i().toUpper(); }
static bool CouldBeRGBf(const QString& colHeader) { return colHeader == AsciiHeaderColumns::RGB32f().toUpper(); }
static bool CouldBeScal(const QString& colHeader) { return colHeader.contains("SCALAR"); }
static bool CouldBeLabel(const QString& colHeader) { return colHeader.contains("LABEL") || colHeader.contains("NAME"); }

static const unsigned MAX_COLUMNS = 512;				//maximum number of columns that can be handled
static const unsigned LINES_READ_FOR_STATS = 200;		//number of lines read for stats
static const unsigned DISPLAYED_LINES = 20;				//number of displayed lines

static unsigned X_BIT		= 1;
static unsigned Y_BIT		= 2;
static unsigned Z_BIT		= 4;
static unsigned W_BIT		= 8;
static unsigned XYZ_BITS	= X_BIT | Y_BIT | Z_BIT;
static unsigned XYZW_BITS	= XYZ_BITS | W_BIT;

static int EnabledBits(unsigned bitField)
{
	int count = 0;
	if (bitField & X_BIT)
		++count;
	if (bitField & Y_BIT)
		++count;
	if (bitField & Z_BIT)
		++count;
	if (bitField & W_BIT)
		++count;

	return count;
}

void AsciiOpenDlg::onSeparatorChange(const QString& separator)
{
	assert(separator.size() == 1);
	if (separator.length() < 1)
	{
		m_ui->asciiCodeLabel->setText("Enter a valid character!");
		m_ui->buttonWidget->setEnabled(false);
		m_ui->tableWidget->clear();
		m_columnType.clear();
		return;
	}

	//new separator
	m_separator = separator[0];
	m_ui->asciiCodeLabel->setText(QString("(ASCII code: %1)").arg(m_separator.unicode()));

	m_headerLine.clear(); //to force re-assignation of columns!
	m_columnType.clear();

	updateTable();
}

bool AsciiOpenDlg::useCommaAsDecimal() const
{
	return m_ui->commaDecimalCheckBox->isEnabled() && m_ui->commaDecimalCheckBox->isChecked();
}

void AsciiOpenDlg::commaDecimalCheckBoxToggled(bool)
{
	onSeparatorChange(m_ui->lineEditSeparator->text());
}

void AsciiOpenDlg::updateTable()
{
	m_ui->tableWidget->setEnabled(false);
	//m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(false); //we can't do that here (as we may have restored the state of this checkbox before calling updateTable)

	bool hadValidHeader = !m_headerLine.isEmpty();
	m_headerLine.clear();

	if (m_filename.isEmpty())
	{
		m_ui->tableWidget->clear();
		m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(false);
		return;
	}
	//we open the file in ASCII mode
	QFile file(m_filename);
	if (!file.open(QFile::ReadOnly))
	{
		m_ui->tableWidget->clear();
		m_columnType.clear();
		m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(false);
		return;
	}
	QTextStream stream(&file);

	//we skip first lines (if needed)
	{
		for (unsigned i = 0; i < m_skippedLines;)
		{
			QString currentLine = stream.readLine();
			if (currentLine.isNull())
			{
				//end of file reached
				break;
			}
			if (currentLine.isEmpty())
			{
				//empty lines are ignored
				continue;
			}
			//we keep track of the first line
			if (i == 0)
			{
				m_headerLine = currentLine;
			}
			++i;
		}
	}

	//if the old setup has less than 3 columns, we forget it
	if (m_columnsCount < 3)
	{
		m_ui->tableWidget->clear();
		m_columnType.clear();
		m_columnsCount = 0;
	}
	m_ui->tableWidget->setRowCount(DISPLAYED_LINES + 1);	//+1 for first line shifting

	unsigned lineCount = 0;			//number of lines read
	unsigned totalChars = 0;		//total read characters (for stats)
	unsigned columnsCount = 0;		//max columns count per line
	unsigned commentLines = 0;		//number of comments line skipped

	std::vector<bool> valueIsNumber;	//identifies columns with numbers only [mandatory]
	std::vector<bool> valueIsBelowOne;	//identifies columns with values between -1 and 1 only
	std::vector<bool> valueIsInteger;	//identifies columns with integer values only
	std::vector<bool> valueIsBelow255;	//identifies columns with integer values between 0 and 255 only

	bool commaAsDecimal = useCommaAsDecimal();
	QLocale locale(commaAsDecimal ? QLocale::French : QLocale::English);
	QChar decimalPoint = commaAsDecimal ? ',' : '.';
	while (lineCount < LINES_READ_FOR_STATS)
	{
		QString currentLine = stream.readLine();
		if (currentLine.isNull())
		{
			//end of file reached
			break;
		}
		if (currentLine.isEmpty())
		{
			//empty lines are ignored
			continue;
		}

		//we recognize "//" as the beginning of a comment
		if (!currentLine.startsWith("//")/* || !currentLine.startsWith("#")*/)
		{
			QStringList parts = currentLine.simplified().split(m_separator, QString::SkipEmptyParts);
			
			if (lineCount < DISPLAYED_LINES)
			{
				unsigned partsCount = std::min(MAX_COLUMNS, static_cast<unsigned>(parts.size()));
				bool columnCountHasIncreased = (partsCount > columnsCount);

				//do we need to add one or several new columns?
				if (columnCountHasIncreased)
				{
					//we also extend vectors
					for (unsigned i = columnsCount; i < partsCount; ++i)
					{
						valueIsNumber.push_back(true);
						valueIsBelowOne.push_back(true);
						valueIsBelow255.push_back(true);
						valueIsInteger.push_back(true);
					}

					if (m_ui->tableWidget->columnCount() < static_cast<int>(partsCount))
					{
						//DGM: at this stage we must not reduce the table!
						//The first line is sometimes smaller than the next ones
						//and we want to keep the widgets/configuration for the
						//other columns!
						m_ui->tableWidget->setColumnCount(partsCount);
					}
					else if (m_ui->tableWidget->columnCount() > static_cast<int>(partsCount))
					{
						//remove the unnecessary cells!
						for (int i = static_cast<int>(partsCount); i < m_ui->tableWidget->columnCount(); ++i)
						{
							m_ui->tableWidget->setItem(lineCount + 1, i, nullptr);
						}
					}
					columnsCount = partsCount;
				}

				//we fill the current row with extracted parts
				for (unsigned i = 0; i < partsCount; ++i)
				{
					QTableWidgetItem* newItem = new QTableWidgetItem(parts[i]);

					//test values
					bool isANumber = false;
					double value = locale.toDouble(parts[i], &isANumber);
					if (!isANumber)
					{
						valueIsNumber[i]   = false;
						valueIsBelowOne[i] = false;
						valueIsInteger[i]  = false;
						valueIsBelow255[i] = false;
						newItem->setBackground(QBrush(QColor(255, 160, 160)));
					}
					else
					{
						if (columnCountHasIncreased || (lineCount == 1 && !valueIsNumber[i]))
						{
							//the previous lines were probably header lines
							//we can forget about their content otherwise it will prevent us from detecting the right pattern
							valueIsNumber[i]   = true;
							valueIsBelowOne[i] = true;
							valueIsInteger[i]  = true;
							valueIsBelow255[i] = true;
						}
						valueIsBelowOne[i] = valueIsBelowOne[i] && (fabs(value) <= 1.0);
						valueIsInteger[i] = valueIsInteger[i] && !parts[i].contains(decimalPoint);
						valueIsBelow255[i] = valueIsBelow255[i] && valueIsInteger[i] && (value >= 0.0 && value <= 255.0);
					}

					m_ui->tableWidget->setItem(lineCount + 1, i, newItem); //+1 for first line shifting
				}
			}

			totalChars += currentLine.size() + 1; //+1 for return char at eol
			++lineCount;
		}
		else
		{
			if (m_skippedLines == 0 && commentLines == 0)
			{
				//if the very first line is a comment, then we force the user to skip it!
				//this way it will be considered as a header
				m_ui->spinBoxSkipLines->setMinimum(1);
				m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(false);
				return;
			}
			++commentLines;
		}
	}

	file.close();

	//now we can reduce the table (if necessary)
	if (m_ui->tableWidget->columnCount() > static_cast<int>(columnsCount))
	{
		m_ui->tableWidget->setColumnCount(columnsCount);
	}

	//process header line
	if (!m_headerLine.isEmpty())
	{
		m_headerLine = m_headerLine.trimmed();
		int n = 0;
		while (n < m_headerLine.size() && m_headerLine.at(n) == '/')
		{
			++n;
		}
		if (n != 0)
		{
			m_headerLine.remove(0, n);
		}

		QString displayHeader = m_headerLine;
		if (m_headerLine.length() > 256)
		{
			displayHeader = m_headerLine.left(256) + "...";
		}
		m_ui->headerLabel->setText(QString("Header: ") + displayHeader);
		m_ui->headerLabel->setVisible(true);
	}
	else
	{
		m_ui->headerLabel->setVisible(false);
	}

	m_ui->commentLinesSkippedLabel->setVisible(commentLines != 0);
	if (commentLines)
	{
		m_ui->commentLinesSkippedLabel->setText(QString("+ %1 comment line(s) skipped").arg(commentLines));
	}

	if (lineCount == 0 || columnsCount == 0)
	{
		m_averageLineSize = -1.0;
		m_ui->tableWidget->clear();
		m_columnType.clear();
		return;
	}

	//average line size
	m_averageLineSize = static_cast<double>(totalChars) / lineCount;
	unsigned approximateTotalLineCount = static_cast<unsigned>(file.size() / m_averageLineSize);

	//we add a type selector for each column
	QStringList propsText;
	{
		propsText.reserve(ASCII_OPEN_DLG_TYPES_COUNT);
		for (unsigned i = 0; i < ASCII_OPEN_DLG_TYPES_COUNT; i++)
		{
			propsText << QString(ASCII_OPEN_DLG_TYPES_NAMES[i]);
		}
	}

	//remove unnecessary columns
	{
		while (columnsCount < m_columnsCount)
			m_ui->tableWidget->removeColumn(--m_columnsCount);
		if (m_columnType.size() > columnsCount)
			m_columnType.resize(columnsCount, UNKNOWN);
		for (unsigned i = lineCount + 1; i <= DISPLAYED_LINES; ++i)
			m_ui->tableWidget->removeRow(i);
	}

	//setup table and widgets
	{
		//Icons
		static const QIcon xIcon		(QString::fromUtf8(":/CC/images/typeXCoordinate.png"));
		static const QIcon yIcon		(QString::fromUtf8(":/CC/images/typeYCoordinate.png"));
		static const QIcon zIcon		(QString::fromUtf8(":/CC/images/typeZCoordinate.png"));
		static const QIcon NormIcon		(QString::fromUtf8(":/CC/images/typeNormal.png"));
		static const QIcon RGBIcon		(QString::fromUtf8(":/CC/images/typeRgbCcolor.png"));
		static const QIcon GreyIcon		(QString::fromUtf8(":/CC/images/typeGrayColor.png"));
		static const QIcon ScalarIcon	(QString::fromUtf8(":/CC/images/typeSF.png"));
		static const QIcon LabelIcon	(QString::fromUtf8(":/CC/images/dbLabelSymbol.png"));

		int columnWidth = (m_ui->tableWidget->width() * 9) / (columnsCount * 10);
		columnWidth = std::max(columnWidth, 80);

		for (unsigned i = 0; i < columnsCount; i++)
		{
			QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));
			QComboBox* _columnHeader = columnHeaderWidget;
			if (!columnHeaderWidget)
			{
				columnHeaderWidget = new QComboBox();
				columnHeaderWidget->addItems(propsText);
				columnHeaderWidget->setMaxVisibleItems(ASCII_OPEN_DLG_TYPES_COUNT);
				columnHeaderWidget->setCurrentIndex(0);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_X, xIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Y, yIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Z, zIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NX, NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NY, NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_NZ, NormIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_R, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_G, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_B, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_A, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Rf, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Gf, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Bf, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Af, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Grey, GreyIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32i, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_RGB32f, RGBIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Label, LabelIcon);
				columnHeaderWidget->setItemIcon(ASCII_OPEN_DLG_Scalar, ScalarIcon);

				connect(columnHeaderWidget, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &AsciiOpenDlg::columnsTypeHasChanged);
			}

			while (m_columnType.size() <= static_cast<size_t>(i))
				m_columnType.push_back(UNKNOWN);
			assert(m_columnType.size() >= static_cast<size_t>(i));

			if (!_columnHeader)
				m_ui->tableWidget->setCellWidget(0, i, columnHeaderWidget);
			m_ui->tableWidget->setColumnWidth(i, columnWidth);

			//a non-numerical column can't be valid
			if (!valueIsNumber[i])
			{
				m_columnType[i] = TEXT;
			}
			else
			{
				// we must do this to ensure we can get a correct result.
				// Otherwise, we may fail in such situations:
				//
				// FILE:
				// Line1   : $ gps file
				// Line2   : $ id name x y z
				// Line3   : 500
				// Line4   : 0    0001.JPG  753811.417453   4307200.381522      1957.803955
				// Linex   : ......
				// Line503 : 499  0500.JPG  753630.672714   4307195.433217      1957.803955
				// 
				// Description:
				// once we open the file, we will get a %m_columnType with 5 values of "TEXT"
				// then if we choose to skip the 3 first lines, we get a %valueIsNumber with 5 "true"
				// but the %m_columnType is still with 5 values of "TEXT" which leads to the failure!
				m_columnType[i] = UNKNOWN;
			}
		}
	}

	//auto-detect columns 'roles'
	{
		//DGM: bit flags now
		unsigned assignedXYZFlags = 0;
		unsigned assignedNormFlags = 0;
		unsigned assignedRGBFlags = 0;

		//split header (if any)
		QStringList headerParts = m_headerLine.simplified().split(m_separator, QString::SkipEmptyParts);
		bool validHeader = (headerParts.size() >= static_cast<int>(columnsCount));
		m_ui->extractSFNamesFrom1stLineCheckBox->setEnabled(validHeader); //can we consider the first ignored line as a header?
		if (!validHeader)
		{
			//no need to keep it (+ it will serve as flag later)
			m_headerLine.clear();
		}
		else if (!hadValidHeader)
		{
			m_ui->extractSFNamesFrom1stLineCheckBox->setChecked(true);
			for (ColumnType& type : m_columnType)
			{
				if (type != TEXT)
					type = UNKNOWN;
			}
			//std::fill(m_columnType.begin(), m_columnType.end(), UNKNOWN); //if the header has changed, we force update of all columns!
		}

		//first with the help of the header (if any)
		bool labelColumnAssigned = false;
		if (validHeader)
		{
			for (unsigned i = 0; i < columnsCount; i++)
			{
				//we try to guess columns if we have a valid header for the first time!
				if (m_columnType[i] == UNKNOWN || m_columnType[i] == IGNORED)
				{
					QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));
					assert(columnHeaderWidget);

					columnHeaderWidget->blockSignals(true);

					QString colHeader = headerParts[i].toUpper();

					if ((assignedXYZFlags & X_BIT) == 0 && CouldBeX(colHeader))
					{
						//X
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_X);
						assignedXYZFlags |= X_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedXYZFlags & Y_BIT) == 0 && CouldBeY(colHeader))
					{
						//Y
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Y);
						assignedXYZFlags |= Y_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedXYZFlags & Z_BIT) == 0 && CouldBeZ(colHeader))
					{
						//Z
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Z);
						assignedXYZFlags |= Z_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedRGBFlags & X_BIT) == 0 && CouldBeRf(colHeader))
					{
						//Red
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Rf);
						assignedRGBFlags |= X_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedRGBFlags & Y_BIT) == 0 && CouldBeGf(colHeader))
					{
						//Green
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Gf);
						assignedRGBFlags |= Y_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedRGBFlags & Z_BIT) == 0 && CouldBeBf(colHeader))
					{
						//Blue
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Bf);
						assignedRGBFlags |= Z_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedRGBFlags & X_BIT) == 0 && CouldBeR(colHeader))
					{
						//Red
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_R);
						assignedRGBFlags |= X_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedRGBFlags & Y_BIT) == 0 && CouldBeG(colHeader))
					{
						//Green
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_G);
						assignedRGBFlags |= Y_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedRGBFlags & Z_BIT) == 0 && CouldBeB(colHeader))
					{
						//Blue
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_B);
						assignedRGBFlags |= Z_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedRGBFlags & W_BIT) == 0 && CouldBeA(colHeader))
					{
						//Blue
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_A);
						assignedRGBFlags |= W_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedNormFlags & X_BIT) == 0 && CouldBeNx(colHeader))
					{
						//Nx
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_NX);
						assignedNormFlags |= X_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedNormFlags & Y_BIT) == 0 && CouldBeNy(colHeader))
					{
						//Ny
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_NY);
						assignedNormFlags |= Y_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if ((assignedNormFlags & Z_BIT) == 0 && CouldBeNz(colHeader))
					{
						//Nz
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_NZ);
						assignedNormFlags |= Z_BIT; //update bit field accordingly
						m_columnType[i] = VALID;
					}
					else if (CouldBeGrey(colHeader))
					{
						//Intensity
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Grey);
						m_columnType[i] = VALID;
					}
					else if (CouldBeRGBi(colHeader))
					{
						//RGBi
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_RGB32i);
						m_columnType[i] = VALID;
					}
					else if (CouldBeRGBf(colHeader))
					{
						//RGBf
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_RGB32f);
						m_columnType[i] = VALID;
					}
					else if (CouldBeScal(colHeader))
					{
						//scalar field
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Scalar);
						m_columnType[i] = VALID;
					}
					else if (!labelColumnAssigned && approximateTotalLineCount < s_maxLabelCount && CouldBeLabel(colHeader)) //no need to promote labels if there are too many of them ;)
					{
						//label
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Label);
						m_columnType[i] = VALID;
						labelColumnAssigned = true;
					}

					columnHeaderWidget->blockSignals(false);
				}
			}
		} //if (validHeader)

		//now for the auto-detection whithout header
		{
			for (unsigned i = 0; i < columnsCount; i++)
			{
				if (m_columnType[i] == TEXT)
				{
					if (!labelColumnAssigned && columnsCount > 1 && approximateTotalLineCount < s_maxLabelCount)
					{
						QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));
						assert(columnHeaderWidget);
						columnHeaderWidget->blockSignals(true);
						columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Label);
						columnHeaderWidget->blockSignals(false);

						labelColumnAssigned = true; //There Can Be Only One!
					}
					continue;
				}

				//now we deal with numerical values only
				assert(valueIsNumber[i]);

				//first time? let's try to assign each column a type
				if (m_columnType[i] == UNKNOWN && columnsCount > 1)
				{
					QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));
					assert(columnHeaderWidget);
					columnHeaderWidget->blockSignals(true);
					columnHeaderWidget->setCurrentIndex(-1);

					//by default, we assume that the first columns are always X,Y and Z
					if (assignedXYZFlags < XYZ_BITS)
					{
						//in rare cases, the first column is an index
						if (columnsCount > 3
							&& i == 0
							&& (EnabledBits(assignedXYZFlags) == 0)
							&& valueIsInteger[i]
							&& i + 1 < columnsCount
							&& !valueIsInteger[i + 1])
						{
							//let's consider it as a scalar
							columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Scalar);
						}
						else
						{
							if (!(assignedXYZFlags & X_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_X);
								assignedXYZFlags |= X_BIT; //update bit field accordingly
							}
							else if (!(assignedXYZFlags & Y_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Y);
								assignedXYZFlags |= Y_BIT; //update bit field accordingly
							}
							else if (!(assignedXYZFlags & Z_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Z);
								assignedXYZFlags |= Z_BIT; //update bit field accordingly
							}
						}
					}
					else
					{
						//looks like RGB?
						if (valueIsBelow255[i]
							&& assignedRGBFlags < XYZ_BITS
							&& (i + 2 - EnabledBits(assignedRGBFlags)) < columnsCount //make sure that we can put all values there!
							&& (EnabledBits(assignedRGBFlags) > 0 || (valueIsBelow255[i + 1] && valueIsBelow255[i + 2])) //make sure that next values are also ok!
							)
						{
							if (!(assignedRGBFlags & X_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_R);
								assignedRGBFlags |= X_BIT; //update bit field accordingly
							}
							else if (!(assignedRGBFlags & Y_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_G);
								assignedRGBFlags |= Y_BIT; //update bit field accordingly
							}
							else if (!(assignedRGBFlags & Z_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_B);
								assignedRGBFlags |= Z_BIT; //update bit field accordingly
							}
							else if (!(assignedRGBFlags & W_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_A);
								assignedRGBFlags |= W_BIT; //update bit field accordingly
							}
						}
						//looks like a normal vector?
						else if (valueIsBelowOne[i]
							&& assignedNormFlags < XYZ_BITS
							&& (i + 2 - EnabledBits(assignedNormFlags) < columnsCount) //make sure that we can put all values there!
							&& (EnabledBits(assignedNormFlags) > 0 || (valueIsBelowOne[i + 1] && valueIsBelowOne[i + 2])) //make sure that next values are also ok!
							) //make sure that next values are also ok!
						{
							if (!(assignedNormFlags & X_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_NX);
								assignedNormFlags |= X_BIT; //update bit field accordingly
							}
							else if (!(assignedNormFlags & Y_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_NY);
								assignedNormFlags |= Y_BIT; //update bit field accordingly
							}
							else if (!(assignedNormFlags & Z_BIT))
							{
								columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_NZ);
								assignedNormFlags |= Z_BIT; //update bit field accordingly
							}
						}
						else
						{
							//maybe it's a scalar?
							columnHeaderWidget->setCurrentIndex(ASCII_OPEN_DLG_Scalar);
						}
					}

					if (columnHeaderWidget->currentIndex() >= 0)
					{
						m_columnType[i] = VALID;
					}
					else
					{
						//we won't look at this column again
						m_columnType[i] = IGNORED;
					}

					columnHeaderWidget->blockSignals(false);
				}
				else
				{
					//we won't look at this column again
					m_columnType[i] = IGNORED;
				}
			}
		}
	}

	m_columnsCount = columnsCount;

	m_ui->tableWidget->setEnabled(true);
	m_ui->buttonWidget->setEnabled(true);

	//check for invalid columns
	checkSelectedColumnsValidity(); //will eventually enable of disable the "OK" button
	
	m_ui->tableWidget->resizeColumnsToContents();
}

void AsciiOpenDlg::checkSelectedColumnsValidity()
{
	//check for invalid columns
	bool m_selectedInvalidColumns = false;
	{
		assert(m_columnType.size() == static_cast<size_t>(m_columnsCount));
		assert(m_ui->tableWidget->columnCount() >= static_cast<int>(m_columnsCount));
		m_ui->show2DLabelsCheckBox->setEnabled(false);
		for (unsigned i = 0; i < m_columnsCount; i++)
		{
			QComboBox* columnHeaderWidget = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));

			if (columnHeaderWidget->currentIndex() == ASCII_OPEN_DLG_Label)
			{
				m_ui->show2DLabelsCheckBox->setEnabled(true);
			}
			else if (m_columnType[i] == TEXT && columnHeaderWidget->currentIndex() != 0)
			{
				//text columns shouldn't be selected (other than for Labels)
				m_selectedInvalidColumns |= true;
			}
		}
	}

	m_ui->applyAllButton->setEnabled(!m_selectedInvalidColumns);
	m_ui->applyButton->setEnabled(!m_selectedInvalidColumns);
}

bool AsciiOpenDlg::CheckOpenSequence(const AsciiOpenDlg::Sequence& sequence, QString& errorMessage)
{
	//two requirements:
	//- at least 2 coordinates must be defined
	//- apart from SFs, only one column assignment per property
	std::vector<unsigned> counters(ASCII_OPEN_DLG_TYPES_COUNT, 0);
	{
		for (size_t i = 0; i < sequence.size(); i++)
			++counters[sequence[i].type];
	}

	//check for doublons
	{
		for (size_t i = 1; i < ASCII_OPEN_DLG_Scalar; i++)
		{
			if (counters[i] > 1)
			{
				errorMessage = QString("'%1' defined at least twice!").arg(ASCII_OPEN_DLG_TYPES_NAMES[i]);
				return false;
			}
		}
	}

	unsigned char coordIsDefined[3] = {	counters[ASCII_OPEN_DLG_X] != 0,
										counters[ASCII_OPEN_DLG_Y] != 0,
										counters[ASCII_OPEN_DLG_Z] != 0 };

	if (coordIsDefined[0] + coordIsDefined[1] + coordIsDefined[2] < 2)
	{
		errorMessage = "At least 2 vertex coordinates must be defined!";
		return false;
	}

	return true;
}

bool AsciiOpenDlg::apply()
{
	QString errorMessage;
	if (!CheckOpenSequence(getOpenSequence(),errorMessage))
	{
		QMessageBox::warning(nullptr, "Error", errorMessage);
		return false;
	}
	else
	{
		s_maxCloudSizeDoubleSpinBoxValue = m_ui->maxCloudSizeDoubleSpinBox->value();
		accept();
		return true;
	}
}

void AsciiOpenDlg::applyAll()
{
	if (!apply())
		return;

	//backup current open sequence
	s_asciiOpenContext.save(m_ui);
	s_asciiOpenContext.sequence = getOpenSequence();
	s_asciiOpenContext.applyAll = true;
}

void AsciiOpenDlg::ResetApplyAll()
{
	s_asciiOpenContext.applyAll = false;
}

bool AsciiOpenDlg::restorePreviousContext()
{
	if (!s_asciiOpenContext.applyAll)
		return false;

	//restore previous dialog state
	s_asciiOpenContext.load(m_ui);
	m_separator = s_asciiOpenContext.separator;
	m_skippedLines = static_cast<unsigned>(std::max(0, s_asciiOpenContext.skipLines));
	updateTable();

	//saved sequence and cloud content don't match!!!
	if (static_cast<size_t>(m_columnsCount) != s_asciiOpenContext.sequence.size())
	{
		s_asciiOpenContext.applyAll = false; //cancel the 'Apply All' effect
		return false;
	}

	//Restore columns attributes
	for (unsigned i = 0; i < m_columnsCount; i++)
	{
		QComboBox* combo = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));
		if (!combo) //yes, it happens if all lines are skipped!
		{
			s_asciiOpenContext.applyAll = false; //cancel the 'Apply All' effect
			return false;
		}
		SequenceItem& item = s_asciiOpenContext.sequence[i];
		combo->setCurrentIndex(item.type);
	}

	QString errorMessage;
	if (!CheckOpenSequence(s_asciiOpenContext.sequence, errorMessage))
	{
		s_asciiOpenContext.applyAll = false; //cancel the 'Apply All' effect
	}
	return s_asciiOpenContext.applyAll;
}

AsciiOpenDlg::Sequence AsciiOpenDlg::getOpenSequence() const
{
	Sequence seq;

	if (m_columnsCount != 0)
	{
		//shall we extract headerParts?
		QStringList headerParts;
		if (!m_headerLine.isEmpty()
			&& m_ui->extractSFNamesFrom1stLineCheckBox->isEnabled()
			&& m_ui->extractSFNamesFrom1stLineCheckBox->isChecked())
		{
			headerParts = m_headerLine.simplified().split(m_separator, QString::SkipEmptyParts);
		}

		seq.reserve(m_columnsCount - 1);
		for (unsigned i = 0; i<m_columnsCount; i++)
		{
			const QComboBox* combo = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));
			if (!combo) //yes, it happens if all lines are skipped!
				break;
			seq.emplace_back(static_cast<CC_ASCII_OPEN_DLG_TYPES>(combo->currentIndex()), headerParts.size() > static_cast<int>(i) ? headerParts[i] : QString());
		}
	}

	return seq;
}

bool AsciiOpenDlg::safeSequence() const
{
	//less than 6 columns: we probably have a 3D point (3 columns)
	//and 2 other columns (i.e. scalar fields) --> no ambiguity
	if (getColumnsCount() < 6)
		return true;

	//no header
	if (m_headerLine.isEmpty())
		return false;

	AsciiOpenDlg::Sequence seq = getOpenSequence();
	QStringList headerParts = m_headerLine.simplified().split(m_separator, QString::SkipEmptyParts);

	//not enough column headers?
	if (headerParts.size() < static_cast<int>(seq.size()))
		return false;

	for (int i = 0; i < headerParts.size(); ++i)
	{
		//column header
		QString colHeader = headerParts[i].toUpper();
		//column type
		switch (seq[i].type)
		{
		case ASCII_OPEN_DLG_None:
			break;
		case ASCII_OPEN_DLG_X:
			if (!CouldBeX(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_Y:
			if (!CouldBeY(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_Z:
			if (!CouldBeZ(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_NX:
			if (!CouldBeNx(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_NY:
			if (!CouldBeNy(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_NZ:
			if (!CouldBeNz(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_R:
		case ASCII_OPEN_DLG_Rf:
			if (!CouldBeR(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_G:
		case ASCII_OPEN_DLG_Gf:
			if (!CouldBeG(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_B:
		case ASCII_OPEN_DLG_Bf:
			if (!CouldBeB(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_A:
		case ASCII_OPEN_DLG_Af:
			if (!CouldBeA(colHeader))
				return false;
			break;
		case ASCII_OPEN_DLG_Grey:
			if (	!CouldBeGrey(colHeader)
				&&	!colHeader.contains("INT"))
				return false;
			break;
		case ASCII_OPEN_DLG_Scalar:
			//a SF name can be anything!
			break;
		case ASCII_OPEN_DLG_RGB32i:
			if (	!CouldBeRGBi(colHeader)
				&&	!colHeader.contains("RGB"))
				return false;
			break;
		case ASCII_OPEN_DLG_RGB32f:
			if (	!CouldBeRGBf(colHeader)
				&&	!colHeader.contains("RGB"))
				return false;
			break;
		case ASCII_OPEN_DLG_Label:
			if (!CouldBeLabel(colHeader))
				return false;
			break;
		default:
			//unhandled case?!
			assert(false);
			return false;
		}
	}

	return true;
}

void AsciiOpenDlg::columnsTypeHasChanged(int index)
{
	if (!m_columnsCount)
	{
		return;
	}

	//we get the signal sender
	QObject* obj = sender();
	if (!obj)
	{
		assert(false);
		return;
	}

	//it should be a QComboBox
	QComboBox* changedCombo = qobject_cast<QComboBox*>(obj);
	if (!changedCombo)
	{
		assert(false);
		return;
	}

	//now we look which column's combobox it is
	for (unsigned i = 0; i < m_columnsCount; i++)
	{
		QComboBox* combo = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i));
		//we found the right element
		if (changedCombo == combo)
		{
			if (index == int(ASCII_OPEN_DLG_X)  ||
				index == int(ASCII_OPEN_DLG_NX) ||
				index == int(ASCII_OPEN_DLG_R)  ||
				index == int(ASCII_OPEN_DLG_Rf)
				)
			{
				//Auto select the next columns type
				if (i + 2 < m_columnsCount)
				{
					QComboBox* nextCombo = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i + 1));
					QComboBox* nextNextCombo = static_cast<QComboBox*>(m_ui->tableWidget->cellWidget(0, i + 2));
					//if the two next columns have no assigned type, we set them auto.
					if (	nextCombo->currentIndex() == int(ASCII_OPEN_DLG_None)
						&&	nextNextCombo->currentIndex() == int(ASCII_OPEN_DLG_None))
					{
						nextCombo->blockSignals(true);
						nextNextCombo->blockSignals(true);

						if (index == int(ASCII_OPEN_DLG_X))
						{
							nextCombo->setCurrentIndex(ASCII_OPEN_DLG_Y);
							nextNextCombo->setCurrentIndex(ASCII_OPEN_DLG_Z);
						}
						else if (index == int(ASCII_OPEN_DLG_NX))
						{
							nextCombo->setCurrentIndex(ASCII_OPEN_DLG_NY);
							nextNextCombo->setCurrentIndex(ASCII_OPEN_DLG_NZ);
						}
						else if (index == int(ASCII_OPEN_DLG_R))
						{
							nextCombo->setCurrentIndex(ASCII_OPEN_DLG_G);
							nextNextCombo->setCurrentIndex(ASCII_OPEN_DLG_B);
						}
						else if (index == int(ASCII_OPEN_DLG_Rf))
						{
							nextCombo->setCurrentIndex(ASCII_OPEN_DLG_Gf);
							nextNextCombo->setCurrentIndex(ASCII_OPEN_DLG_Bf);
						}
					}

					nextCombo->blockSignals(false);
					nextNextCombo->blockSignals(false);
				}
			}
		}
		else if (index< ASCII_OPEN_DLG_Scalar) //check that the other combo as the same index (apart from SF)
		{
			if (combo->currentIndex() == index)
			{
				combo->blockSignals(true);
				combo->setCurrentIndex(ASCII_OPEN_DLG_None);
				combo->blockSignals(false);
			}
		}
	}

	checkSelectedColumnsValidity(); //will eventually enable of disable the "OK" button
}

void AsciiOpenDlg::shortcutButtonPressed()
{
	if (!m_columnsCount)
		return;

	//we get the signal sender
	QObject* obj = sender();
	if (!obj)
		return;

	//it should be a QToolButton (could we test this?)
	QToolButton* shortcutButton = static_cast<QToolButton*>(obj);

	char newSeparator = 0;
	if (shortcutButton == m_ui->toolButtonShortcutSpace)
		newSeparator = 32;
	else if (shortcutButton == m_ui->toolButtonShortcutComma)
		newSeparator = 44;
	else if (shortcutButton == m_ui->toolButtonShortcutSemicolon)
		newSeparator = 59;

	if (newSeparator != 0 && getSeparator() != newSeparator)
	{
		setSeparator(QChar(newSeparator));
	}
}

void AsciiOpenDlg::setSeparator(QChar sep)
{
	m_ui->commaDecimalCheckBox->blockSignals(true);
	if (sep == 44) //comma
	{
		m_ui->commaDecimalCheckBox->setEnabled(false);
		//m_ui->commaDecimalCheckBox->setChecked(false);
	}
	else
	{
		m_ui->commaDecimalCheckBox->setEnabled(true);
	}
	m_ui->commaDecimalCheckBox->blockSignals(false);
	m_ui->lineEditSeparator->setText(sep);
}

unsigned AsciiOpenDlg::getMaxCloudSize() const
{
	return static_cast<unsigned>(floor(m_ui->maxCloudSizeDoubleSpinBox->value() * 1.0e6));
}

bool AsciiOpenDlg::showLabelsIn2D() const
{
	return m_ui->show2DLabelsCheckBox->isEnabled() && m_ui->show2DLabelsCheckBox->isChecked();
}