Queue.cpp 85 KB

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