summaryrefslogtreecommitdiff
path: root/plugins/CopyEngine/Ultracopier-0.3/TransferThread.cpp
blob: 359a705c79e7765e1810cfc83871891699043ef3 (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
//presume bug linked as multple paralelle inode to resume after "overwrite"
//then do overwrite node function to not re-set the file name

#include "TransferThread.h"

#ifdef Q_CC_GNU
//this next header is needed to change file time/date under gcc
#include <utime.h>
#endif

/// \todo manage case resume after error, because previously inode opt free before
/// \todo manage error in pre and post operation
/// \todo remove destination when canceled
/// \todo test if source if closed by end but write error
/// \todo pointer for readThread and writeThread to destroy the read before the write (prevent dead lock)

/// \bug continue progress when write error

TransferThread::TransferThread()
{
	start();
	moveToThread(this);
	needSkip		= false;
	stat			= Idle;
	stopIt			= false;
	fileExistsAction	= FileExists_NotSet;
	alwaysDoFileExistsAction= FileExists_NotSet;
	readError		= false;
	writeError		= false;
	this->mkpathTransfer	= mkpathTransfer;
	readThread.setWriteThread(&writeThread);

	connect(&clockForTheCopySpeed,	SIGNAL(timeout()),			this,	SLOT(timeOfTheBlockCopyFinished()));
	maxTime=QDateTime(QDate(ULTRACOPIER_PLUGIN_MINIMALYEAR,1,1));
}

TransferThread::~TransferThread()
{
	exit();
	disconnect(&readThread);
	disconnect(&writeThread);
	disconnect(this);
	wait();
}

void TransferThread::run()
{
	//ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start: "+QString::number((qint64)QThread::currentThreadId()));
	stat			= Idle;
	stopIt			= false;
	fileExistsAction	= FileExists_NotSet;
	alwaysDoFileExistsAction= FileExists_NotSet;
	//the error push
	connect(&readThread,SIGNAL(error()),			this,					SLOT(getReadError()),		Qt::QueuedConnection);
	connect(&writeThread,SIGNAL(error()),			this,					SLOT(getWriteError()),		Qt::QueuedConnection);
	//the thread change operation
	connect(this,SIGNAL(internalStartPreOperation()),	this,					SLOT(preOperation()),		Qt::QueuedConnection);
	connect(this,SIGNAL(internalStartPostOperation()),	this,					SLOT(postOperation()),		Qt::QueuedConnection);
        //the state change operation
	connect(&readThread,SIGNAL(readIsStopped()),		&readThread,				SLOT(postOperation()),		Qt::QueuedConnection);
	connect(&readThread,SIGNAL(opened()),			this,					SLOT(readIsReady()),		Qt::QueuedConnection);
	connect(&writeThread,SIGNAL(opened()),			this,					SLOT(writeIsReady()),		Qt::QueuedConnection);
	connect(&readThread,SIGNAL(readIsStopped()),		this,					SLOT(readIsStopped()),		Qt::QueuedConnection);
	connect(&writeThread,SIGNAL(writeIsStopped()),		this,					SLOT(writeIsStopped()),		Qt::QueuedConnection);
	connect(&readThread,SIGNAL(readIsStopped()),		&writeThread,				SLOT(endIsDetected()),		Qt::QueuedConnection);
	connect(&writeThread,SIGNAL(writeIsStopped()),		&writeThread,				SLOT(postOperation()),		Qt::QueuedConnection);
	connect(&readThread,SIGNAL(readIsStopped()),		this,					SLOT(readIsFinish()),		Qt::QueuedConnection);
	connect(&readThread,SIGNAL(closed()),			this,					SLOT(readIsClosed()),		Qt::QueuedConnection);
	connect(&writeThread,SIGNAL(closed()),			this,					SLOT(writeIsClosed()),		Qt::QueuedConnection);
	connect(&writeThread,SIGNAL(reopened()),		this,					SLOT(writeThreadIsReopened()),	Qt::QueuedConnection);
        //error management
	connect(&readThread,SIGNAL(isSeekToZeroAndWait()),	this,					SLOT(readThreadIsSeekToZeroAndWait()),	Qt::QueuedConnection);
	connect(&readThread,SIGNAL(resumeAfterErrorByRestartAtTheLastPosition()),	this,		SLOT(readThreadResumeAfterError()),	Qt::QueuedConnection);
	connect(&readThread,SIGNAL(resumeAfterErrorByRestartAll()),                     &writeThread,	SLOT(flushAndSeekToZero()),		Qt::QueuedConnection);
	connect(&writeThread,SIGNAL(flushedAndSeekedToZero()),                          this,           SLOT(readThreadResumeAfterError()),	Qt::QueuedConnection);
	connect(this,SIGNAL(internalTryStartTheTransfer()),	this,					SLOT(internalStartTheTransfer()),	Qt::QueuedConnection);

	#ifdef ULTRACOPIER_PLUGIN_DEBUG
	connect(&readThread,SIGNAL(debugInformation(DebugLevel,QString,QString,QString,int)),this,SIGNAL(debugInformation(DebugLevel,QString,QString,QString,int)),Qt::QueuedConnection);
	connect(&writeThread,SIGNAL(debugInformation(DebugLevel,QString,QString,QString,int)),this,SIGNAL(debugInformation(DebugLevel,QString,QString,QString,int)),Qt::QueuedConnection);
	#endif

	/// \todo do the current post opt only after the read write opt
	exec();
}

TransferThread::TransferStat TransferThread::getStat()
{
	return stat;
}

void TransferThread::startTheTransfer()
{
	emit internalTryStartTheTransfer();
}

void TransferThread::internalStartTheTransfer()
{
	if(stat==Idle)
	{
		if(mode!=Move)
		{
			/// \bug can pass here because in case of direct move on same media, it return to idle stat directly
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] can't start transfert at idle");
		}
		return;
	}
	if(stat==PostOperation)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] can't start transfert at PostOperation");
		return;
	}
	if(stat==Transfer)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] can't start transfert at Transfer");
		return;
	}
	if(canStartTransfer)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] canStartTransfer is already set to true");
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] check how start the transfer");
	canStartTransfer=true;
	if(readIsReadyVariable && writeIsReadyVariable)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start directly the transfer");
		ifCanStartTransfer();
	}
	else
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start the transfer as delayed");
}

