Queue.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Common.h"
  5. #include "Terminal.h"
  6. #include "Queue.h"
  7. #include "Exceptions.h"
  8. #include <System.DateUtils.hpp>
  9. //---------------------------------------------------------------------------
  10. #pragma package(smart_init)
  11. //---------------------------------------------------------------------------
  12. class TBackgroundTerminal;
  13. //---------------------------------------------------------------------------
  14. class TParallelTransferQueueItem : public TLocatedQueueItem
  15. {
  16. public:
  17. __fastcall TParallelTransferQueueItem(const TLocatedQueueItem * ParentItem, TParallelOperation * ParallelOperation);
  18. protected:
  19. virtual void __fastcall DoExecute(TTerminal * Terminal);
  20. private:
  21. TParallelOperation * FParallelOperation;
  22. };
  23. //---------------------------------------------------------------------------
  24. class TUserAction
  25. {
  26. public:
  27. virtual __fastcall ~TUserAction() {}
  28. virtual void __fastcall Execute(void * Arg) = 0;
  29. virtual bool __fastcall Force() { return false; }
  30. };
  31. //---------------------------------------------------------------------------
  32. class TNotifyAction : public TUserAction
  33. {
  34. public:
  35. TNotifyAction(TNotifyEvent AOnNotify) :
  36. OnNotify(AOnNotify)
  37. {
  38. }
  39. virtual void __fastcall Execute(void * Arg)
  40. {
  41. if (OnNotify != NULL)
  42. {
  43. OnNotify(Sender);
  44. }
  45. }
  46. TNotifyEvent OnNotify;
  47. TObject * Sender;
  48. };
  49. //---------------------------------------------------------------------------
  50. class TInformationUserAction : public TUserAction
  51. {
  52. public:
  53. TInformationUserAction(TInformationEvent AOnInformation) :
  54. OnInformation(AOnInformation)
  55. {
  56. }
  57. virtual void __fastcall Execute(void * Arg)
  58. {
  59. if (OnInformation != NULL)
  60. {
  61. OnInformation(Terminal, Str, Phase, Additional);
  62. }
  63. }
  64. virtual bool __fastcall Force()
  65. {
  66. // we need to propagate mainly the end-phase event even, when user cancels
  67. // the connection, so that authentication window is closed
  68. return TUserAction::Force() || (Phase >= 0);
  69. }
  70. TInformationEvent OnInformation;
  71. TTerminal * Terminal;
  72. UnicodeString Str;
  73. int Phase;
  74. UnicodeString Additional;
  75. };
  76. //---------------------------------------------------------------------------
  77. class TQueryUserAction : public TUserAction
  78. {
  79. public:
  80. TQueryUserAction(TQueryUserEvent AOnQueryUser) :
  81. OnQueryUser(AOnQueryUser)
  82. {
  83. }
  84. virtual void __fastcall Execute(void * Arg)
  85. {
  86. if (OnQueryUser != NULL)
  87. {
  88. OnQueryUser(Sender, Query, MoreMessages, Answers, Params, Answer, Type, Arg);
  89. }
  90. }
  91. TQueryUserEvent OnQueryUser;
  92. TObject * Sender;
  93. UnicodeString Query;
  94. TStrings * MoreMessages;
  95. unsigned int Answers;
  96. const TQueryParams * Params;
  97. unsigned int Answer;
  98. TQueryType Type;
  99. };
  100. //---------------------------------------------------------------------------
  101. class TPromptUserAction : public TUserAction
  102. {
  103. public:
  104. __fastcall TPromptUserAction(TPromptUserEvent AOnPromptUser) :
  105. OnPromptUser(AOnPromptUser), Results(new TStringList())
  106. {
  107. }
  108. virtual __fastcall ~TPromptUserAction()
  109. {
  110. delete Results;
  111. }
  112. virtual void __fastcall Execute(void * Arg)
  113. {
  114. if (OnPromptUser != NULL)
  115. {
  116. OnPromptUser(Terminal, Kind, Name, Instructions, Prompts, Results, Result, Arg);
  117. }
  118. }
  119. TPromptUserEvent OnPromptUser;
  120. TTerminal * Terminal;
  121. TPromptKind Kind;
  122. UnicodeString Name;
  123. UnicodeString Instructions;
  124. TStrings * Prompts;
  125. TStrings * Results;
  126. bool Result;
  127. };
  128. //---------------------------------------------------------------------------
  129. class TShowExtendedExceptionAction : public TUserAction
  130. {
  131. public:
  132. __fastcall TShowExtendedExceptionAction(TExtendedExceptionEvent AOnShowExtendedException) :
  133. OnShowExtendedException(AOnShowExtendedException)
  134. {
  135. }
  136. virtual void __fastcall Execute(void * Arg)
  137. {
  138. if (OnShowExtendedException != NULL)
  139. {
  140. OnShowExtendedException(Terminal, E, Arg);
  141. }
  142. }
  143. TExtendedExceptionEvent OnShowExtendedException;
  144. TTerminal * Terminal;
  145. Exception * E;
  146. };
  147. //---------------------------------------------------------------------------
  148. class TDisplayBannerAction : public TUserAction
  149. {
  150. public:
  151. __fastcall TDisplayBannerAction (TDisplayBannerEvent AOnDisplayBanner) :
  152. OnDisplayBanner(AOnDisplayBanner)
  153. {
  154. }
  155. virtual void __fastcall Execute(void * Arg)
  156. {
  157. if (OnDisplayBanner != NULL)
  158. {
  159. OnDisplayBanner(Terminal, SessionName, Banner, NeverShowAgain, Options, Params);
  160. }
  161. }
  162. TDisplayBannerEvent OnDisplayBanner;
  163. TTerminal * Terminal;
  164. UnicodeString SessionName;
  165. UnicodeString Banner;
  166. bool NeverShowAgain;
  167. int Options;
  168. unsigned int Params;
  169. };
  170. //---------------------------------------------------------------------------
  171. class TReadDirectoryAction : public TUserAction
  172. {
  173. public:
  174. TReadDirectoryAction(TReadDirectoryEvent AOnReadDirectory) :
  175. OnReadDirectory(AOnReadDirectory)
  176. {
  177. }
  178. virtual void __fastcall Execute(void * Arg)
  179. {
  180. if (OnReadDirectory != NULL)
  181. {
  182. OnReadDirectory(Sender, ReloadOnly);
  183. }
  184. }
  185. TReadDirectoryEvent OnReadDirectory;
  186. TObject * Sender;
  187. bool ReloadOnly;
  188. };
  189. //---------------------------------------------------------------------------
  190. class TReadDirectoryProgressAction : public TUserAction
  191. {
  192. public:
  193. TReadDirectoryProgressAction(TReadDirectoryProgressEvent AOnReadDirectoryProgress) :
  194. OnReadDirectoryProgress(AOnReadDirectoryProgress)
  195. {
  196. }
  197. virtual void __fastcall Execute(void * Arg)
  198. {
  199. if (OnReadDirectoryProgress != NULL)
  200. {
  201. OnReadDirectoryProgress(Sender, Progress, ResolvedLinks, Cancel);
  202. }
  203. }
  204. TReadDirectoryProgressEvent OnReadDirectoryProgress;
  205. TObject * Sender;
  206. int Progress;
  207. int ResolvedLinks;
  208. bool Cancel;
  209. };
  210. //---------------------------------------------------------------------------
  211. class TTerminalItem : public TSignalThread
  212. {
  213. friend class TQueueItem;
  214. friend class TBackgroundTerminal;
  215. public:
  216. __fastcall TTerminalItem(TTerminalQueue * Queue, int Index);
  217. virtual __fastcall ~TTerminalItem();
  218. void __fastcall Process(TQueueItem * Item);
  219. bool __fastcall ProcessUserAction(void * Arg);
  220. void __fastcall Cancel();
  221. void __fastcall Idle();
  222. bool __fastcall Pause();
  223. bool __fastcall Resume();
  224. bool IsCancelled();
  225. protected:
  226. TTerminalQueue * FQueue;
  227. TBackgroundTerminal * FTerminal;
  228. TQueueItem * FItem;
  229. TCriticalSection * FCriticalSection;
  230. TUserAction * FUserAction;
  231. bool FCancel;
  232. bool FPause;
  233. virtual void __fastcall ProcessEvent();
  234. virtual bool __fastcall Finished();
  235. bool __fastcall WaitForUserAction(TQueueItem::TStatus ItemStatus, TUserAction * UserAction);
  236. bool __fastcall OverrideItemStatus(TQueueItem::TStatus & ItemStatus);
  237. void __fastcall TerminalQueryUser(TObject * Sender,
  238. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  239. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * Arg);
  240. void __fastcall TerminalPromptUser(TTerminal * Terminal, TPromptKind Kind,
  241. UnicodeString Name, UnicodeString Instructions,
  242. TStrings * Prompts, TStrings * Results, bool & Result, void * Arg);
  243. void __fastcall TerminalShowExtendedException(TTerminal * Terminal,
  244. Exception * E, void * Arg);
  245. void __fastcall OperationFinished(TFileOperation Operation, TOperationSide Side,
  246. bool Temp, const UnicodeString & FileName, bool Success, bool NotCancelled,
  247. TOnceDoneOperation & OnceDoneOperation);
  248. void __fastcall OperationProgress(TFileOperationProgressType & ProgressData);
  249. };
  250. //---------------------------------------------------------------------------
  251. // TSignalThread
  252. //---------------------------------------------------------------------------
  253. int __fastcall TSimpleThread::ThreadProc(void * Thread)
  254. {
  255. TSimpleThread * SimpleThread = reinterpret_cast<TSimpleThread*>(Thread);
  256. DebugAssert(SimpleThread != NULL);
  257. try
  258. {
  259. SimpleThread->Execute();
  260. }
  261. catch(...)
  262. {
  263. // we do not expect thread to be terminated with exception
  264. DebugFail();
  265. }
  266. SimpleThread->FFinished = true;
  267. if (SimpleThread->Finished())
  268. {
  269. delete SimpleThread;
  270. }
  271. return 0;
  272. }
  273. //---------------------------------------------------------------------------
  274. __fastcall TSimpleThread::TSimpleThread() :
  275. FThread(NULL), FFinished(true)
  276. {
  277. FThread = reinterpret_cast<HANDLE>(
  278. StartThread(NULL, 0, ThreadProc, this, CREATE_SUSPENDED, FThreadId));
  279. }
  280. //---------------------------------------------------------------------------
  281. __fastcall TSimpleThread::~TSimpleThread()
  282. {
  283. // This is turn calls pure virtual Terminate, what does not work as intended, do not rely on it and remove the call eventually
  284. Close();
  285. if (FThread != NULL)
  286. {
  287. CloseHandle(FThread);
  288. }
  289. }
  290. //---------------------------------------------------------------------------
  291. bool __fastcall TSimpleThread::IsFinished()
  292. {
  293. return FFinished;
  294. }
  295. //---------------------------------------------------------------------------
  296. void __fastcall TSimpleThread::Start()
  297. {
  298. if (ResumeThread(FThread) == 1)
  299. {
  300. FFinished = false;
  301. }
  302. }
  303. //---------------------------------------------------------------------------
  304. bool __fastcall TSimpleThread::Finished()
  305. {
  306. return false;
  307. }
  308. //---------------------------------------------------------------------------
  309. void __fastcall TSimpleThread::Close()
  310. {
  311. if (!FFinished)
  312. {
  313. Terminate();
  314. WaitFor();
  315. }
  316. }
  317. //---------------------------------------------------------------------------
  318. void __fastcall TSimpleThread::WaitFor(unsigned int Milliseconds)
  319. {
  320. WaitForSingleObject(FThread, Milliseconds);
  321. }
  322. //---------------------------------------------------------------------------
  323. // TSignalThread
  324. //---------------------------------------------------------------------------
  325. __fastcall TSignalThread::TSignalThread(bool LowPriority, HANDLE Event) :
  326. TSimpleThread(),
  327. FTerminated(true), FEvent(NULL)
  328. {
  329. if (Event == NULL)
  330. {
  331. FEvent = CreateEvent(NULL, false, false, NULL);
  332. }
  333. else
  334. {
  335. FEvent = Event;
  336. }
  337. DebugAssert(FEvent != NULL);
  338. if (LowPriority)
  339. {
  340. ::SetThreadPriority(FThread, THREAD_PRIORITY_BELOW_NORMAL);
  341. }
  342. }
  343. //---------------------------------------------------------------------------
  344. __fastcall TSignalThread::~TSignalThread()
  345. {
  346. // cannot leave closing to TSimpleThread as we need to close it before
  347. // destroying the event
  348. Close();
  349. if (FEvent)
  350. {
  351. CloseHandle(FEvent);
  352. }
  353. }
  354. //---------------------------------------------------------------------------
  355. void __fastcall TSignalThread::Start()
  356. {
  357. FTerminated = false;
  358. TSimpleThread::Start();
  359. }
  360. //---------------------------------------------------------------------------
  361. void __fastcall TSignalThread::TriggerEvent()
  362. {
  363. SetEvent(FEvent);
  364. }
  365. //---------------------------------------------------------------------------
  366. bool __fastcall TSignalThread::WaitForEvent()
  367. {
  368. // should never return -1, so it is only about 0 or 1
  369. return (WaitForEvent(INFINITE) > 0);
  370. }
  371. //---------------------------------------------------------------------------
  372. int __fastcall TSignalThread::WaitForEvent(unsigned int Timeout)
  373. {
  374. unsigned int Result = WaitForSingleObject(FEvent, Timeout);
  375. int Return;
  376. if ((Result == WAIT_TIMEOUT) && !FTerminated)
  377. {
  378. Return = -1;
  379. }
  380. else
  381. {
  382. Return = ((Result == WAIT_OBJECT_0) && !FTerminated) ? 1 : 0;
  383. }
  384. return Return;
  385. }
  386. //---------------------------------------------------------------------------
  387. void __fastcall TSignalThread::Execute()
  388. {
  389. while (!FTerminated)
  390. {
  391. if (WaitForEvent())
  392. {
  393. ProcessEvent();
  394. }
  395. }
  396. }
  397. //---------------------------------------------------------------------------
  398. void __fastcall TSignalThread::Terminate()
  399. {
  400. FTerminated = true;
  401. TriggerEvent();
  402. }
  403. //---------------------------------------------------------------------------
  404. // TTerminalQueue
  405. //---------------------------------------------------------------------------
  406. __fastcall TTerminalQueue::TTerminalQueue(TTerminal * Terminal,
  407. TConfiguration * Configuration) :
  408. TSignalThread(true),
  409. FTerminal(Terminal), FTransfersLimit(2), FKeepDoneItemsFor(0), FEnabled(true),
  410. FConfiguration(Configuration), FSessionData(NULL), FItems(NULL), FDoneItems(NULL),
  411. FTerminals(NULL), FItemsSection(NULL), FFreeTerminals(0),
  412. FItemsInProcess(0), FTemporaryTerminals(0), FOverallTerminals(0)
  413. {
  414. FOnQueryUser = NULL;
  415. FOnPromptUser = NULL;
  416. FOnShowExtendedException = NULL;
  417. FOnQueueItemUpdate = NULL;
  418. FOnListUpdate = NULL;
  419. FOnEvent = NULL;
  420. FLastIdle = Now();
  421. FIdleInterval = EncodeTimeVerbose(0, 0, 2, 0);
  422. DebugAssert(Terminal != NULL);
  423. FSessionData = new TSessionData(L"");
  424. FSessionData->Assign(Terminal->SessionData);
  425. FItems = new TList();
  426. FDoneItems = new TList();
  427. FTerminals = new TList();
  428. FForcedItems = new TList();
  429. FItemsSection = new TCriticalSection();
  430. Start();
  431. }
  432. //---------------------------------------------------------------------------
  433. __fastcall TTerminalQueue::~TTerminalQueue()
  434. {
  435. Close();
  436. {
  437. TGuard Guard(FItemsSection);
  438. TTerminalItem * TerminalItem;
  439. while (FTerminals->Count > 0)
  440. {
  441. TerminalItem = reinterpret_cast<TTerminalItem*>(FTerminals->Items[0]);
  442. FTerminals->Delete(0);
  443. TerminalItem->Terminate();
  444. TerminalItem->WaitFor();
  445. delete TerminalItem;
  446. }
  447. delete FTerminals;
  448. delete FForcedItems;
  449. FreeItemsList(FItems);
  450. FreeItemsList(FDoneItems);
  451. }
  452. delete FItemsSection;
  453. delete FSessionData;
  454. }
  455. //---------------------------------------------------------------------------
  456. void __fastcall TTerminalQueue::FreeItemsList(TList * List)
  457. {
  458. for (int Index = 0; Index < List->Count; Index++)
  459. {
  460. delete GetItem(List, Index);
  461. }
  462. delete List;
  463. }
  464. //---------------------------------------------------------------------------
  465. void __fastcall TTerminalQueue::TerminalFinished(TTerminalItem * TerminalItem)
  466. {
  467. if (!FTerminated)
  468. {
  469. {
  470. TGuard Guard(FItemsSection);
  471. int Index = FTerminals->IndexOf(TerminalItem);
  472. DebugAssert(Index >= 0);
  473. if (Index < FFreeTerminals)
  474. {
  475. FFreeTerminals--;
  476. }
  477. // Index may be >= FTransfersLimit also when the transfer limit was
  478. // recently decreased, then
  479. // FTemporaryTerminals < FTerminals->Count - FTransfersLimit
  480. if ((FTransfersLimit >= 0) && (Index >= FTransfersLimit) && (FTemporaryTerminals > 0))
  481. {
  482. FTemporaryTerminals--;
  483. }
  484. FTerminals->Extract(TerminalItem);
  485. delete TerminalItem;
  486. }
  487. TriggerEvent();
  488. }
  489. }
  490. //---------------------------------------------------------------------------
  491. bool __fastcall TTerminalQueue::TerminalFree(TTerminalItem * TerminalItem)
  492. {
  493. bool Result = true;
  494. if (!FTerminated)
  495. {
  496. {
  497. TGuard Guard(FItemsSection);
  498. int Index = FTerminals->IndexOf(TerminalItem);
  499. DebugAssert(Index >= 0);
  500. DebugAssert(Index >= FFreeTerminals);
  501. Result = (FTransfersLimit < 0) || (Index < FTransfersLimit);
  502. if (Result)
  503. {
  504. FTerminals->Move(Index, 0);
  505. FFreeTerminals++;
  506. }
  507. }
  508. TriggerEvent();
  509. }
  510. return Result;
  511. }
  512. //---------------------------------------------------------------------------
  513. int __fastcall TTerminalQueue::GetParallelDurationThreshold()
  514. {
  515. return FConfiguration->ParallelDurationThreshold;
  516. }
  517. //---------------------------------------------------------------------------
  518. void __fastcall TTerminalQueue::AddItem(TQueueItem * Item)
  519. {
  520. DebugAssert(!FTerminated);
  521. Item->SetStatus(TQueueItem::qsPending);
  522. {
  523. TGuard Guard(FItemsSection);
  524. FItems->Add(Item);
  525. Item->FQueue = this;
  526. }
  527. DoListUpdate();
  528. TriggerEvent();
  529. }
  530. //---------------------------------------------------------------------------
  531. void __fastcall TTerminalQueue::RetryItem(TQueueItem * Item)
  532. {
  533. if (!FTerminated)
  534. {
  535. {
  536. TGuard Guard(FItemsSection);
  537. int Index = FItems->Remove(Item);
  538. DebugAssert(Index < FItemsInProcess);
  539. DebugUsedParam(Index);
  540. FItemsInProcess--;
  541. FItems->Add(Item);
  542. }
  543. DoListUpdate();
  544. TriggerEvent();
  545. }
  546. }
  547. //---------------------------------------------------------------------------
  548. void __fastcall TTerminalQueue::DeleteItem(TQueueItem * Item, bool CanKeep)
  549. {
  550. if (!FTerminated)
  551. {
  552. bool Empty;
  553. bool EmptyButMonitored;
  554. bool Monitored;
  555. {
  556. TGuard Guard(FItemsSection);
  557. // does this need to be within guard?
  558. Monitored = (Item->CompleteEvent != INVALID_HANDLE_VALUE);
  559. int Index = FItems->Remove(Item);
  560. DebugAssert(Index < FItemsInProcess);
  561. DebugUsedParam(Index);
  562. FItemsInProcess--;
  563. FForcedItems->Remove(Item);
  564. // =0 do not keep
  565. // <0 infinity
  566. if ((FKeepDoneItemsFor != 0) && CanKeep && Item->Complete())
  567. {
  568. DebugAssert(Item->Status == TQueueItem::qsDone);
  569. FDoneItems->Add(Item);
  570. }
  571. else
  572. {
  573. delete Item;
  574. }
  575. EmptyButMonitored = true;
  576. Index = 0;
  577. while (EmptyButMonitored && (Index < FItems->Count))
  578. {
  579. EmptyButMonitored = (GetItem(FItems, Index)->CompleteEvent != INVALID_HANDLE_VALUE);
  580. Index++;
  581. }
  582. Empty = (FItems->Count == 0);
  583. }
  584. DoListUpdate();
  585. // report empty but/except for monitored, if queue is empty or only monitored items are pending.
  586. // do not report if current item was the last, but was monitored.
  587. if (!Monitored && EmptyButMonitored)
  588. {
  589. DoEvent(qeEmptyButMonitored);
  590. }
  591. if (Empty)
  592. {
  593. DoEvent(qeEmpty);
  594. }
  595. }
  596. }
  597. //---------------------------------------------------------------------------
  598. TQueueItem * __fastcall TTerminalQueue::GetItem(TList * List, int Index)
  599. {
  600. return reinterpret_cast<TQueueItem*>(List->Items[Index]);
  601. }
  602. //---------------------------------------------------------------------------
  603. TQueueItem * __fastcall TTerminalQueue::GetItem(int Index)
  604. {
  605. return GetItem(FItems, Index);
  606. }
  607. //---------------------------------------------------------------------------
  608. void __fastcall TTerminalQueue::UpdateStatusForList(
  609. TTerminalQueueStatus * Status, TList * List, TTerminalQueueStatus * Current)
  610. {
  611. TQueueItem * Item;
  612. TQueueItemProxy * ItemProxy;
  613. for (int Index = 0; Index < List->Count; Index++)
  614. {
  615. Item = GetItem(List, Index);
  616. if (Current != NULL)
  617. {
  618. ItemProxy = Current->FindByQueueItem(Item);
  619. }
  620. else
  621. {
  622. ItemProxy = NULL;
  623. }
  624. if (ItemProxy != NULL)
  625. {
  626. Current->Delete(ItemProxy);
  627. Status->Add(ItemProxy);
  628. ItemProxy->Update();
  629. }
  630. else
  631. {
  632. Status->Add(new TQueueItemProxy(this, Item));
  633. }
  634. }
  635. }
  636. //---------------------------------------------------------------------------
  637. TTerminalQueueStatus * __fastcall TTerminalQueue::CreateStatus(TTerminalQueueStatus * Current)
  638. {
  639. TTerminalQueueStatus * Status = new TTerminalQueueStatus();
  640. try
  641. {
  642. try
  643. {
  644. TGuard Guard(FItemsSection);
  645. UpdateStatusForList(Status, FDoneItems, Current);
  646. Status->SetDoneCount(Status->Count);
  647. UpdateStatusForList(Status, FItems, Current);
  648. }
  649. __finally
  650. {
  651. if (Current != NULL)
  652. {
  653. delete Current;
  654. }
  655. }
  656. }
  657. catch(...)
  658. {
  659. delete Status;
  660. throw;
  661. }
  662. return Status;
  663. }
  664. //---------------------------------------------------------------------------
  665. bool __fastcall TTerminalQueue::ItemGetData(TQueueItem * Item, TQueueItemProxy * Proxy, TQueueFileList * FileList)
  666. {
  667. // to prevent deadlocks when closing queue from other thread
  668. bool Result = !FFinished;
  669. if (Result)
  670. {
  671. TGuard Guard(FItemsSection);
  672. Result = (FDoneItems->IndexOf(Item) >= 0) || (FItems->IndexOf(Item) >= 0);
  673. if (Result)
  674. {
  675. if (FileList != NULL)
  676. {
  677. Result = Item->UpdateFileList(FileList);
  678. }
  679. else
  680. {
  681. Item->GetData(Proxy);
  682. }
  683. }
  684. }
  685. return Result;
  686. }
  687. //---------------------------------------------------------------------------
  688. bool __fastcall TTerminalQueue::ItemProcessUserAction(TQueueItem * Item, void * Arg)
  689. {
  690. // to prevent deadlocks when closing queue from other thread
  691. bool Result = !FFinished;
  692. if (Result)
  693. {
  694. TTerminalItem * TerminalItem;
  695. {
  696. TGuard Guard(FItemsSection);
  697. Result = (FItems->IndexOf(Item) >= 0) &&
  698. TQueueItem::IsUserActionStatus(Item->Status);
  699. if (Result)
  700. {
  701. TerminalItem = Item->FTerminalItem;
  702. }
  703. }
  704. if (Result)
  705. {
  706. Result = TerminalItem->ProcessUserAction(Arg);
  707. }
  708. }
  709. return Result;
  710. }
  711. //---------------------------------------------------------------------------
  712. bool __fastcall TTerminalQueue::ItemMove(TQueueItem * Item, TQueueItem * BeforeItem)
  713. {
  714. // to prevent deadlocks when closing queue from other thread
  715. bool Result = !FFinished;
  716. if (Result)
  717. {
  718. {
  719. TGuard Guard(FItemsSection);
  720. int Index = FItems->IndexOf(Item);
  721. int IndexDest = FItems->IndexOf(BeforeItem);
  722. Result = (Index >= 0) && (IndexDest >= 0) &&
  723. (Item->GetStatus() == TQueueItem::qsPending) &&
  724. (BeforeItem->GetStatus() == TQueueItem::qsPending);
  725. if (Result)
  726. {
  727. FItems->Move(Index, IndexDest);
  728. }
  729. }
  730. if (Result)
  731. {
  732. DoListUpdate();
  733. TriggerEvent();
  734. }
  735. }
  736. return Result;
  737. }
  738. //---------------------------------------------------------------------------
  739. bool __fastcall TTerminalQueue::ItemExecuteNow(TQueueItem * Item)
  740. {
  741. // to prevent deadlocks when closing queue from other thread
  742. bool Result = !FFinished;
  743. if (Result)
  744. {
  745. {
  746. TGuard Guard(FItemsSection);
  747. int Index = FItems->IndexOf(Item);
  748. Result = (Index >= 0) && (Item->GetStatus() == TQueueItem::qsPending) &&
  749. // prevent double-initiation when "execute" is clicked twice too fast
  750. (Index >= FItemsInProcess);
  751. if (Result)
  752. {
  753. if (Index > FItemsInProcess)
  754. {
  755. FItems->Move(Index, FItemsInProcess);
  756. }
  757. if ((FTransfersLimit >= 0) && (FTerminals->Count >= FTransfersLimit) &&
  758. // when queue is disabled, we may have idle terminals,
  759. // even when there are pending queue items
  760. (FFreeTerminals == 0))
  761. {
  762. FTemporaryTerminals++;
  763. }
  764. FForcedItems->Add(Item);
  765. }
  766. }
  767. if (Result)
  768. {
  769. DoListUpdate();
  770. TriggerEvent();
  771. }
  772. }
  773. return Result;
  774. }
  775. //---------------------------------------------------------------------------
  776. bool __fastcall TTerminalQueue::ItemDelete(TQueueItem * Item)
  777. {
  778. // to prevent deadlocks when closing queue from other thread
  779. bool Result = !FFinished;
  780. if (Result)
  781. {
  782. bool UpdateList = false;
  783. {
  784. TGuard Guard(FItemsSection);
  785. int Index = FItems->IndexOf(Item);
  786. Result = (Index >= 0);
  787. if (Result)
  788. {
  789. if (Item->Status == TQueueItem::qsPending)
  790. {
  791. FItems->Delete(Index);
  792. FForcedItems->Remove(Item);
  793. delete Item;
  794. UpdateList = true;
  795. }
  796. else
  797. {
  798. Item->FTerminalItem->Cancel();
  799. }
  800. }
  801. else
  802. {
  803. Index = FDoneItems->IndexOf(Item);
  804. Result = (Index >= 0);
  805. if (Result)
  806. {
  807. FDoneItems->Delete(Index);
  808. delete Item;
  809. UpdateList = true;
  810. }
  811. }
  812. }
  813. if (UpdateList)
  814. {
  815. DoListUpdate();
  816. TriggerEvent();
  817. }
  818. }
  819. return Result;
  820. }
  821. //---------------------------------------------------------------------------
  822. bool __fastcall TTerminalQueue::ItemPause(TQueueItem * Item, bool Pause)
  823. {
  824. // to prevent deadlocks when closing queue from other thread
  825. bool Result = !FFinished;
  826. if (Result)
  827. {
  828. TTerminalItem * TerminalItem;
  829. {
  830. TGuard Guard(FItemsSection);
  831. Result = (FItems->IndexOf(Item) >= 0) &&
  832. ((Pause && (Item->Status == TQueueItem::qsProcessing)) ||
  833. (!Pause && (Item->Status == TQueueItem::qsPaused)));
  834. if (Result)
  835. {
  836. TerminalItem = Item->FTerminalItem;
  837. }
  838. }
  839. if (Result)
  840. {
  841. if (Pause)
  842. {
  843. Result = TerminalItem->Pause();
  844. }
  845. else
  846. {
  847. Result = TerminalItem->Resume();
  848. }
  849. }
  850. }
  851. return Result;
  852. }
  853. //---------------------------------------------------------------------------
  854. bool __fastcall TTerminalQueue::ItemSetCPSLimit(TQueueItem * Item, unsigned long CPSLimit)
  855. {
  856. // to prevent deadlocks when closing queue from other thread
  857. bool Result = !FFinished;
  858. if (Result)
  859. {
  860. TGuard Guard(FItemsSection);
  861. Result = (FItems->IndexOf(Item) >= 0);
  862. if (Result)
  863. {
  864. Item->SetCPSLimit(CPSLimit);
  865. }
  866. }
  867. return Result;
  868. }
  869. //---------------------------------------------------------------------------
  870. bool __fastcall TTerminalQueue::ItemGetCPSLimit(TQueueItem * Item, unsigned long & CPSLimit)
  871. {
  872. CPSLimit = 0;
  873. // to prevent deadlocks when closing queue from other thread
  874. bool Result = !FFinished;
  875. if (Result)
  876. {
  877. TGuard Guard(FItemsSection);
  878. Result = (FItems->IndexOf(Item) >= 0);
  879. if (Result)
  880. {
  881. CPSLimit = Item->GetCPSLimit();
  882. }
  883. }
  884. return Result;
  885. }
  886. //---------------------------------------------------------------------------
  887. void __fastcall TTerminalQueue::Idle()
  888. {
  889. TDateTime N = Now();
  890. if (N - FLastIdle > FIdleInterval)
  891. {
  892. FLastIdle = N;
  893. TTerminalItem * TerminalItem = NULL;
  894. if (FFreeTerminals > 0)
  895. {
  896. TGuard Guard(FItemsSection);
  897. if (FFreeTerminals > 0)
  898. {
  899. // take the last free terminal, because TerminalFree() puts it to the
  900. // front, this ensures we cycle thru all free terminals
  901. TerminalItem = reinterpret_cast<TTerminalItem*>(FTerminals->Items[FFreeTerminals - 1]);
  902. FTerminals->Move(FFreeTerminals - 1, FTerminals->Count - 1);
  903. FFreeTerminals--;
  904. }
  905. }
  906. if (TerminalItem != NULL)
  907. {
  908. TerminalItem->Idle();
  909. }
  910. }
  911. }
  912. //---------------------------------------------------------------------------
  913. bool __fastcall TTerminalQueue::WaitForEvent()
  914. {
  915. // terminate loop regularly, so that we can check for expired done items
  916. bool Result = (TSignalThread::WaitForEvent(1000) != 0);
  917. return Result;
  918. }
  919. //---------------------------------------------------------------------------
  920. void __fastcall TTerminalQueue::ProcessEvent()
  921. {
  922. TTerminalItem * TerminalItem;
  923. TQueueItem * Item;
  924. do
  925. {
  926. TerminalItem = NULL;
  927. Item = NULL;
  928. {
  929. TGuard Guard(FItemsSection);
  930. // =0 do not keep
  931. // <0 infinity
  932. if (FKeepDoneItemsFor >= 0)
  933. {
  934. TDateTime RemoveDoneItemsBefore = Now();
  935. if (FKeepDoneItemsFor > 0)
  936. {
  937. RemoveDoneItemsBefore = IncSecond(RemoveDoneItemsBefore, -FKeepDoneItemsFor);
  938. }
  939. for (int Index = 0; Index < FDoneItems->Count; Index++)
  940. {
  941. TQueueItem * Item = GetItem(FDoneItems, Index);
  942. if (Item->FDoneAt <= RemoveDoneItemsBefore)
  943. {
  944. FDoneItems->Delete(Index);
  945. delete Item;
  946. Index--;
  947. DoListUpdate();
  948. }
  949. }
  950. }
  951. if (FItems->Count > FItemsInProcess)
  952. {
  953. Item = GetItem(FItemsInProcess);
  954. int ForcedIndex = FForcedItems->IndexOf(Item);
  955. if (FEnabled || (ForcedIndex >= 0))
  956. {
  957. if ((FFreeTerminals == 0) &&
  958. ((FTransfersLimit < 0) ||
  959. (FTerminals->Count < FTransfersLimit + FTemporaryTerminals)))
  960. {
  961. FOverallTerminals++;
  962. TerminalItem = new TTerminalItem(this, FOverallTerminals);
  963. FTerminals->Add(TerminalItem);
  964. }
  965. else if (FFreeTerminals > 0)
  966. {
  967. TerminalItem = reinterpret_cast<TTerminalItem*>(FTerminals->Items[0]);
  968. FTerminals->Move(0, FTerminals->Count - 1);
  969. FFreeTerminals--;
  970. }
  971. if (TerminalItem != NULL)
  972. {
  973. if (ForcedIndex >= 0)
  974. {
  975. FForcedItems->Delete(ForcedIndex);
  976. }
  977. FItemsInProcess++;
  978. }
  979. }
  980. }
  981. }
  982. if (TerminalItem != NULL)
  983. {
  984. TerminalItem->Process(Item);
  985. }
  986. }
  987. while (!FTerminated && (TerminalItem != NULL));
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TTerminalQueue::DoQueueItemUpdate(TQueueItem * Item)
  991. {
  992. if (OnQueueItemUpdate != NULL)
  993. {
  994. OnQueueItemUpdate(this, Item);
  995. }
  996. }
  997. //---------------------------------------------------------------------------
  998. void __fastcall TTerminalQueue::DoListUpdate()
  999. {
  1000. if (OnListUpdate != NULL)
  1001. {
  1002. OnListUpdate(this);
  1003. }
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. void __fastcall TTerminalQueue::DoEvent(TQueueEvent Event)
  1007. {
  1008. if (OnEvent != NULL)
  1009. {
  1010. OnEvent(this, Event);
  1011. }
  1012. }
  1013. //---------------------------------------------------------------------------
  1014. void __fastcall TTerminalQueue::SetTransfersLimit(int value)
  1015. {
  1016. if (FTransfersLimit != value)
  1017. {
  1018. {
  1019. TGuard Guard(FItemsSection);
  1020. if ((value >= 0) && (value < FItemsInProcess))
  1021. {
  1022. FTemporaryTerminals = (FItemsInProcess - value);
  1023. }
  1024. else
  1025. {
  1026. FTemporaryTerminals = 0;
  1027. }
  1028. FTransfersLimit = value;
  1029. }
  1030. TriggerEvent();
  1031. }
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. void __fastcall TTerminalQueue::SetKeepDoneItemsFor(int value)
  1035. {
  1036. if (FKeepDoneItemsFor != value)
  1037. {
  1038. {
  1039. TGuard Guard(FItemsSection);
  1040. FKeepDoneItemsFor = value;
  1041. }
  1042. }
  1043. }
  1044. //---------------------------------------------------------------------------
  1045. void __fastcall TTerminalQueue::SetEnabled(bool value)
  1046. {
  1047. if (FEnabled != value)
  1048. {
  1049. {
  1050. TGuard Guard(FItemsSection);
  1051. FEnabled = value;
  1052. }
  1053. TriggerEvent();
  1054. }
  1055. }
  1056. //---------------------------------------------------------------------------
  1057. bool __fastcall TTerminalQueue::GetIsEmpty()
  1058. {
  1059. TGuard Guard(FItemsSection);
  1060. return (FItems->Count == 0);
  1061. }
  1062. //---------------------------------------------------------------------------
  1063. bool __fastcall TTerminalQueue::TryAddParallelOperation(TQueueItem * Item, bool Force)
  1064. {
  1065. TGuard Guard(FItemsSection);
  1066. bool Result =
  1067. (FFreeTerminals > 0) ||
  1068. (Force && (FItemsInProcess < FTransfersLimit));
  1069. if (Result)
  1070. {
  1071. TQueueItem * ParallelItem = DebugNotNull(Item->CreateParallelOperation());
  1072. if (!FEnabled)
  1073. {
  1074. FForcedItems->Add(ParallelItem);
  1075. }
  1076. AddItem(ParallelItem);
  1077. }
  1078. return Result;
  1079. }
  1080. //---------------------------------------------------------------------------
  1081. bool __fastcall TTerminalQueue::ContinueParallelOperation()
  1082. {
  1083. TGuard Guard(FItemsSection);
  1084. return
  1085. (FItems->Count <= FItemsInProcess) ||
  1086. // When queue auto processing is not enabled, keep using all connections for the transfers that were manually started
  1087. !FEnabled;
  1088. }
  1089. //---------------------------------------------------------------------------
  1090. // TBackgroundItem
  1091. //---------------------------------------------------------------------------
  1092. class TBackgroundTerminal : public TSecondaryTerminal
  1093. {
  1094. friend class TTerminalItem;
  1095. public:
  1096. __fastcall TBackgroundTerminal(TTerminal * MainTerminal,
  1097. TSessionData * SessionData, TConfiguration * Configuration,
  1098. TTerminalItem * Item, const UnicodeString & Name);
  1099. protected:
  1100. virtual bool __fastcall DoQueryReopen(Exception * E);
  1101. private:
  1102. TTerminalItem * FItem;
  1103. };
  1104. //---------------------------------------------------------------------------
  1105. __fastcall TBackgroundTerminal::TBackgroundTerminal(TTerminal * MainTerminal,
  1106. TSessionData * SessionData, TConfiguration * Configuration, TTerminalItem * Item,
  1107. const UnicodeString & Name) :
  1108. TSecondaryTerminal(MainTerminal, SessionData, Configuration, Name, NULL), FItem(Item)
  1109. {
  1110. ActionLog->Enabled = false;
  1111. }
  1112. //---------------------------------------------------------------------------
  1113. bool __fastcall TBackgroundTerminal::DoQueryReopen(Exception * /*E*/)
  1114. {
  1115. bool Result;
  1116. if (FItem->IsCancelled())
  1117. {
  1118. // avoid reconnection if we are closing
  1119. Result = false;
  1120. }
  1121. else
  1122. {
  1123. Sleep(Configuration->SessionReopenBackground);
  1124. Result = true;
  1125. }
  1126. return Result;
  1127. }
  1128. //---------------------------------------------------------------------------
  1129. // TTerminalItem
  1130. //---------------------------------------------------------------------------
  1131. __fastcall TTerminalItem::TTerminalItem(TTerminalQueue * Queue, int Index) :
  1132. TSignalThread(true), FQueue(Queue), FTerminal(NULL), FItem(NULL),
  1133. FCriticalSection(NULL), FUserAction(NULL)
  1134. {
  1135. FCriticalSection = new TCriticalSection();
  1136. FTerminal = new TBackgroundTerminal(FQueue->FTerminal, Queue->FSessionData,
  1137. FQueue->FConfiguration, this, FORMAT(L"Background %d", (Index)));
  1138. try
  1139. {
  1140. FTerminal->UseBusyCursor = false;
  1141. FTerminal->OnQueryUser = TerminalQueryUser;
  1142. FTerminal->OnPromptUser = TerminalPromptUser;
  1143. FTerminal->OnShowExtendedException = TerminalShowExtendedException;
  1144. FTerminal->OnProgress = OperationProgress;
  1145. FTerminal->OnFinished = OperationFinished;
  1146. }
  1147. catch(...)
  1148. {
  1149. delete FTerminal;
  1150. throw;
  1151. }
  1152. Start();
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. __fastcall TTerminalItem::~TTerminalItem()
  1156. {
  1157. Close();
  1158. DebugAssert(FItem == NULL);
  1159. delete FTerminal;
  1160. delete FCriticalSection;
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void __fastcall TTerminalItem::Process(TQueueItem * Item)
  1164. {
  1165. {
  1166. TGuard Guard(FCriticalSection);
  1167. DebugAssert(FItem == NULL);
  1168. FItem = Item;
  1169. }
  1170. TriggerEvent();
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. void __fastcall TTerminalItem::ProcessEvent()
  1174. {
  1175. TGuard Guard(FCriticalSection);
  1176. bool Retry = true;
  1177. FCancel = false;
  1178. FPause = false;
  1179. FItem->FTerminalItem = this;
  1180. try
  1181. {
  1182. DebugAssert(FItem != NULL);
  1183. if (!FTerminal->Active)
  1184. {
  1185. FItem->SetStatus(TQueueItem::qsConnecting);
  1186. FTerminal->SessionData->RemoteDirectory = FItem->StartupDirectory();
  1187. FTerminal->Open();
  1188. }
  1189. Retry = false;
  1190. if (!FCancel)
  1191. {
  1192. FTerminal->UpdateFromMain();
  1193. FItem->SetStatus(TQueueItem::qsProcessing);
  1194. FItem->Execute();
  1195. }
  1196. }
  1197. catch(Exception & E)
  1198. {
  1199. UnicodeString Message;
  1200. if (ExceptionMessageFormatted(&E, Message))
  1201. {
  1202. // do not show error messages, if task was canceled anyway
  1203. // (for example if transfer is canceled during reconnection attempts)
  1204. if (!FCancel &&
  1205. (FTerminal->QueryUserException(L"", &E, qaOK | qaCancel, NULL, qtError) == qaCancel))
  1206. {
  1207. FCancel = true;
  1208. }
  1209. }
  1210. }
  1211. FItem->SetStatus(TQueueItem::qsDone);
  1212. FItem->FTerminalItem = NULL;
  1213. TQueueItem * Item = FItem;
  1214. FItem = NULL;
  1215. if (Retry && !FCancel)
  1216. {
  1217. FQueue->RetryItem(Item);
  1218. }
  1219. else
  1220. {
  1221. FQueue->DeleteItem(Item, !FCancel);
  1222. }
  1223. if (!FTerminal->Active ||
  1224. !FQueue->TerminalFree(this))
  1225. {
  1226. Terminate();
  1227. }
  1228. }
  1229. //---------------------------------------------------------------------------
  1230. void __fastcall TTerminalItem::Idle()
  1231. {
  1232. TGuard Guard(FCriticalSection);
  1233. DebugAssert(FTerminal->Active);
  1234. try
  1235. {
  1236. FTerminal->Idle();
  1237. }
  1238. catch(...)
  1239. {
  1240. }
  1241. if (!FTerminal->Active ||
  1242. !FQueue->TerminalFree(this))
  1243. {
  1244. Terminate();
  1245. }
  1246. }
  1247. //---------------------------------------------------------------------------
  1248. void __fastcall TTerminalItem::Cancel()
  1249. {
  1250. FCancel = true;
  1251. if ((FItem->GetStatus() == TQueueItem::qsPaused) ||
  1252. TQueueItem::IsUserActionStatus(FItem->GetStatus()))
  1253. {
  1254. TriggerEvent();
  1255. }
  1256. }
  1257. //---------------------------------------------------------------------------
  1258. bool __fastcall TTerminalItem::Pause()
  1259. {
  1260. DebugAssert(FItem != NULL);
  1261. bool Result = (FItem->GetStatus() == TQueueItem::qsProcessing) && !FPause;
  1262. if (Result)
  1263. {
  1264. FPause = true;
  1265. }
  1266. return Result;
  1267. }
  1268. //---------------------------------------------------------------------------
  1269. bool __fastcall TTerminalItem::Resume()
  1270. {
  1271. DebugAssert(FItem != NULL);
  1272. bool Result = (FItem->GetStatus() == TQueueItem::qsPaused);
  1273. if (Result)
  1274. {
  1275. TriggerEvent();
  1276. }
  1277. return Result;
  1278. }
  1279. //---------------------------------------------------------------------------
  1280. bool __fastcall TTerminalItem::ProcessUserAction(void * Arg)
  1281. {
  1282. // When status is changed twice quickly, the controller when responding
  1283. // to the first change (non-user-action) can be so slow to check only after
  1284. // the second (user-action) change occurs. Thus it responds it.
  1285. // Then as reaction to the second (user-action) change there will not be
  1286. // any outstanding user-action.
  1287. bool Result = (FUserAction != NULL);
  1288. if (Result)
  1289. {
  1290. DebugAssert(FItem != NULL);
  1291. FUserAction->Execute(Arg);
  1292. FUserAction = NULL;
  1293. TriggerEvent();
  1294. }
  1295. return Result;
  1296. }
  1297. //---------------------------------------------------------------------------
  1298. bool __fastcall TTerminalItem::WaitForUserAction(
  1299. TQueueItem::TStatus ItemStatus, TUserAction * UserAction)
  1300. {
  1301. DebugAssert(FItem != NULL);
  1302. DebugAssert((FItem->GetStatus() == TQueueItem::qsProcessing) ||
  1303. (FItem->GetStatus() == TQueueItem::qsConnecting));
  1304. bool Result;
  1305. TQueueItem::TStatus PrevStatus = FItem->GetStatus();
  1306. try
  1307. {
  1308. FUserAction = UserAction;
  1309. FItem->SetStatus(ItemStatus);
  1310. FQueue->DoEvent(qePendingUserAction);
  1311. Result = !FTerminated && WaitForEvent() && !FCancel;
  1312. }
  1313. __finally
  1314. {
  1315. FUserAction = NULL;
  1316. FItem->SetStatus(PrevStatus);
  1317. }
  1318. return Result;
  1319. }
  1320. //---------------------------------------------------------------------------
  1321. bool __fastcall TTerminalItem::Finished()
  1322. {
  1323. bool Result = TSignalThread::Finished();
  1324. FQueue->TerminalFinished(this);
  1325. return Result;
  1326. }
  1327. //---------------------------------------------------------------------------
  1328. void __fastcall TTerminalItem::TerminalQueryUser(TObject * Sender,
  1329. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  1330. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * Arg)
  1331. {
  1332. // so far query without queue item can occur only for key confirmation
  1333. // on re-key with non-cached host key. make it fail.
  1334. if (FItem != NULL)
  1335. {
  1336. DebugUsedParam(Arg);
  1337. DebugAssert(Arg == NULL);
  1338. TQueryUserAction Action(FQueue->OnQueryUser);
  1339. Action.Sender = Sender;
  1340. Action.Query = Query;
  1341. Action.MoreMessages = MoreMessages;
  1342. Action.Answers = Answers;
  1343. Action.Params = Params;
  1344. Action.Answer = Answer;
  1345. Action.Type = Type;
  1346. // if the query is "error", present it as an "error" state in UI,
  1347. // however it is still handled as query by the action.
  1348. TQueueItem::TStatus ItemStatus =
  1349. (Action.Type == qtError ? TQueueItem::qsError : TQueueItem::qsQuery);
  1350. if (WaitForUserAction(ItemStatus, &Action))
  1351. {
  1352. Answer = Action.Answer;
  1353. }
  1354. }
  1355. }
  1356. //---------------------------------------------------------------------------
  1357. void __fastcall TTerminalItem::TerminalPromptUser(TTerminal * Terminal,
  1358. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  1359. TStrings * Results, bool & Result, void * Arg)
  1360. {
  1361. if (FItem == NULL)
  1362. {
  1363. // sanity, should not occur
  1364. DebugFail();
  1365. Result = false;
  1366. }
  1367. else
  1368. {
  1369. DebugUsedParam(Arg);
  1370. DebugAssert(Arg == NULL);
  1371. TPromptUserAction Action(FQueue->OnPromptUser);
  1372. Action.Terminal = Terminal;
  1373. Action.Kind = Kind;
  1374. Action.Name = Name;
  1375. Action.Instructions = Instructions;
  1376. Action.Prompts = Prompts;
  1377. Action.Results->AddStrings(Results);
  1378. if (WaitForUserAction(TQueueItem::qsPrompt, &Action))
  1379. {
  1380. Results->Clear();
  1381. Results->AddStrings(Action.Results);
  1382. Result = Action.Result;
  1383. }
  1384. }
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. void __fastcall TTerminalItem::TerminalShowExtendedException(
  1388. TTerminal * Terminal, Exception * E, void * Arg)
  1389. {
  1390. DebugUsedParam(Arg);
  1391. DebugAssert(Arg == NULL);
  1392. if ((FItem != NULL) &&
  1393. ShouldDisplayException(E))
  1394. {
  1395. TShowExtendedExceptionAction Action(FQueue->OnShowExtendedException);
  1396. Action.Terminal = Terminal;
  1397. Action.E = E;
  1398. WaitForUserAction(TQueueItem::qsError, &Action);
  1399. }
  1400. }
  1401. //---------------------------------------------------------------------------
  1402. void __fastcall TTerminalItem::OperationFinished(TFileOperation /*Operation*/,
  1403. TOperationSide /*Side*/, bool /*Temp*/, const UnicodeString & /*FileName*/,
  1404. bool /*Success*/, bool /*NotCancelled*/, TOnceDoneOperation & /*OnceDoneOperation*/)
  1405. {
  1406. // nothing
  1407. }
  1408. //---------------------------------------------------------------------------
  1409. void __fastcall TTerminalItem::OperationProgress(
  1410. TFileOperationProgressType & ProgressData)
  1411. {
  1412. if (FPause && !IsCancelled())
  1413. {
  1414. DebugAssert(FItem != NULL);
  1415. TQueueItem::TStatus PrevStatus = FItem->GetStatus();
  1416. DebugAssert(PrevStatus == TQueueItem::qsProcessing);
  1417. // must be set before TFileOperationProgressType::Suspend(), because
  1418. // it invokes this method back
  1419. FPause = false;
  1420. ProgressData.Suspend();
  1421. try
  1422. {
  1423. FItem->SetStatus(TQueueItem::qsPaused);
  1424. WaitForEvent();
  1425. }
  1426. __finally
  1427. {
  1428. FItem->SetStatus(PrevStatus);
  1429. ProgressData.Resume();
  1430. }
  1431. }
  1432. if (IsCancelled())
  1433. {
  1434. if (ProgressData.TransferringFile)
  1435. {
  1436. ProgressData.SetCancel(csCancelTransfer);
  1437. }
  1438. else
  1439. {
  1440. ProgressData.SetCancel(csCancel);
  1441. }
  1442. }
  1443. DebugAssert(FItem != NULL);
  1444. FItem->SetProgress(ProgressData);
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. bool __fastcall TTerminalItem::OverrideItemStatus(TQueueItem::TStatus & ItemStatus)
  1448. {
  1449. DebugAssert(FTerminal != NULL);
  1450. bool Result = (FTerminal->Status < ssOpened) && (ItemStatus == TQueueItem::qsProcessing);
  1451. if (Result)
  1452. {
  1453. ItemStatus = TQueueItem::qsConnecting;
  1454. }
  1455. return Result;
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. bool TTerminalItem::IsCancelled()
  1459. {
  1460. return FTerminated || FCancel;
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. // TQueueItem
  1464. //---------------------------------------------------------------------------
  1465. __fastcall TQueueItem::TQueueItem() :
  1466. FStatus(qsPending), FTerminalItem(NULL), FSection(NULL), FProgressData(NULL),
  1467. FQueue(NULL), FInfo(NULL), FCompleteEvent(INVALID_HANDLE_VALUE),
  1468. FCPSLimit(-1)
  1469. {
  1470. FSection = new TCriticalSection();
  1471. FInfo = new TInfo();
  1472. FInfo->SingleFile = false;
  1473. FInfo->Primary = true;
  1474. FInfo->GroupToken = this;
  1475. }
  1476. //---------------------------------------------------------------------------
  1477. __fastcall TQueueItem::~TQueueItem()
  1478. {
  1479. // we need to keep the total transfer size even after transfer completes
  1480. delete FProgressData;
  1481. Complete();
  1482. delete FSection;
  1483. delete FInfo;
  1484. }
  1485. //---------------------------------------------------------------------------
  1486. bool __fastcall TQueueItem::Complete()
  1487. {
  1488. TGuard Guard(FSection);
  1489. if (FCompleteEvent != INVALID_HANDLE_VALUE)
  1490. {
  1491. SetEvent(FCompleteEvent);
  1492. FCompleteEvent = INVALID_HANDLE_VALUE;
  1493. }
  1494. return FInfo->Primary;
  1495. }
  1496. //---------------------------------------------------------------------------
  1497. bool __fastcall TQueueItem::IsUserActionStatus(TStatus Status)
  1498. {
  1499. return (Status == qsQuery) || (Status == qsError) || (Status == qsPrompt);
  1500. }
  1501. //---------------------------------------------------------------------------
  1502. TQueueItem::TStatus __fastcall TQueueItem::GetStatus()
  1503. {
  1504. TGuard Guard(FSection);
  1505. return FStatus;
  1506. }
  1507. //---------------------------------------------------------------------------
  1508. void __fastcall TQueueItem::SetStatus(TStatus Status)
  1509. {
  1510. {
  1511. TGuard Guard(FSection);
  1512. FStatus = Status;
  1513. if (FStatus == qsDone)
  1514. {
  1515. FDoneAt = Now();
  1516. }
  1517. }
  1518. DebugAssert((FQueue != NULL) || (Status == qsPending));
  1519. if (FQueue != NULL)
  1520. {
  1521. FQueue->DoQueueItemUpdate(this);
  1522. }
  1523. }
  1524. //---------------------------------------------------------------------------
  1525. void __fastcall TQueueItem::ProgressUpdated()
  1526. {
  1527. // noop
  1528. }
  1529. //---------------------------------------------------------------------------
  1530. void __fastcall TQueueItem::SetProgress(
  1531. TFileOperationProgressType & ProgressData)
  1532. {
  1533. {
  1534. TGuard Guard(FSection);
  1535. // do not lose CPS limit override on "calculate size" operation,
  1536. // wait until the real transfer operation starts
  1537. if ((FCPSLimit >= 0) && ProgressData.IsTransfer())
  1538. {
  1539. ProgressData.SetCPSLimit(static_cast<unsigned long>(FCPSLimit));
  1540. FCPSLimit = -1;
  1541. }
  1542. DebugAssert(FProgressData != NULL);
  1543. FProgressData->Assign(ProgressData);
  1544. FProgressData->Reset();
  1545. }
  1546. ProgressUpdated();
  1547. FQueue->DoQueueItemUpdate(this);
  1548. }
  1549. //---------------------------------------------------------------------------
  1550. void __fastcall TQueueItem::GetData(TQueueItemProxy * Proxy)
  1551. {
  1552. TGuard Guard(FSection);
  1553. DebugAssert(Proxy->FProgressData != NULL);
  1554. if (FProgressData != NULL)
  1555. {
  1556. Proxy->FProgressData->Assign(*FProgressData);
  1557. }
  1558. else
  1559. {
  1560. Proxy->FProgressData->Clear();
  1561. }
  1562. *Proxy->FInfo = *FInfo;
  1563. Proxy->FStatus = FStatus;
  1564. if (FTerminalItem != NULL)
  1565. {
  1566. FTerminalItem->OverrideItemStatus(Proxy->FStatus);
  1567. }
  1568. }
  1569. //---------------------------------------------------------------------------
  1570. bool __fastcall TQueueItem::UpdateFileList(TQueueFileList *)
  1571. {
  1572. // noop - implemented in TTransferQueueItem
  1573. return false;
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. bool TQueueItem::IsExecutionCancelled()
  1577. {
  1578. return DebugAlwaysTrue(FTerminalItem != NULL) ? FTerminalItem->IsCancelled() : true;
  1579. }
  1580. //---------------------------------------------------------------------------
  1581. void __fastcall TQueueItem::Execute()
  1582. {
  1583. {
  1584. DebugAssert(FProgressData == NULL);
  1585. TGuard Guard(FSection);
  1586. FProgressData = new TFileOperationProgressType();
  1587. }
  1588. DoExecute(FTerminalItem->FTerminal);
  1589. }
  1590. //---------------------------------------------------------------------------
  1591. void __fastcall TQueueItem::SetCPSLimit(unsigned long CPSLimit)
  1592. {
  1593. FCPSLimit = static_cast<long>(CPSLimit);
  1594. }
  1595. //---------------------------------------------------------------------------
  1596. unsigned long __fastcall TQueueItem::DefaultCPSLimit()
  1597. {
  1598. return 0;
  1599. }
  1600. //---------------------------------------------------------------------------
  1601. unsigned long __fastcall TQueueItem::GetCPSLimit()
  1602. {
  1603. unsigned long Result;
  1604. if (FCPSLimit >= 0)
  1605. {
  1606. Result = FCPSLimit;
  1607. }
  1608. else if (FProgressData != NULL)
  1609. {
  1610. Result = FProgressData->CPSLimit;
  1611. }
  1612. else
  1613. {
  1614. Result = DefaultCPSLimit();
  1615. }
  1616. return Result;
  1617. }
  1618. //---------------------------------------------------------------------------
  1619. TQueueItem * __fastcall TQueueItem::CreateParallelOperation()
  1620. {
  1621. return NULL;
  1622. }
  1623. //---------------------------------------------------------------------------
  1624. UnicodeString __fastcall TQueueItem::StartupDirectory() const
  1625. {
  1626. return EmptyStr;
  1627. }
  1628. //---------------------------------------------------------------------------
  1629. // TQueueItemProxy
  1630. //---------------------------------------------------------------------------
  1631. __fastcall TQueueItemProxy::TQueueItemProxy(TTerminalQueue * Queue,
  1632. TQueueItem * QueueItem) :
  1633. FQueue(Queue), FQueueItem(QueueItem), FProgressData(NULL),
  1634. FQueueStatus(NULL), FInfo(NULL),
  1635. FProcessingUserAction(false), FUserData(NULL)
  1636. {
  1637. FProgressData = new TFileOperationProgressType();
  1638. FInfo = new TQueueItem::TInfo();
  1639. Update();
  1640. }
  1641. //---------------------------------------------------------------------------
  1642. __fastcall TQueueItemProxy::~TQueueItemProxy()
  1643. {
  1644. delete FProgressData;
  1645. delete FInfo;
  1646. }
  1647. //---------------------------------------------------------------------------
  1648. TFileOperationProgressType * __fastcall TQueueItemProxy::GetProgressData()
  1649. {
  1650. return (FProgressData->Operation == foNone) ? NULL : FProgressData;
  1651. }
  1652. //---------------------------------------------------------------------------
  1653. __int64 __fastcall TQueueItemProxy::GetTotalTransferred()
  1654. {
  1655. // want to show total transferred also for "completed" items,
  1656. // for which GetProgressData() is NULL
  1657. return
  1658. (FProgressData->Operation == Info->Operation) || (Status == TQueueItem::qsDone) ?
  1659. FProgressData->TotalTransferred : -1;
  1660. }
  1661. //---------------------------------------------------------------------------
  1662. bool __fastcall TQueueItemProxy::Update()
  1663. {
  1664. DebugAssert(FQueueItem != NULL);
  1665. TQueueItem::TStatus PrevStatus = Status;
  1666. bool Result = FQueue->ItemGetData(FQueueItem, this, NULL);
  1667. if ((FQueueStatus != NULL) && (PrevStatus != Status))
  1668. {
  1669. FQueueStatus->ResetStats();
  1670. }
  1671. return Result;
  1672. }
  1673. //---------------------------------------------------------------------------
  1674. bool __fastcall TQueueItemProxy::UpdateFileList(TQueueFileList * FileList)
  1675. {
  1676. return FQueue->ItemGetData(FQueueItem, NULL, FileList);
  1677. }
  1678. //---------------------------------------------------------------------------
  1679. bool __fastcall TQueueItemProxy::ExecuteNow()
  1680. {
  1681. return FQueue->ItemExecuteNow(FQueueItem);
  1682. }
  1683. //---------------------------------------------------------------------------
  1684. bool __fastcall TQueueItemProxy::Move(bool Sooner)
  1685. {
  1686. bool Result = false;
  1687. int I = Index;
  1688. if (Sooner)
  1689. {
  1690. if (I > 0)
  1691. {
  1692. Result = Move(FQueueStatus->Items[I - 1]);
  1693. }
  1694. }
  1695. else
  1696. {
  1697. if (I < FQueueStatus->Count - 1)
  1698. {
  1699. Result = FQueueStatus->Items[I + 1]->Move(this);
  1700. }
  1701. }
  1702. return Result;
  1703. }
  1704. //---------------------------------------------------------------------------
  1705. bool __fastcall TQueueItemProxy::Move(TQueueItemProxy * BeforeItem)
  1706. {
  1707. return FQueue->ItemMove(FQueueItem, BeforeItem->FQueueItem);
  1708. }
  1709. //---------------------------------------------------------------------------
  1710. bool __fastcall TQueueItemProxy::Delete()
  1711. {
  1712. return FQueue->ItemDelete(FQueueItem);
  1713. }
  1714. //---------------------------------------------------------------------------
  1715. bool __fastcall TQueueItemProxy::Pause()
  1716. {
  1717. return FQueue->ItemPause(FQueueItem, true);
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. bool __fastcall TQueueItemProxy::Resume()
  1721. {
  1722. return FQueue->ItemPause(FQueueItem, false);
  1723. }
  1724. //---------------------------------------------------------------------------
  1725. bool __fastcall TQueueItemProxy::ProcessUserAction()
  1726. {
  1727. DebugAssert(FQueueItem != NULL);
  1728. bool Result;
  1729. FProcessingUserAction = true;
  1730. try
  1731. {
  1732. Result = FQueue->ItemProcessUserAction(FQueueItem, NULL);
  1733. }
  1734. __finally
  1735. {
  1736. FProcessingUserAction = false;
  1737. }
  1738. return Result;
  1739. }
  1740. //---------------------------------------------------------------------------
  1741. bool __fastcall TQueueItemProxy::GetCPSLimit(unsigned long & CPSLimit)
  1742. {
  1743. return FQueue->ItemGetCPSLimit(FQueueItem, CPSLimit);
  1744. }
  1745. //---------------------------------------------------------------------------
  1746. bool __fastcall TQueueItemProxy::SetCPSLimit(unsigned long CPSLimit)
  1747. {
  1748. return FQueue->ItemSetCPSLimit(FQueueItem, CPSLimit);
  1749. }
  1750. //---------------------------------------------------------------------------
  1751. int __fastcall TQueueItemProxy::GetIndex()
  1752. {
  1753. DebugAssert(FQueueStatus != NULL);
  1754. int Index = FQueueStatus->FList->IndexOf(this);
  1755. DebugAssert(Index >= 0);
  1756. return Index;
  1757. }
  1758. //---------------------------------------------------------------------------
  1759. // TTerminalQueueStatus
  1760. //---------------------------------------------------------------------------
  1761. __fastcall TTerminalQueueStatus::TTerminalQueueStatus() :
  1762. FList(NULL)
  1763. {
  1764. FList = new TList();
  1765. ResetStats();
  1766. }
  1767. //---------------------------------------------------------------------------
  1768. __fastcall TTerminalQueueStatus::~TTerminalQueueStatus()
  1769. {
  1770. for (int Index = 0; Index < FList->Count; Index++)
  1771. {
  1772. delete GetItem(Index);
  1773. }
  1774. delete FList;
  1775. FList = NULL;
  1776. }
  1777. //---------------------------------------------------------------------------
  1778. void __fastcall TTerminalQueueStatus::ResetStats()
  1779. {
  1780. FActiveCount = -1;
  1781. FActivePrimaryCount = -1;
  1782. FActiveAndPendingPrimaryCount = -1;
  1783. }
  1784. //---------------------------------------------------------------------------
  1785. void __fastcall TTerminalQueueStatus::SetDoneCount(int Value)
  1786. {
  1787. FDoneCount = Value;
  1788. ResetStats();
  1789. }
  1790. //---------------------------------------------------------------------------
  1791. void __fastcall TTerminalQueueStatus::NeedStats()
  1792. {
  1793. if (FActiveCount < 0)
  1794. {
  1795. FActiveCount = 0;
  1796. FActivePrimaryCount = 0;
  1797. FActiveAndPendingPrimaryCount = 0;
  1798. for (int Index = DoneCount; Index < Count; Index++)
  1799. {
  1800. bool Primary = GetItem(Index)->Info->Primary;
  1801. if (GetItem(Index)->Status != TQueueItem::qsPending)
  1802. {
  1803. FActiveCount++;
  1804. if (Primary)
  1805. {
  1806. FActivePrimaryCount++;
  1807. }
  1808. }
  1809. if (Primary)
  1810. {
  1811. FActiveAndPendingPrimaryCount++;
  1812. }
  1813. }
  1814. }
  1815. }
  1816. //---------------------------------------------------------------------------
  1817. int __fastcall TTerminalQueueStatus::GetActiveCount()
  1818. {
  1819. NeedStats();
  1820. return FActiveCount;
  1821. }
  1822. //---------------------------------------------------------------------------
  1823. int __fastcall TTerminalQueueStatus::GetDoneAndActiveCount()
  1824. {
  1825. return DoneCount + ActiveCount;
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. int __fastcall TTerminalQueueStatus::GetActivePrimaryCount()
  1829. {
  1830. NeedStats();
  1831. return FActivePrimaryCount;
  1832. }
  1833. //---------------------------------------------------------------------------
  1834. bool __fastcall TTerminalQueueStatus::IsOnlyOneActiveAndNoPending()
  1835. {
  1836. return (ActivePrimaryCount == 1) && (ActiveAndPendingPrimaryCount == 1);
  1837. }
  1838. //---------------------------------------------------------------------------
  1839. int __fastcall TTerminalQueueStatus::GetActiveAndPendingPrimaryCount()
  1840. {
  1841. NeedStats();
  1842. return FActiveAndPendingPrimaryCount;
  1843. }
  1844. //---------------------------------------------------------------------------
  1845. void __fastcall TTerminalQueueStatus::Add(TQueueItemProxy * ItemProxy)
  1846. {
  1847. ItemProxy->FQueueStatus = this;
  1848. int Index = FList->Count;
  1849. if (!ItemProxy->Info->Primary)
  1850. {
  1851. for (int I = 0; I < FList->Count; I++)
  1852. {
  1853. if (Items[I]->Info->GroupToken == ItemProxy->Info->GroupToken)
  1854. {
  1855. Index = I + 1;
  1856. }
  1857. }
  1858. DebugAssert(Index >= 0);
  1859. }
  1860. FList->Insert(Index, ItemProxy);
  1861. ResetStats();
  1862. }
  1863. //---------------------------------------------------------------------------
  1864. void __fastcall TTerminalQueueStatus::Delete(TQueueItemProxy * ItemProxy)
  1865. {
  1866. FList->Extract(ItemProxy);
  1867. ItemProxy->FQueueStatus = NULL;
  1868. ResetStats();
  1869. }
  1870. //---------------------------------------------------------------------------
  1871. int __fastcall TTerminalQueueStatus::GetCount()
  1872. {
  1873. return FList->Count;
  1874. }
  1875. //---------------------------------------------------------------------------
  1876. TQueueItemProxy * __fastcall TTerminalQueueStatus::GetItem(int Index)
  1877. {
  1878. return reinterpret_cast<TQueueItemProxy *>(FList->Items[Index]);
  1879. }
  1880. //---------------------------------------------------------------------------
  1881. TQueueItemProxy * __fastcall TTerminalQueueStatus::FindByQueueItem(
  1882. TQueueItem * QueueItem)
  1883. {
  1884. TQueueItemProxy * Item;
  1885. for (int Index = 0; Index < FList->Count; Index++)
  1886. {
  1887. Item = GetItem(Index);
  1888. if (Item->FQueueItem == QueueItem)
  1889. {
  1890. return Item;
  1891. }
  1892. }
  1893. return NULL;
  1894. }
  1895. //---------------------------------------------------------------------------
  1896. bool __fastcall TTerminalQueueStatus::UpdateFileList(TQueueItemProxy * ItemProxy, TQueueFileList * FileList)
  1897. {
  1898. bool Result;
  1899. if (ItemProxy != NULL)
  1900. {
  1901. Result = ItemProxy->UpdateFileList(FileList);
  1902. }
  1903. else
  1904. {
  1905. Result = (FileList->GetCount() > 0);
  1906. if (Result)
  1907. {
  1908. FileList->Clear();
  1909. }
  1910. }
  1911. return Result;
  1912. }
  1913. //---------------------------------------------------------------------------
  1914. // TBootstrapQueueItem
  1915. //---------------------------------------------------------------------------
  1916. __fastcall TBootstrapQueueItem::TBootstrapQueueItem()
  1917. {
  1918. FInfo->SingleFile = true;
  1919. }
  1920. //---------------------------------------------------------------------------
  1921. void __fastcall TBootstrapQueueItem::DoExecute(TTerminal * DebugUsedArg(Terminal))
  1922. {
  1923. // noop
  1924. }
  1925. //---------------------------------------------------------------------------
  1926. bool __fastcall TBootstrapQueueItem::Complete()
  1927. {
  1928. TQueueItem::Complete();
  1929. // To hide the item, even if "keep done items" is on
  1930. return false;
  1931. }
  1932. //---------------------------------------------------------------------------
  1933. // TLocatedQueueItem
  1934. //---------------------------------------------------------------------------
  1935. __fastcall TLocatedQueueItem::TLocatedQueueItem(TTerminal * Terminal) :
  1936. TQueueItem()
  1937. {
  1938. DebugAssert(Terminal != NULL);
  1939. FCurrentDir = Terminal->CurrentDirectory;
  1940. }
  1941. //---------------------------------------------------------------------------
  1942. __fastcall TLocatedQueueItem::TLocatedQueueItem(const TLocatedQueueItem & Source) :
  1943. TQueueItem()
  1944. {
  1945. FCurrentDir = Source.FCurrentDir;
  1946. }
  1947. //---------------------------------------------------------------------------
  1948. UnicodeString __fastcall TLocatedQueueItem::StartupDirectory() const
  1949. {
  1950. return FCurrentDir;
  1951. }
  1952. //---------------------------------------------------------------------------
  1953. void __fastcall TLocatedQueueItem::DoExecute(TTerminal * Terminal)
  1954. {
  1955. DebugAssert(Terminal != NULL);
  1956. Terminal->CurrentDirectory = FCurrentDir;
  1957. }
  1958. //---------------------------------------------------------------------------
  1959. // TTransferQueueItem
  1960. //---------------------------------------------------------------------------
  1961. __fastcall TTransferQueueItem::TTransferQueueItem(TTerminal * Terminal,
  1962. TStrings * FilesToCopy, const UnicodeString & TargetDir,
  1963. const TCopyParamType * CopyParam, int Params, TOperationSide Side,
  1964. bool SingleFile, bool Parallel) :
  1965. TLocatedQueueItem(Terminal), FFilesToCopy(NULL), FCopyParam(NULL)
  1966. {
  1967. FInfo->Operation = (Params & cpDelete ? foMove : foCopy);
  1968. FInfo->Side = Side;
  1969. FInfo->SingleFile = SingleFile;
  1970. if (FilesToCopy != NULL)
  1971. {
  1972. FFilesToCopy = new TStringList();
  1973. for (int Index = 0; Index < FilesToCopy->Count; Index++)
  1974. {
  1975. UnicodeString FileName = FilesToCopy->Strings[Index];
  1976. TRemoteFile * File = dynamic_cast<TRemoteFile *>(FilesToCopy->Objects[Index]);
  1977. FFilesToCopy->AddObject(FileName, ((File == NULL) || (Side == osLocal)) ? NULL : File->Duplicate());
  1978. }
  1979. }
  1980. FTargetDir = TargetDir;
  1981. DebugAssert(CopyParam != NULL);
  1982. FCopyParam = new TCopyParamType(*CopyParam);
  1983. FParams = Params;
  1984. FParallel = Parallel;
  1985. FLastParallelOperationAdded = GetTickCount();
  1986. }
  1987. //---------------------------------------------------------------------------
  1988. __fastcall TTransferQueueItem::~TTransferQueueItem()
  1989. {
  1990. if (FFilesToCopy != NULL)
  1991. {
  1992. for (int Index = 0; Index < FFilesToCopy->Count; Index++)
  1993. {
  1994. delete FFilesToCopy->Objects[Index];
  1995. }
  1996. delete FFilesToCopy;
  1997. }
  1998. delete FCopyParam;
  1999. }
  2000. //---------------------------------------------------------------------------
  2001. unsigned long __fastcall TTransferQueueItem::DefaultCPSLimit()
  2002. {
  2003. return FCopyParam->CPSLimit;
  2004. }
  2005. //---------------------------------------------------------------------------
  2006. void __fastcall TTransferQueueItem::DoExecute(TTerminal * Terminal)
  2007. {
  2008. TLocatedQueueItem::DoExecute(Terminal);
  2009. DebugAssert(Terminal != NULL);
  2010. FParallelOperation.reset(new TParallelOperation(FInfo->Side));
  2011. try
  2012. {
  2013. DoTransferExecute(Terminal, FParallelOperation.get());
  2014. }
  2015. __finally
  2016. {
  2017. FParallelOperation->WaitFor();
  2018. }
  2019. }
  2020. //---------------------------------------------------------------------------
  2021. void __fastcall TTransferQueueItem::ProgressUpdated()
  2022. {
  2023. TLocatedQueueItem::ProgressUpdated();
  2024. if (FParallel)
  2025. {
  2026. bool Add = false;
  2027. bool Force = false;
  2028. DWORD LastParallelOperationAddedPrev = 0;
  2029. {
  2030. TGuard Guard(FSection);
  2031. DebugAssert(FParallelOperation.get() != NULL);
  2032. // Won't be initialized, if the operation is not eligible for parallel transfers (like cpDelete).
  2033. // We can probably move the check outside of the guard.
  2034. if (FParallelOperation->IsInitialized())
  2035. {
  2036. DebugAssert(FProgressData->IsTransfer());
  2037. if (FProgressData->Operation == foCopy)
  2038. {
  2039. Add = FParallelOperation->ShouldAddClient();
  2040. if (Add)
  2041. {
  2042. DWORD Now = GetTickCount();
  2043. Force =
  2044. (Now - FLastParallelOperationAdded >= 5*1000) &&
  2045. (TimeToSeconds(FProgressData->TotalTimeLeft()) >= FQueue->ParallelDurationThreshold);
  2046. LastParallelOperationAddedPrev = FLastParallelOperationAdded;
  2047. // update now already to prevent race condition, but we will have to rollback it back,
  2048. // if we actually do not add the parallel operation
  2049. FLastParallelOperationAdded = Now;
  2050. }
  2051. }
  2052. }
  2053. }
  2054. if (Add)
  2055. {
  2056. if (!FQueue->TryAddParallelOperation(this, Force))
  2057. {
  2058. TGuard Guard(FSection);
  2059. FLastParallelOperationAdded = LastParallelOperationAddedPrev;
  2060. }
  2061. }
  2062. }
  2063. }
  2064. //---------------------------------------------------------------------------
  2065. TQueueItem * __fastcall TTransferQueueItem::CreateParallelOperation()
  2066. {
  2067. DebugAssert(FParallelOperation.get() != NULL);
  2068. FParallelOperation->AddClient();
  2069. DebugAssert(!FInfo->SingleFile || FParallelOperation->IsParallelFileTransfer);
  2070. FInfo->SingleFile = false;
  2071. return new TParallelTransferQueueItem(this, FParallelOperation.get());
  2072. }
  2073. //---------------------------------------------------------------------------
  2074. bool __fastcall TTransferQueueItem::UpdateFileList(TQueueFileList * FileList)
  2075. {
  2076. TGuard Guard(FSection);
  2077. bool Result;
  2078. if ((FParallelOperation.get() != NULL) && FParallelOperation->IsInitialized())
  2079. {
  2080. Result = FParallelOperation->UpdateFileList(FileList);
  2081. }
  2082. else
  2083. {
  2084. Result = false;
  2085. }
  2086. return Result;
  2087. }
  2088. //---------------------------------------------------------------------------
  2089. // TUploadQueueItem
  2090. //---------------------------------------------------------------------------
  2091. static void ExtractLocalSourcePath(TStrings * Files, UnicodeString & Path)
  2092. {
  2093. ExtractCommonPath(Files, Path);
  2094. // this way the trailing backslash is preserved for root directories like D:\\
  2095. Path = ExtractFileDir(IncludeTrailingBackslash(Path));
  2096. }
  2097. //---------------------------------------------------------------------------
  2098. static bool IsSingleFileUpload(TStrings * FilesToCopy)
  2099. {
  2100. return
  2101. (FilesToCopy->Count == 1) &&
  2102. FileExists(ApiPath(FilesToCopy->Strings[0]));
  2103. }
  2104. //---------------------------------------------------------------------------
  2105. __fastcall TUploadQueueItem::TUploadQueueItem(
  2106. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  2107. const TCopyParamType * CopyParam, int Params, bool Parallel) :
  2108. TTransferQueueItem(
  2109. Terminal, FilesToCopy, TargetDir, CopyParam, Params, osLocal, IsSingleFileUpload(FilesToCopy), Parallel)
  2110. {
  2111. if (FilesToCopy->Count > 1)
  2112. {
  2113. if (FLAGSET(Params, cpTemporary))
  2114. {
  2115. FInfo->Source = L"";
  2116. FInfo->ModifiedLocal = L"";
  2117. }
  2118. else
  2119. {
  2120. ExtractLocalSourcePath(FilesToCopy, FInfo->Source);
  2121. FInfo->ModifiedLocal = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2122. IncludeTrailingBackslash(FInfo->Source);
  2123. }
  2124. }
  2125. else
  2126. {
  2127. if (FLAGSET(Params, cpTemporary))
  2128. {
  2129. FInfo->Source = ExtractFileName(FilesToCopy->Strings[0]);
  2130. FInfo->ModifiedLocal = L"";
  2131. }
  2132. else
  2133. {
  2134. DebugAssert(FilesToCopy->Count > 0);
  2135. FInfo->Source = FilesToCopy->Strings[0];
  2136. FInfo->ModifiedLocal = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2137. IncludeTrailingBackslash(ExtractFilePath(FInfo->Source));
  2138. }
  2139. }
  2140. FInfo->Destination =
  2141. UnixIncludeTrailingBackslash(TargetDir) + CopyParam->FileMask;
  2142. FInfo->ModifiedRemote = UnixIncludeTrailingBackslash(TargetDir);
  2143. }
  2144. //---------------------------------------------------------------------------
  2145. void __fastcall TUploadQueueItem::DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  2146. {
  2147. Terminal->CopyToRemote(FFilesToCopy, FTargetDir, FCopyParam, FParams, ParallelOperation);
  2148. }
  2149. //---------------------------------------------------------------------------
  2150. // TParallelTransferQueueItem
  2151. //---------------------------------------------------------------------------
  2152. __fastcall TParallelTransferQueueItem::TParallelTransferQueueItem(
  2153. const TLocatedQueueItem * ParentItem, TParallelOperation * ParallelOperation) :
  2154. TLocatedQueueItem(*ParentItem),
  2155. FParallelOperation(ParallelOperation)
  2156. {
  2157. // deliberately not copying the ModifiedLocal and ModifiedRemote, not to trigger panel refresh, when sub-item completes
  2158. FInfo->Operation = ParentItem->FInfo->Operation;
  2159. FInfo->Side = ParentItem->FInfo->Side;
  2160. FInfo->Source = ParentItem->FInfo->Source;
  2161. FInfo->Destination = ParentItem->FInfo->Destination;
  2162. FInfo->SingleFile = DebugAlwaysFalse(ParentItem->FInfo->SingleFile);
  2163. FInfo->Primary = false;
  2164. FInfo->GroupToken = ParentItem->FInfo->GroupToken;
  2165. }
  2166. //---------------------------------------------------------------------------
  2167. void __fastcall TParallelTransferQueueItem::DoExecute(TTerminal * Terminal)
  2168. {
  2169. TLocatedQueueItem::DoExecute(Terminal);
  2170. Terminal->LogParallelTransfer(FParallelOperation);
  2171. TFileOperationProgressType OperationProgress(Terminal->OnProgress, Terminal->OnFinished, FParallelOperation->MainOperationProgress);
  2172. TFileOperation Operation = (FLAGSET(FParallelOperation->Params, cpDelete) ? foMove : foCopy);
  2173. bool Temp = FLAGSET(FParallelOperation->Params, cpTemporary);
  2174. OperationProgress.Start(
  2175. // CPS limit inherited from parent OperationProgress.
  2176. // Count not known and won't be needed as we will always have TotalSize as we always transfer a single file at a time.
  2177. Operation, FParallelOperation->Side, -1, Temp, FParallelOperation->TargetDir, 0, odoIdle);
  2178. try
  2179. {
  2180. bool Continue = true;
  2181. do
  2182. {
  2183. int GotNext = Terminal->CopyToParallel(FParallelOperation, &OperationProgress);
  2184. if (GotNext < 0)
  2185. {
  2186. Continue = false;
  2187. }
  2188. else if (!FQueue->ContinueParallelOperation())
  2189. {
  2190. Continue = false;
  2191. }
  2192. }
  2193. while (Continue);
  2194. }
  2195. __finally
  2196. {
  2197. OperationProgress.Stop();
  2198. FParallelOperation->RemoveClient();
  2199. }
  2200. }
  2201. //---------------------------------------------------------------------------
  2202. // TDownloadQueueItem
  2203. //---------------------------------------------------------------------------
  2204. static void ExtractRemoteSourcePath(TTerminal * Terminal, TStrings * Files, UnicodeString & Path)
  2205. {
  2206. if (!UnixExtractCommonPath(Files, Path))
  2207. {
  2208. Path = Terminal->CurrentDirectory;
  2209. }
  2210. Path = UnixExcludeTrailingBackslash(Path);
  2211. }
  2212. //---------------------------------------------------------------------------
  2213. static bool IsSingleFileDownload(TStrings * FilesToCopy)
  2214. {
  2215. return
  2216. (FilesToCopy->Count == 1) &&
  2217. !static_cast<TRemoteFile *>(FilesToCopy->Objects[0])->IsDirectory;
  2218. }
  2219. //---------------------------------------------------------------------------
  2220. __fastcall TDownloadQueueItem::TDownloadQueueItem(TTerminal * Terminal,
  2221. TStrings * FilesToCopy, const UnicodeString & TargetDir,
  2222. const TCopyParamType * CopyParam, int Params, bool Parallel) :
  2223. TTransferQueueItem(
  2224. Terminal, FilesToCopy, TargetDir, CopyParam, Params, osRemote, IsSingleFileDownload(FilesToCopy), Parallel)
  2225. {
  2226. if (FilesToCopy->Count > 1)
  2227. {
  2228. ExtractRemoteSourcePath(Terminal, FilesToCopy, FInfo->Source);
  2229. FInfo->ModifiedRemote = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2230. UnixIncludeTrailingBackslash(FInfo->Source);
  2231. }
  2232. else
  2233. {
  2234. DebugAssert(FilesToCopy->Count > 0);
  2235. FInfo->Source = FilesToCopy->Strings[0];
  2236. if (UnixExtractFilePath(FInfo->Source).IsEmpty())
  2237. {
  2238. FInfo->Source = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2239. FInfo->Source;
  2240. FInfo->ModifiedRemote = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2241. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);
  2242. }
  2243. else
  2244. {
  2245. FInfo->ModifiedRemote = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2246. UnixExtractFilePath(FInfo->Source);
  2247. }
  2248. }
  2249. if (FLAGSET(Params, cpTemporary))
  2250. {
  2251. FInfo->Destination = L"";
  2252. }
  2253. else
  2254. {
  2255. FInfo->Destination =
  2256. IncludeTrailingBackslash(TargetDir) + CopyParam->FileMask;
  2257. }
  2258. FInfo->ModifiedLocal = IncludeTrailingBackslash(TargetDir);
  2259. }
  2260. //---------------------------------------------------------------------------
  2261. void __fastcall TDownloadQueueItem::DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  2262. {
  2263. Terminal->CopyToLocal(FFilesToCopy, FTargetDir, FCopyParam, FParams, ParallelOperation);
  2264. }
  2265. //---------------------------------------------------------------------------
  2266. //---------------------------------------------------------------------------
  2267. TRemoteDeleteQueueItem::TRemoteDeleteQueueItem(TTerminal * Terminal, TStrings * FilesToDelete, int Params) :
  2268. TLocatedQueueItem(Terminal)
  2269. {
  2270. FInfo->Operation = foDelete;
  2271. FInfo->Side = osRemote;
  2272. DebugAssert(FilesToDelete != NULL);
  2273. FFilesToDelete.reset(TRemoteFileList::CloneStrings(FilesToDelete));
  2274. ExtractRemoteSourcePath(Terminal, FilesToDelete, FInfo->Source);
  2275. FInfo->ModifiedRemote = FInfo->Source;
  2276. FParams = Params;
  2277. }
  2278. //---------------------------------------------------------------------------
  2279. void __fastcall TRemoteDeleteQueueItem::DoExecute(TTerminal * Terminal)
  2280. {
  2281. TLocatedQueueItem::DoExecute(Terminal);
  2282. DebugAssert(Terminal != NULL);
  2283. Terminal->DeleteFiles(FFilesToDelete.get(), FParams);
  2284. }
  2285. //---------------------------------------------------------------------------
  2286. //---------------------------------------------------------------------------
  2287. TLocalDeleteQueueItem::TLocalDeleteQueueItem(TStrings * FilesToDelete, int Params) :
  2288. TQueueItem()
  2289. {
  2290. FInfo->Operation = foDelete;
  2291. FInfo->Side = osLocal;
  2292. DebugAssert(FilesToDelete != NULL);
  2293. FFilesToDelete.reset(CloneStrings(FilesToDelete));
  2294. ExtractLocalSourcePath(FilesToDelete, FInfo->Source);
  2295. FInfo->ModifiedLocal = FInfo->Source;
  2296. FParams = Params;
  2297. }
  2298. //---------------------------------------------------------------------------
  2299. void __fastcall TLocalDeleteQueueItem::DoExecute(TTerminal * Terminal)
  2300. {
  2301. DebugAssert(Terminal != NULL);
  2302. Terminal->DeleteLocalFiles(FFilesToDelete.get(), FParams);
  2303. }
  2304. //---------------------------------------------------------------------------
  2305. // TTerminalThread
  2306. //---------------------------------------------------------------------------
  2307. __fastcall TTerminalThread::TTerminalThread(TTerminal * Terminal) :
  2308. TSignalThread(false), FTerminal(Terminal)
  2309. {
  2310. FAction = NULL;
  2311. FActionEvent = CreateEvent(NULL, false, false, NULL);
  2312. FException = NULL;
  2313. FIdleException = NULL;
  2314. FOnIdle = NULL;
  2315. FUserAction = NULL;
  2316. FCancel = false;
  2317. FAbandoned = false;
  2318. FAllowAbandon = false;
  2319. FMainThread = GetCurrentThreadId();
  2320. FSection = new TCriticalSection();
  2321. FOnInformation = FTerminal->OnInformation;
  2322. FOnQueryUser = FTerminal->OnQueryUser;
  2323. FOnPromptUser = FTerminal->OnPromptUser;
  2324. FOnShowExtendedException = FTerminal->OnShowExtendedException;
  2325. FOnDisplayBanner = FTerminal->OnDisplayBanner;
  2326. FOnChangeDirectory = FTerminal->OnChangeDirectory;
  2327. FOnReadDirectory = FTerminal->OnReadDirectory;
  2328. FOnStartReadDirectory = FTerminal->OnStartReadDirectory;
  2329. FOnReadDirectoryProgress = FTerminal->OnReadDirectoryProgress;
  2330. FOnInitializeLog = FTerminal->OnInitializeLog;
  2331. FTerminal->OnInformation = TerminalInformation;
  2332. FTerminal->OnQueryUser = TerminalQueryUser;
  2333. FTerminal->OnPromptUser = TerminalPromptUser;
  2334. FTerminal->OnShowExtendedException = TerminalShowExtendedException;
  2335. FTerminal->OnDisplayBanner = TerminalDisplayBanner;
  2336. FTerminal->OnChangeDirectory = TerminalChangeDirectory;
  2337. FTerminal->OnReadDirectory = TerminalReadDirectory;
  2338. FTerminal->OnStartReadDirectory = TerminalStartReadDirectory;
  2339. FTerminal->OnReadDirectoryProgress = TerminalReadDirectoryProgress;
  2340. FTerminal->OnInitializeLog = TerminalInitializeLog;
  2341. Start();
  2342. }
  2343. //---------------------------------------------------------------------------
  2344. __fastcall TTerminalThread::~TTerminalThread()
  2345. {
  2346. Close();
  2347. CloseHandle(FActionEvent);
  2348. DebugAssert(FTerminal->OnInformation == TerminalInformation);
  2349. DebugAssert(FTerminal->OnQueryUser == TerminalQueryUser);
  2350. DebugAssert(FTerminal->OnPromptUser == TerminalPromptUser);
  2351. DebugAssert(FTerminal->OnShowExtendedException == TerminalShowExtendedException);
  2352. DebugAssert(FTerminal->OnDisplayBanner == TerminalDisplayBanner);
  2353. DebugAssert(FTerminal->OnChangeDirectory == TerminalChangeDirectory);
  2354. DebugAssert(FTerminal->OnReadDirectory == TerminalReadDirectory);
  2355. DebugAssert(FTerminal->OnStartReadDirectory == TerminalStartReadDirectory);
  2356. DebugAssert(FTerminal->OnReadDirectoryProgress == TerminalReadDirectoryProgress);
  2357. DebugAssert(FTerminal->OnInitializeLog == TerminalInitializeLog);
  2358. FTerminal->OnInformation = FOnInformation;
  2359. FTerminal->OnQueryUser = FOnQueryUser;
  2360. FTerminal->OnPromptUser = FOnPromptUser;
  2361. FTerminal->OnShowExtendedException = FOnShowExtendedException;
  2362. FTerminal->OnDisplayBanner = FOnDisplayBanner;
  2363. FTerminal->OnChangeDirectory = FOnChangeDirectory;
  2364. FTerminal->OnReadDirectory = FOnReadDirectory;
  2365. FTerminal->OnStartReadDirectory = FOnStartReadDirectory;
  2366. FTerminal->OnReadDirectoryProgress = FOnReadDirectoryProgress;
  2367. FTerminal->OnInitializeLog = FOnInitializeLog;
  2368. delete FSection;
  2369. if (FAbandoned)
  2370. {
  2371. delete FTerminal;
  2372. }
  2373. }
  2374. //---------------------------------------------------------------------------
  2375. void __fastcall TTerminalThread::Cancel()
  2376. {
  2377. FCancel = true;
  2378. FCancelAfter = IncMilliSecond(Now(), 1000);
  2379. }
  2380. //---------------------------------------------------------------------------
  2381. void __fastcall TTerminalThread::Idle()
  2382. {
  2383. // If user action is needed during Idle() call from TTerminalThread::WaitForUserAction
  2384. // (e.g. when disconnect is detected and session get reconnected)
  2385. // unconditional Enter() here would deadlock.
  2386. if (FSection->TryEnter())
  2387. {
  2388. try
  2389. {
  2390. // only when running user action already,
  2391. // so that the exception is caught, saved and actually
  2392. // passed back into the terminal thread, saved again
  2393. // and passed back to us
  2394. if ((FUserAction != NULL) && (FIdleException != NULL))
  2395. {
  2396. Rethrow(FIdleException);
  2397. }
  2398. FPendingIdle = true;
  2399. }
  2400. __finally
  2401. {
  2402. FSection->Release();
  2403. }
  2404. }
  2405. }
  2406. //---------------------------------------------------------------------------
  2407. void __fastcall TTerminalThread::TerminalOpen()
  2408. {
  2409. RunAction(TerminalOpenEvent);
  2410. }
  2411. //---------------------------------------------------------------------------
  2412. void __fastcall TTerminalThread::TerminalReopen()
  2413. {
  2414. RunAction(TerminalReopenEvent);
  2415. }
  2416. //---------------------------------------------------------------------------
  2417. void __fastcall TTerminalThread::RunAction(TNotifyEvent Action)
  2418. {
  2419. DebugAssert(FAction == NULL);
  2420. DebugAssert(FException == NULL);
  2421. DebugAssert(FIdleException == NULL);
  2422. DebugAssert(FOnIdle != NULL);
  2423. FCancelled = false;
  2424. FAction = Action;
  2425. try
  2426. {
  2427. try
  2428. {
  2429. TriggerEvent();
  2430. bool Done = false;
  2431. const unsigned int MaxWait = 50;
  2432. unsigned int Wait = MaxWait;
  2433. do
  2434. {
  2435. switch (WaitForSingleObject(FActionEvent, Wait))
  2436. {
  2437. case WAIT_OBJECT_0:
  2438. Done = true;
  2439. break;
  2440. case WAIT_TIMEOUT:
  2441. if (FUserAction != NULL)
  2442. {
  2443. try
  2444. {
  2445. FUserAction->Execute(NULL);
  2446. }
  2447. catch (Exception & E)
  2448. {
  2449. SaveException(E, FException);
  2450. }
  2451. FUserAction = NULL;
  2452. TriggerEvent();
  2453. Wait = 0;
  2454. }
  2455. else
  2456. {
  2457. if (FOnIdle != NULL)
  2458. {
  2459. FOnIdle(NULL);
  2460. }
  2461. Wait = std::min(Wait + 10, MaxWait);
  2462. }
  2463. break;
  2464. default:
  2465. throw Exception(L"Error waiting for background session task to complete");
  2466. }
  2467. if (AllowAbandon && !Done && FCancel && (Now() >= FCancelAfter))
  2468. {
  2469. TGuard Guard(FSection);
  2470. if (WaitForSingleObject(FActionEvent, 0) != WAIT_OBJECT_0)
  2471. {
  2472. FAbandoned = true;
  2473. FCancelled = true;
  2474. FatalAbort();
  2475. }
  2476. }
  2477. }
  2478. while (!Done);
  2479. if (Done)
  2480. {
  2481. Rethrow(FException);
  2482. }
  2483. }
  2484. __finally
  2485. {
  2486. FAction = NULL;
  2487. SAFE_DESTROY(FException);
  2488. }
  2489. }
  2490. catch(...)
  2491. {
  2492. if (FCancelled)
  2493. {
  2494. // even if the abort thrown as result of Cancel() was wrapped into
  2495. // some higher-level exception, normalize back to message-less fatal
  2496. // exception here
  2497. FatalAbort();
  2498. }
  2499. else
  2500. {
  2501. throw;
  2502. }
  2503. }
  2504. }
  2505. //---------------------------------------------------------------------------
  2506. void __fastcall TTerminalThread::TerminalOpenEvent(TObject * /*Sender*/)
  2507. {
  2508. FTerminal->Open();
  2509. }
  2510. //---------------------------------------------------------------------------
  2511. void __fastcall TTerminalThread::TerminalReopenEvent(TObject * /*Sender*/)
  2512. {
  2513. FTerminal->Reopen(0);
  2514. }
  2515. //---------------------------------------------------------------------------
  2516. void __fastcall TTerminalThread::ProcessEvent()
  2517. {
  2518. DebugAssert(FEvent != NULL);
  2519. DebugAssert(FException == NULL);
  2520. // Needed at least for TXMLDocument use in TS3FileSystem
  2521. CoInitialize(NULL);
  2522. try
  2523. {
  2524. FAction(NULL);
  2525. }
  2526. catch(Exception & E)
  2527. {
  2528. SaveException(E, FException);
  2529. }
  2530. {
  2531. TGuard Guard(FSection);
  2532. if (!FAbandoned)
  2533. {
  2534. SetEvent(FActionEvent);
  2535. }
  2536. }
  2537. }
  2538. //---------------------------------------------------------------------------
  2539. void __fastcall TTerminalThread::Rethrow(Exception *& Exception)
  2540. {
  2541. if (Exception != NULL)
  2542. {
  2543. try
  2544. {
  2545. RethrowException(Exception);
  2546. }
  2547. __finally
  2548. {
  2549. SAFE_DESTROY(Exception);
  2550. }
  2551. }
  2552. }
  2553. //---------------------------------------------------------------------------
  2554. void __fastcall TTerminalThread::SaveException(Exception & E, Exception *& Exception)
  2555. {
  2556. DebugAssert(Exception == NULL);
  2557. Exception = CloneException(&E);
  2558. }
  2559. //---------------------------------------------------------------------------
  2560. void __fastcall TTerminalThread::FatalAbort()
  2561. {
  2562. if (FAbandoned)
  2563. {
  2564. // We cannot use TTerminal::FatalError as the terminal still runs on a background thread,
  2565. // may have its TCallbackGuard armed right now.
  2566. throw ESshFatal(NULL, L"");
  2567. }
  2568. else
  2569. {
  2570. FTerminal->FatalAbort();
  2571. }
  2572. }
  2573. //---------------------------------------------------------------------------
  2574. void __fastcall TTerminalThread::CheckCancel()
  2575. {
  2576. if (FCancel && !FCancelled)
  2577. {
  2578. FCancelled = true;
  2579. FatalAbort();
  2580. }
  2581. }
  2582. //---------------------------------------------------------------------------
  2583. void __fastcall TTerminalThread::WaitForUserAction(TUserAction * UserAction)
  2584. {
  2585. DWORD Thread = GetCurrentThreadId();
  2586. // we can get called from the main thread from within Idle,
  2587. // should be only to call HandleExtendedException
  2588. if (Thread == FMainThread)
  2589. {
  2590. if (UserAction != NULL)
  2591. {
  2592. UserAction->Execute(NULL);
  2593. }
  2594. }
  2595. else
  2596. {
  2597. // we should be called from our thread only,
  2598. // with exception noted above
  2599. DebugAssert(Thread == FThreadId);
  2600. bool DoCheckCancel =
  2601. DebugAlwaysFalse(UserAction == NULL) || !UserAction->Force() || FAbandoned;
  2602. if (DoCheckCancel)
  2603. {
  2604. CheckCancel();
  2605. }
  2606. // have to save it as we can go recursive via TQueryParams::TimerEvent,
  2607. // see TTerminalThread::TerminalQueryUser
  2608. TUserAction * PrevUserAction = FUserAction;
  2609. try
  2610. {
  2611. FUserAction = UserAction;
  2612. while (true)
  2613. {
  2614. {
  2615. TGuard Guard(FSection);
  2616. // If idle exception is already set, we are only waiting
  2617. // for the main thread to pick it up
  2618. // (or at least to finish handling the user action, so
  2619. // that we rethrow the idle exception below)
  2620. // Also if idle exception is set, it is probable that terminal
  2621. // is not active anyway.
  2622. if (FTerminal->Active && FPendingIdle && (FIdleException == NULL))
  2623. {
  2624. FPendingIdle = false;
  2625. try
  2626. {
  2627. FTerminal->Idle();
  2628. }
  2629. catch (Exception & E)
  2630. {
  2631. SaveException(E, FIdleException);
  2632. }
  2633. }
  2634. }
  2635. int WaitResult = WaitForEvent(1000);
  2636. if (WaitResult == 0)
  2637. {
  2638. SAFE_DESTROY(FIdleException);
  2639. FatalAbort();
  2640. }
  2641. else if (WaitResult > 0)
  2642. {
  2643. break;
  2644. }
  2645. }
  2646. Rethrow(FException);
  2647. if (FIdleException != NULL)
  2648. {
  2649. // idle exception was not used to cancel the user action
  2650. // (if it where it would be already cloned into the FException above
  2651. // and rethrown)
  2652. Rethrow(FIdleException);
  2653. }
  2654. }
  2655. __finally
  2656. {
  2657. FUserAction = PrevUserAction;
  2658. SAFE_DESTROY(FException);
  2659. }
  2660. // Contrary to a call before, this is unconditional,
  2661. // otherwise cancelling authentication won't work,
  2662. // if it is tried only after the last user action
  2663. // (what is common, when cancelling while waiting for
  2664. // resolving of unresolvable host name, where the last user action is
  2665. // "resolving hostname" information action)
  2666. CheckCancel();
  2667. }
  2668. }
  2669. //---------------------------------------------------------------------------
  2670. void __fastcall TTerminalThread::TerminalInformation(
  2671. TTerminal * Terminal, const UnicodeString & Str, int Phase, const UnicodeString & Additional)
  2672. {
  2673. TInformationUserAction Action(FOnInformation);
  2674. Action.Terminal = Terminal;
  2675. Action.Str = Str;
  2676. Action.Phase = Phase;
  2677. Action.Additional = Additional;
  2678. WaitForUserAction(&Action);
  2679. }
  2680. //---------------------------------------------------------------------------
  2681. void __fastcall TTerminalThread::TerminalQueryUser(TObject * Sender,
  2682. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  2683. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * Arg)
  2684. {
  2685. DebugUsedParam(Arg);
  2686. DebugAssert(Arg == NULL);
  2687. // note about TQueryParams::TimerEvent
  2688. // So far there is only one use for this, the TSecureShell::SendBuffer,
  2689. // which should be thread-safe, as long as the terminal thread,
  2690. // is stopped waiting for OnQueryUser to finish.
  2691. // note about TQueryButtonAlias::OnClick
  2692. // So far there is only one use for this, the TClipboardHandler,
  2693. // which is thread-safe.
  2694. TQueryUserAction Action(FOnQueryUser);
  2695. Action.Sender = Sender;
  2696. Action.Query = Query;
  2697. Action.MoreMessages = MoreMessages;
  2698. Action.Answers = Answers;
  2699. Action.Params = Params;
  2700. Action.Answer = Answer;
  2701. Action.Type = Type;
  2702. WaitForUserAction(&Action);
  2703. Answer = Action.Answer;
  2704. }
  2705. //---------------------------------------------------------------------------
  2706. void __fastcall TTerminalThread::TerminalInitializeLog(TObject * Sender)
  2707. {
  2708. if (FOnInitializeLog != NULL)
  2709. {
  2710. // never used, so not tested either
  2711. DebugFail();
  2712. TNotifyAction Action(FOnInitializeLog);
  2713. Action.Sender = Sender;
  2714. WaitForUserAction(&Action);
  2715. }
  2716. }
  2717. //---------------------------------------------------------------------------
  2718. void __fastcall TTerminalThread::TerminalPromptUser(TTerminal * Terminal,
  2719. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  2720. TStrings * Results, bool & Result, void * Arg)
  2721. {
  2722. DebugUsedParam(Arg);
  2723. DebugAssert(Arg == NULL);
  2724. TPromptUserAction Action(FOnPromptUser);
  2725. Action.Terminal = Terminal;
  2726. Action.Kind = Kind;
  2727. Action.Name = Name;
  2728. Action.Instructions = Instructions;
  2729. Action.Prompts = Prompts;
  2730. Action.Results->AddStrings(Results);
  2731. WaitForUserAction(&Action);
  2732. Results->Clear();
  2733. Results->AddStrings(Action.Results);
  2734. Result = Action.Result;
  2735. }
  2736. //---------------------------------------------------------------------------
  2737. void __fastcall TTerminalThread::TerminalShowExtendedException(
  2738. TTerminal * Terminal, Exception * E, void * Arg)
  2739. {
  2740. DebugUsedParam(Arg);
  2741. DebugAssert(Arg == NULL);
  2742. TShowExtendedExceptionAction Action(FOnShowExtendedException);
  2743. Action.Terminal = Terminal;
  2744. Action.E = E;
  2745. WaitForUserAction(&Action);
  2746. }
  2747. //---------------------------------------------------------------------------
  2748. void __fastcall TTerminalThread::TerminalDisplayBanner(TTerminal * Terminal,
  2749. UnicodeString SessionName, const UnicodeString & Banner,
  2750. bool & NeverShowAgain, int Options, unsigned int & Params)
  2751. {
  2752. TDisplayBannerAction Action(FOnDisplayBanner);
  2753. Action.Terminal = Terminal;
  2754. Action.SessionName = SessionName;
  2755. Action.Banner = Banner;
  2756. Action.NeverShowAgain = NeverShowAgain;
  2757. Action.Options = Options;
  2758. Action.Params = Params;
  2759. WaitForUserAction(&Action);
  2760. NeverShowAgain = Action.NeverShowAgain;
  2761. Params = Action.Params;
  2762. }
  2763. //---------------------------------------------------------------------------
  2764. void __fastcall TTerminalThread::TerminalChangeDirectory(TObject * Sender)
  2765. {
  2766. TNotifyAction Action(FOnChangeDirectory);
  2767. Action.Sender = Sender;
  2768. WaitForUserAction(&Action);
  2769. }
  2770. //---------------------------------------------------------------------------
  2771. void __fastcall TTerminalThread::TerminalReadDirectory(TObject * Sender, Boolean ReloadOnly)
  2772. {
  2773. TReadDirectoryAction Action(FOnReadDirectory);
  2774. Action.Sender = Sender;
  2775. Action.ReloadOnly = ReloadOnly;
  2776. WaitForUserAction(&Action);
  2777. }
  2778. //---------------------------------------------------------------------------
  2779. void __fastcall TTerminalThread::TerminalStartReadDirectory(TObject * Sender)
  2780. {
  2781. TNotifyAction Action(FOnStartReadDirectory);
  2782. Action.Sender = Sender;
  2783. WaitForUserAction(&Action);
  2784. }
  2785. //---------------------------------------------------------------------------
  2786. void __fastcall TTerminalThread::TerminalReadDirectoryProgress(
  2787. TObject * Sender, int Progress, int ResolvedLinks, bool & Cancel)
  2788. {
  2789. TReadDirectoryProgressAction Action(FOnReadDirectoryProgress);
  2790. Action.Sender = Sender;
  2791. Action.Progress = Progress;
  2792. Action.ResolvedLinks = ResolvedLinks;
  2793. Action.Cancel = Cancel;
  2794. WaitForUserAction(&Action);
  2795. Cancel = Action.Cancel;
  2796. }
  2797. //---------------------------------------------------------------------------
  2798. bool __fastcall TTerminalThread::Release()
  2799. {
  2800. bool Result = !FAbandoned;
  2801. if (Result)
  2802. {
  2803. delete this;
  2804. }
  2805. return Result;
  2806. }
  2807. //---------------------------------------------------------------------------
  2808. bool __fastcall TTerminalThread::Finished()
  2809. {
  2810. return TSimpleThread::Finished() || FAbandoned;
  2811. }
  2812. //---------------------------------------------------------------------------
  2813. //---------------------------------------------------------------------------
  2814. TQueueFileList::TQueueFileList() :
  2815. FList(new TStringList())
  2816. {
  2817. Clear();
  2818. }
  2819. //---------------------------------------------------------------------------
  2820. void TQueueFileList::Clear()
  2821. {
  2822. FList->Clear();
  2823. FLastParallelOperation = NULL;
  2824. FLastParallelOperationVersion = -1;
  2825. }
  2826. //---------------------------------------------------------------------------
  2827. void TQueueFileList::Add(const UnicodeString & FileName, int State)
  2828. {
  2829. FList->AddObject(FileName, reinterpret_cast<TObject *>(State));
  2830. }
  2831. //---------------------------------------------------------------------------
  2832. UnicodeString TQueueFileList::GetFileName(int Index) const
  2833. {
  2834. return FList->Strings[Index];
  2835. }
  2836. //---------------------------------------------------------------------------
  2837. int TQueueFileList::GetState(int Index) const
  2838. {
  2839. return reinterpret_cast<int>(FList->Objects[Index]);
  2840. }
  2841. //---------------------------------------------------------------------------
  2842. void TQueueFileList::SetState(int Index, int State)
  2843. {
  2844. FList->Objects[Index] = reinterpret_cast<TObject *>(State);
  2845. }
  2846. //---------------------------------------------------------------------------
  2847. int TQueueFileList::GetCount() const
  2848. {
  2849. return FList->Count;
  2850. }