Queue.cpp 81 KB

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