void TransferThread::setFiles(const QString &source,const qint64 &size,const QString &destination,const CopyMode &mode)
{
	if(stat!=Idle)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] already used, source: "+source+", destination: "+destination);
		return;
	}
	//to prevent multiple file alocation into ListThread::doNewActions_inode_manipulation()
	stat			= PreOperation;
	//emit pushStat(stat,transferId);
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start, source: "+source+", destination: "+destination);
	this->source			= source;
	this->destination		= destination;
	this->mode			= mode;
	this->size			= size;
	fileExistsAction		= FileExists_NotSet;
	canStartTransfer		= false;
	sended_state_preOperationStopped= false;
	canBeMovedDirectlyVariable	= false;
	resetExtraVariable();
	emit internalStartPreOperation();
}

void TransferThread::setFileExistsAction(const FileExistsAction &action)
{
	if(stat!=PreOperation)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] already used, source: "+source+", destination: "+destination);
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] action: "+QString::number(action));
	if(action!=FileExists_Rename)
		fileExistsAction	= action;
	else
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] rename at the wrong part, source: "+source+", destination: "+destination);
	if(action==FileExists_Skip)
	{
		skip();
		return;
	}
	resetExtraVariable();
	emit internalStartPreOperation();
}

void TransferThread::setFileRename(const QString &nameForRename)
{
	if(stat!=PreOperation)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] already used, source: "+source+", destination: "+destination);
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] nameForRename: "+nameForRename);
	destinationInfo.setFile(destination);
	destination=destinationInfo.absolutePath();
	destination+=QDir::separator()+nameForRename;
	destinationInfo.setFile(destination);
	fileExistsAction	= FileExists_NotSet;
	resetExtraVariable();
	emit internalStartPreOperation();
}

