Queue.cpp 87 KB

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