Queue.cpp 81 KB

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