Queue.cpp 86 KB

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