void TransferThread::setAlwaysFileExistsAction(const FileExistsAction &action)
{
	//ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] action to do always: "+QString::number(action));
	alwaysDoFileExistsAction=action;
}

void TransferThread::resetExtraVariable()
{
	sended_state_readStopped	= false;
	sended_state_writeStopped	= false;
	writeError			= false;
	readError			= false;
	readIsReadyVariable		= false;
	writeIsReadyVariable		= false;
	readIsFinishVariable		= false;
	readIsClosedVariable		= false;
	writeIsClosedVariable		= false;
	needSkip			= false;
	retry				= false;
	readIsOpenVariable		= false;
	writeIsOpenVariable		= false;
}

void TransferThread::preOperation()
{
	if(stat!=PreOperation)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] already used, source: "+source+", destination: "+destination);
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	needRemove=false;
	sourceInfo.setFile(source);
	destinationInfo.setFile(destination);
	if(isSame())
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] is same"+source);
		return;
	}
	if(destinationExists())
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] destination exists: "+source);
		return;
	}
	if(canBeMovedDirectly())
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] need moved directly: "+source);
		canBeMovedDirectlyVariable=true;
		readThread.fakeOpen();
		writeThread.fakeOpen();
		return;
	}
	tryOpen();
}

void TransferThread::tryOpen()
{
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start source and destination: "+source+" and "+destination);
	if(!readIsOpenVariable)
	{
		readError=false;
		readThread.open(source,mode);
	}
	if(!writeIsOpenVariable)
	{
		writeError=false;
		writeThread.open(destination,sourceInfo.size());
	}
}

bool TransferThread::isSame()
{
	//check if source and destination is not the same
	if(sourceInfo==destinationInfo)
	{
		emit fileAlreadyExists(sourceInfo,destinationInfo,true);
		return true;
	}
	return false;
}

bool TransferThread::destinationExists()
{
	/// \todo do the overwrite: FileExists_OverwriteIfNotSameModificationDate
	//check if destination exists
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] overwrite: "+QString::number(fileExistsAction)+", always action: "+QString::number(alwaysDoFileExistsAction));
	if(alwaysDoFileExistsAction==FileExists_Overwrite || readError || writeError)
		return false;
	if(destinationInfo.exists())
	{
		if(fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_Skip)
		{
			stat=Idle;
			emit postOperationStopped();
			return true;
		}
		if(alwaysDoFileExistsAction==FileExists_Rename)
		{
			QString absolutePath=destinationInfo.absolutePath();
			QString fileName=destinationInfo.fileName();
			QString suffix="";
			if(fileName.contains(QRegExp("^(.*)(\\.[a-z0-9]+)$")))
			{
				suffix=fileName;
				suffix.replace(QRegExp("^(.*)(\\.[a-z0-9]+)$"),"\\2");
				fileName.replace(QRegExp("^(.*)(\\.[a-z0-9]+)$"),"\\1");
			}
			do
			{
				if(!fileName.startsWith(tr("Copy of ")))
					fileName=tr("Copy of ")+fileName;
				else
				{
					if(fileName.contains(QRegExp("_[0-9]+$")))
					{
						QString number=fileName;
						number.replace(QRegExp("^.*_([0-9]+)$"),"\\1");
						int num=number.toInt()+1;
						fileName.remove(QRegExp("[0-9]+$"));
						fileName+=QString::number(num);
					}
					else
						fileName+="_2";
				}
				destination=absolutePath+QDir::separator()+fileName+suffix;
				destinationInfo.setFile(destination);
			}
			while(destinationInfo.exists());
			return false;
		}
		if(fileExistsAction==FileExists_OverwriteIfNewer || (fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_OverwriteIfNewer))
		{
			if(destinationInfo.lastModified()<sourceInfo.lastModified())
				return false;
			else
			{
				stat=Idle;
				emit postOperationStopped();
				return true;
			}
		}
		if(fileExistsAction==FileExists_OverwriteIfNotSameModificationDate || (fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_OverwriteIfNotSameModificationDate))
		{
			if(destinationInfo.lastModified()!=sourceInfo.lastModified())
				return false;
			else
			{
				stat=Idle;
				emit postOperationStopped();
				return true;
			}
		}
		if(fileExistsAction==FileExists_NotSet)
		{
			emit fileAlreadyExists(sourceInfo,destinationInfo,false);
			return true;
		}
	}
	return false;
}

