Queue.cpp 80 KB

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