Queue.cpp 81 KB

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