void TransferThread::tryMoveDirectly()
{
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start the system move");

	//move if on same mount point
	QFile sourceFile(sourceInfo.absoluteFilePath());
	QFile destinationFile(destinationInfo.absoluteFilePath());
	if(destinationFile.exists() && !destinationFile.remove())
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] "+destinationFile.fileName()+", error: "+destinationFile.errorString());
		emit errorOnFile(destinationInfo,destinationFile.errorString());
		return;
	}
	QDir dir(destinationInfo.absolutePath());
	{
		mkpathTransfer->acquire();
		if(!dir.exists())
			dir.mkpath(destinationInfo.absolutePath());
		mkpathTransfer->release();
	}
	if(!sourceFile.rename(destinationFile.fileName()))
	{
		if(sourceFile.exists())
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] "+QString("file not not exists %1: %2, error: %3").arg(sourceFile.fileName()).arg(destinationFile.fileName()).arg(sourceFile.errorString()));
		else if(!dir.exists())
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] "+QString("destination folder not exists %1: %2, error: %3").arg(sourceFile.fileName()).arg(destinationFile.fileName()).arg(sourceFile.errorString()));
		else
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] "+QString("unable to do real move %1: %2, error: %3").arg(sourceFile.fileName()).arg(destinationFile.fileName()).arg(sourceFile.errorString()));
		emit errorOnFile(sourceFile,sourceFile.errorString());
		return;
	}
	readThread.fakeReadIsStarted();
	writeThread.fakeWriteIsStarted();
	readThread.fakeReadIsStopped();
	writeThread.fakeWriteIsStopped();
}

bool TransferThread::canBeMovedDirectly()
{
	//move if on same mount point
	#if defined (Q_OS_LINUX) || defined (Q_OS_WIN32)
	if(mode!=Move)
		return false;
	if(mountSysPoint.size()==0)
		return false;
	if(getDrive(destinationInfo.fileName())==getDrive(sourceInfo.fileName()))
		return true;
	#endif
	return false;
}

void TransferThread::readIsReady()
{
	if(readIsReadyVariable)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] double event dropped");
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	readIsReadyVariable=true;
	readIsOpenVariable=true;
	readIsClosedVariable=false;
	ifCanStartTransfer();
}

void TransferThread::ifCanStartTransfer()
{
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] readIsReadyVariable: "+QString::number(readIsReadyVariable)+", writeIsReadyVariable: "+QString::number(writeIsReadyVariable));
	if(readIsReadyVariable && writeIsReadyVariable)
	{
		stat=WaitForTheTransfer;
		sended_state_readStopped	= false;
		sended_state_writeStopped	= false;
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] stat=WaitForTheTransfer");
		if(!sended_state_preOperationStopped)
		{
			sended_state_preOperationStopped=true;
			emit preOperationStopped();
		}
		if(canStartTransfer)
		{
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] stat=Transfer");
			stat=Transfer;
			if(!canBeMovedDirectlyVariable)
			{
				needRemove=true;
				readThread.startRead();
			}
			else
				tryMoveDirectly();
			emit pushStat(stat,transferId);
		}
		//else
			//emit pushStat(stat,transferId);
	}
}

void TransferThread::writeIsReady()
{
	if(writeIsReadyVariable)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] double event dropped");
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	writeIsReadyVariable=true;
	writeIsOpenVariable=true;
	writeIsClosedVariable=false;
	ifCanStartTransfer();
}


//set the copy info and options before runing
void TransferThread::setRightTransfer(const bool doRightTransfer)
{
	this->doRightTransfer=doRightTransfer;
}

