Queue.cpp 86 KB

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