//set keep date
void TransferThread::setKeepDate(const bool keepDate)
{
	this->keepDate=keepDate;
}

//set the current max speed in KB/s
void TransferThread::setMaxSpeed(int maxSpeed)
{
	int interval=readThread.setMaxSpeed(maxSpeed);
	if(maxSpeed>0)
	{
		clockForTheCopySpeed.setInterval(interval);
		if(!clockForTheCopySpeed.isActive())//seam useless !this->isFinished()
			clockForTheCopySpeed.start();
	}
	else
	{
		if(clockForTheCopySpeed.isActive())
			clockForTheCopySpeed.stop();
	}
}

//set block size in KB
bool TransferThread::setBlockSize(const unsigned int blockSize)
{
	this->blockSize=blockSize;
	return readThread.setBlockSize(blockSize);
}

//pause the copy
void TransferThread::pause()
{
	readThread.pause();
}

//resume the copy
void TransferThread::resume()
{
	readThread.resume();
}

//stop the current copy
void TransferThread::stop()
{
	stopIt=true;
	readThread.stop();
	writeThread.stop();
}

void TransferThread::readIsFinish()
{
	if(readIsFinishVariable)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] double event dropped");
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	readIsFinishVariable=true;
	canStartTransfer=false;
	stat=PostTransfer;
	emit pushStat(stat,transferId);
}

void TransferThread::readIsClosed()
{
	if(readIsClosedVariable)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] double event dropped");
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	readIsClosedVariable=true;
	checkIfAllIsClosed();
}

void TransferThread::writeIsClosed()
{
	if(writeIsClosedVariable)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] double event dropped");
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	writeIsClosedVariable=true;
	checkIfAllIsClosed();
}

bool TransferThread::checkIfAllIsClosed()
{
	if((readError || writeError) && !needSkip)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] resolve error before progress");
		return false;
	}
	if((!readIsReadyVariable || readIsClosedVariable) && (!writeIsReadyVariable || writeIsClosedVariable))
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] emit internalStartPostOperation() to do the real post operation");
		stat=PostOperation;
		//emit pushStat(stat,transferId);
		emit internalStartPostOperation();
		return true;
	}
	else
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] wait self close");
		return false;
	}
}

/// \todo found way to retry that's
/// \todo the rights copy
void TransferThread::postOperation()
{
	if(stat!=PostOperation)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] need be in transfer, source: "+source+", destination: "+destination+", stat:"+QString::number(stat));
		return;
	}
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	//all except closing
	if((readError || writeError) && !needSkip)//normally useless by checkIfAllIsFinish()
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] resume after error");
		return;
	}

	if(!needSkip)
	{
		if(!doFilePostOperation())
			return;

		//remove source in moving mode
		if(mode==Move && !canBeMovedDirectlyVariable)
		{
			if(QFile::exists(destination))
			{
				QFile sourceFile(source);
				if(!sourceFile.remove())
				{
					emit errorOnFile(sourceInfo,sourceFile.errorString());
					return;
				}
			}
			else
				ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] try remove source but destination not exists!");
		}
	}
	else//do difference skip a file and skip this error case
	{
		if(needRemove && QFile::exists(destination))
		{
			QFile destinationFile(destination);
			if(!destinationFile.remove())
			{
				//emit errorOnFile(sourceInfo,destinationFile.errorString());
				//return;
			}
		}
		else
			ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] try remove destination but not exists!");
	}
	stat=Idle;
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] emit postOperationStopped()");
	emit postOperationStopped();
}

bool TransferThread::doFilePostOperation()
{
	//do operation needed by copy
	if(!canBeMovedDirectlyVariable)
	{
		//set the time if no write thread used
		if(keepDate)
			changeFileDateTime(destination,source);//can't do that's after move because after move the source not exist
			/*
			  ignore it, because need correct management, mainly with move
			if(!)
			{
				emit errorOnFile(destinationInfo,tr("Unable to change the date"));//destination.errorString()
				return false;
			}*/
	}

	if(stopIt)
		return false;

	return true;
}

//////////////////////////////////////////////////////////////////
/////////////////////// Error management /////////////////////////
//////////////////////////////////////////////////////////////////

void TransferThread::getWriteError()
{
        if(writeError)
        {
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] already in write error!");
                return;
        }
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	writeError			= true;
	writeIsReadyVariable		= false;
	writeError_source_seeked	= false;
	writeError_destination_reopened	= false;
	emit errorOnFile(destinationInfo,writeThread.errorString());
}

void TransferThread::getReadError()
{
        if(readError)
        {
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] already in read error!");
                return;
        }
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	readError		= true;
	writeIsReadyVariable	= false;
	readIsReadyVariable	= false;
	emit errorOnFile(sourceInfo,readThread.errorString());
}

//retry after error
void TransferThread::retryAfterError()
{
	//opening error
	if(stat==PreOperation)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] is not idle, source: "+source+", destination: "+destination+", stat: "+QString::number(stat));
		tryOpen();
		return;
	}
	//data streaming error
	if(stat!=PostOperation && stat!=Transfer)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Critical,"["+QString::number(id)+"] is not idle, source: "+source+", destination: "+destination+", stat: "+QString::number(stat));
		return;
	}
	if(canBeMovedDirectlyVariable)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] retry the system move");
		tryMoveDirectly();
		return;
	}
	if(writeError)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start and resume the write error");
		readThread.seekToZeroAndWait();
		writeThread.reopen();
	}
	else if(readError)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start and resume the read error");
		readThread.reopen();
	}
	else
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] unknow error resume");
}

void TransferThread::writeThreadIsReopened()
{
	if(writeError_destination_reopened)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] double event dropped");
		return;
	}
	writeError_destination_reopened=true;
	if(writeError_source_seeked && writeError_destination_reopened)
		resumeTransferAfterWriteError();
}

void TransferThread::readThreadIsSeekToZeroAndWait()
{
	if(writeError_source_seeked)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] double event dropped");
		return;
	}
	writeError_source_seeked=true;
	if(writeError_source_seeked && writeError_destination_reopened)
		resumeTransferAfterWriteError();
}

void TransferThread::resumeTransferAfterWriteError()
{
	writeError=false;
/********************************
 if(canStartTransfer)
	 readThread.startRead();
useless, because the open destination event
will restart the transfer as normal
*********************************/
/*********************************
if(!canStartTransfer)
	stat=WaitForTheTransfer;
useless because already do at open event
**********************************/
	//if is in wait
	if(!canStartTransfer)
		emit checkIfItCanBeResumed();
}

void TransferThread::readThreadResumeAfterError()
{
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
        readError=false;
        writeIsReady();
        readIsReady();
}

//////////////////////////////////////////////////////////////////
///////////////////////// Normal event ///////////////////////////
//////////////////////////////////////////////////////////////////

void TransferThread::readIsStopped()
{
	if(!sended_state_readStopped)
	{
		sended_state_readStopped=true;
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] emit readIsStopped()");
		emit readStopped();
	}
	else
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] drop dual read stopped");
}

void TransferThread::writeIsStopped()
{
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start");
	if(!sended_state_writeStopped)
	{
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] emit writeStopped()");
		sended_state_writeStopped=true;
		emit writeStopped();
	}
	else
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] double event dropped");
}

void TransferThread::timeOfTheBlockCopyFinished()
{
	readThread.timeOfTheBlockCopyFinished();
}

//get drive of an file or folder
QString TransferThread::getDrive(QString fileOrFolder)
{
	for (int i = 0; i < mountSysPoint.size(); ++i) {
		if(fileOrFolder.startsWith(mountSysPoint.at(i)))
			return mountSysPoint.at(i);
	}
	//if unable to locate the right mount point
	return "";
}

//set drive list, used in getDrive()
void TransferThread::setDrive(QStringList drives)
{
	mountSysPoint=drives;
}

//fonction to edit the file date time
bool TransferThread::changeFileDateTime(const QString &source,const QString &destination)
{
	/*
	  if(maxTime>=sourceInfo.lastModified())
		return;
	  */
	QFileInfo fileInfo(destination);
	time_t ctime=fileInfo.created().toTime_t();
	time_t actime=fileInfo.lastRead().toTime_t();
	time_t modtime=fileInfo.lastModified().toTime_t();
	#ifdef Q_CC_GNU
		//this function avalaible on unix and mingw
		utimbuf butime;
		butime.actime=actime;
		butime.modtime=modtime;
		//creation time not exists into unix world
		Q_UNUSED(ctime)
		return utime(source.toLatin1().data(),&butime)==0;
	#else
		return false;
	#endif
	return true;
}

//skip the copy
void TransferThread::skip()
{
	ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] start with stat: "+QString::number(stat));
	switch(stat)
	{
	case PreOperation:
	case WaitForTheTransfer:
		needSkip=true;
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] case WaitForTheTransfer or PreOperation, readIsReadyVariable: "+QString::number(readIsReadyVariable)+", readIsClosedVariable: "+QString::number(readIsClosedVariable)+", writeIsReadyVariable: "+QString::number(writeIsReadyVariable)+", writeIsClosedVariable: "+QString::number(writeIsClosedVariable));
		//check if all is source and destination is closed
		if(!checkIfAllIsClosed())
		{
			if(readIsReadyVariable && !readIsClosedVariable)
				readThread.stop();
			if(writeIsReadyVariable && !writeIsClosedVariable)
				writeThread.stop();
		}
		break;
	case Transfer:
		needSkip=true;
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Notice,"["+QString::number(id)+"] case Transfer, readIsReadyVariable: "+QString::number(readIsReadyVariable)+", readIsClosedVariable: "+QString::number(readIsClosedVariable)+", writeIsReadyVariable: "+QString::number(writeIsReadyVariable)+", writeIsClosedVariable: "+QString::number(writeIsClosedVariable));
		if(!checkIfAllIsClosed())
		{
			if(readIsReadyVariable && !readIsClosedVariable)
				readThread.stop();
			if(writeIsReadyVariable && !writeIsClosedVariable)
				writeThread.stop();
		}
		break;
	case PostOperation:
		//do nothing because here is closing...
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] is already in post op");
		break;
	default:
		ULTRACOPIER_DEBUGCONSOLE(DebugLevel_Warning,"["+QString::number(id)+"] can skip in this state!");
		return;
	}
}

//return info about the copied size
qint64 TransferThread::copiedSize()
{
	switch(stat)
	{
	case Transfer:
	case PostOperation:
		return readThread.getLastGoodPosition();
	default:
		return 0;
	}
}

//retry after error
void TransferThread::putAtBottom()
{
	emit tryPutAtBottom();
}

#ifdef ULTRACOPIER_PLUGIN_DEBUG
//to set the id
void TransferThread::setId(int id)
{
	this->id=id;
	readThread.setId(id);
	writeThread.setId(id);
}

QChar TransferThread::readingLetter()
{
	switch(readThread.stat)
	{
	case ReadThread::Idle:
		return '_';
	break;
	case ReadThread::InodeOperation:
		return 'I';
	break;
	case ReadThread::Read:
		return 'R';
	break;
	case ReadThread::WaitWritePipe:
		return 'W';
	break;
	default:
		return '?';
	}
}

QChar TransferThread::writingLetter()
{
	switch(writeThread.stat)
	{
	case WriteThread::Idle:
		return '_';
	break;
	case WriteThread::InodeOperation:
		return 'I';
	break;
	case WriteThread::Write:
		return 'W';
	break;
	case WriteThread::Close:
		return 'C';
	break;
	default:
		return '?';
	}
}

#endif

void TransferThread::setMkpathTransfer(QSemaphore *mkpathTransfer)
{
	this->mkpathTransfer=mkpathTransfer;
	writeThread.setMkpathTransfer(mkpathTransfer);
}