Queue.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896
  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. TQueueItem * ParallelItem = DebugNotNull(Item->CreateParallelOperation());
  1063. if (!FEnabled)
  1064. {
  1065. FForcedItems->Add(ParallelItem);
  1066. }
  1067. AddItem(ParallelItem);
  1068. }
  1069. return Result;
  1070. }
  1071. //---------------------------------------------------------------------------
  1072. bool __fastcall TTerminalQueue::ContinueParallelOperation()
  1073. {
  1074. TGuard Guard(FItemsSection);
  1075. return (FItems->Count <= FItemsInProcess);
  1076. }
  1077. //---------------------------------------------------------------------------
  1078. // TBackgroundItem
  1079. //---------------------------------------------------------------------------
  1080. class TBackgroundTerminal : public TSecondaryTerminal
  1081. {
  1082. friend class TTerminalItem;
  1083. public:
  1084. __fastcall TBackgroundTerminal(TTerminal * MainTerminal,
  1085. TSessionData * SessionData, TConfiguration * Configuration,
  1086. TTerminalItem * Item, const UnicodeString & Name);
  1087. protected:
  1088. virtual bool __fastcall DoQueryReopen(Exception * E);
  1089. private:
  1090. TTerminalItem * FItem;
  1091. };
  1092. //---------------------------------------------------------------------------
  1093. __fastcall TBackgroundTerminal::TBackgroundTerminal(TTerminal * MainTerminal,
  1094. TSessionData * SessionData, TConfiguration * Configuration, TTerminalItem * Item,
  1095. const UnicodeString & Name) :
  1096. TSecondaryTerminal(MainTerminal, SessionData, Configuration, Name), FItem(Item)
  1097. {
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. bool __fastcall TBackgroundTerminal::DoQueryReopen(Exception * /*E*/)
  1101. {
  1102. bool Result;
  1103. if (FItem->FTerminated || FItem->FCancel)
  1104. {
  1105. // avoid reconnection if we are closing
  1106. Result = false;
  1107. }
  1108. else
  1109. {
  1110. Sleep(Configuration->SessionReopenBackground);
  1111. Result = true;
  1112. }
  1113. return Result;
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. // TTerminalItem
  1117. //---------------------------------------------------------------------------
  1118. __fastcall TTerminalItem::TTerminalItem(TTerminalQueue * Queue, int Index) :
  1119. TSignalThread(true), FQueue(Queue), FTerminal(NULL), FItem(NULL),
  1120. FCriticalSection(NULL), FUserAction(NULL)
  1121. {
  1122. FCriticalSection = new TCriticalSection();
  1123. FTerminal = new TBackgroundTerminal(FQueue->FTerminal, Queue->FSessionData,
  1124. FQueue->FConfiguration, this, FORMAT(L"Background %d", (Index)));
  1125. try
  1126. {
  1127. FTerminal->UseBusyCursor = false;
  1128. FTerminal->OnQueryUser = TerminalQueryUser;
  1129. FTerminal->OnPromptUser = TerminalPromptUser;
  1130. FTerminal->OnShowExtendedException = TerminalShowExtendedException;
  1131. FTerminal->OnProgress = OperationProgress;
  1132. FTerminal->OnFinished = OperationFinished;
  1133. }
  1134. catch(...)
  1135. {
  1136. delete FTerminal;
  1137. throw;
  1138. }
  1139. Start();
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. __fastcall TTerminalItem::~TTerminalItem()
  1143. {
  1144. Close();
  1145. DebugAssert(FItem == NULL);
  1146. delete FTerminal;
  1147. delete FCriticalSection;
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TTerminalItem::Process(TQueueItem * Item)
  1151. {
  1152. {
  1153. TGuard Guard(FCriticalSection);
  1154. DebugAssert(FItem == NULL);
  1155. FItem = Item;
  1156. }
  1157. TriggerEvent();
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. void __fastcall TTerminalItem::ProcessEvent()
  1161. {
  1162. TGuard Guard(FCriticalSection);
  1163. bool Retry = true;
  1164. FCancel = false;
  1165. FPause = false;
  1166. FItem->FTerminalItem = this;
  1167. try
  1168. {
  1169. DebugAssert(FItem != NULL);
  1170. if (!FTerminal->Active)
  1171. {
  1172. FItem->SetStatus(TQueueItem::qsConnecting);
  1173. FTerminal->SessionData->RemoteDirectory = FItem->StartupDirectory();
  1174. FTerminal->Open();
  1175. }
  1176. Retry = false;
  1177. if (!FCancel)
  1178. {
  1179. FTerminal->UpdateFromMain();
  1180. FItem->SetStatus(TQueueItem::qsProcessing);
  1181. FItem->Execute(this);
  1182. }
  1183. }
  1184. catch(Exception & E)
  1185. {
  1186. UnicodeString Message;
  1187. if (ExceptionMessageFormatted(&E, Message))
  1188. {
  1189. // do not show error messages, if task was cancelled anyway
  1190. // (for example if transfer is cancelled during reconnection attempts)
  1191. if (!FCancel &&
  1192. (FTerminal->QueryUserException(L"", &E, qaOK | qaCancel, NULL, qtError) == qaCancel))
  1193. {
  1194. FCancel = true;
  1195. }
  1196. }
  1197. }
  1198. FItem->SetStatus(TQueueItem::qsDone);
  1199. FItem->FTerminalItem = NULL;
  1200. TQueueItem * Item = FItem;
  1201. FItem = NULL;
  1202. if (Retry && !FCancel)
  1203. {
  1204. FQueue->RetryItem(Item);
  1205. }
  1206. else
  1207. {
  1208. FQueue->DeleteItem(Item, !FCancel);
  1209. }
  1210. if (!FTerminal->Active ||
  1211. !FQueue->TerminalFree(this))
  1212. {
  1213. Terminate();
  1214. }
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. void __fastcall TTerminalItem::Idle()
  1218. {
  1219. TGuard Guard(FCriticalSection);
  1220. DebugAssert(FTerminal->Active);
  1221. try
  1222. {
  1223. FTerminal->Idle();
  1224. }
  1225. catch(...)
  1226. {
  1227. }
  1228. if (!FTerminal->Active ||
  1229. !FQueue->TerminalFree(this))
  1230. {
  1231. Terminate();
  1232. }
  1233. }
  1234. //---------------------------------------------------------------------------
  1235. void __fastcall TTerminalItem::Cancel()
  1236. {
  1237. FCancel = true;
  1238. if ((FItem->GetStatus() == TQueueItem::qsPaused) ||
  1239. TQueueItem::IsUserActionStatus(FItem->GetStatus()))
  1240. {
  1241. TriggerEvent();
  1242. }
  1243. }
  1244. //---------------------------------------------------------------------------
  1245. bool __fastcall TTerminalItem::Pause()
  1246. {
  1247. DebugAssert(FItem != NULL);
  1248. bool Result = (FItem->GetStatus() == TQueueItem::qsProcessing) && !FPause;
  1249. if (Result)
  1250. {
  1251. FPause = true;
  1252. }
  1253. return Result;
  1254. }
  1255. //---------------------------------------------------------------------------
  1256. bool __fastcall TTerminalItem::Resume()
  1257. {
  1258. DebugAssert(FItem != NULL);
  1259. bool Result = (FItem->GetStatus() == TQueueItem::qsPaused);
  1260. if (Result)
  1261. {
  1262. TriggerEvent();
  1263. }
  1264. return Result;
  1265. }
  1266. //---------------------------------------------------------------------------
  1267. bool __fastcall TTerminalItem::ProcessUserAction(void * Arg)
  1268. {
  1269. // When status is changed twice quickly, the controller when responding
  1270. // to the first change (non-user-action) can be so slow to check only after
  1271. // the second (user-action) change occurs. Thus it responds it.
  1272. // Then as reaction to the second (user-action) change there will not be
  1273. // any outstanding user-action.
  1274. bool Result = (FUserAction != NULL);
  1275. if (Result)
  1276. {
  1277. DebugAssert(FItem != NULL);
  1278. FUserAction->Execute(Arg);
  1279. FUserAction = NULL;
  1280. TriggerEvent();
  1281. }
  1282. return Result;
  1283. }
  1284. //---------------------------------------------------------------------------
  1285. bool __fastcall TTerminalItem::WaitForUserAction(
  1286. TQueueItem::TStatus ItemStatus, TUserAction * UserAction)
  1287. {
  1288. DebugAssert(FItem != NULL);
  1289. DebugAssert((FItem->GetStatus() == TQueueItem::qsProcessing) ||
  1290. (FItem->GetStatus() == TQueueItem::qsConnecting));
  1291. bool Result;
  1292. TQueueItem::TStatus PrevStatus = FItem->GetStatus();
  1293. try
  1294. {
  1295. FUserAction = UserAction;
  1296. FItem->SetStatus(ItemStatus);
  1297. FQueue->DoEvent(qePendingUserAction);
  1298. Result = !FTerminated && WaitForEvent() && !FCancel;
  1299. }
  1300. __finally
  1301. {
  1302. FUserAction = NULL;
  1303. FItem->SetStatus(PrevStatus);
  1304. }
  1305. return Result;
  1306. }
  1307. //---------------------------------------------------------------------------
  1308. bool __fastcall TTerminalItem::Finished()
  1309. {
  1310. bool Result = TSignalThread::Finished();
  1311. FQueue->TerminalFinished(this);
  1312. return Result;
  1313. }
  1314. //---------------------------------------------------------------------------
  1315. void __fastcall TTerminalItem::TerminalQueryUser(TObject * Sender,
  1316. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  1317. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * Arg)
  1318. {
  1319. // so far query without queue item can occur only for key confirmation
  1320. // on re-key with non-cached host key. make it fail.
  1321. if (FItem != NULL)
  1322. {
  1323. DebugUsedParam(Arg);
  1324. DebugAssert(Arg == NULL);
  1325. TQueryUserAction Action(FQueue->OnQueryUser);
  1326. Action.Sender = Sender;
  1327. Action.Query = Query;
  1328. Action.MoreMessages = MoreMessages;
  1329. Action.Answers = Answers;
  1330. Action.Params = Params;
  1331. Action.Answer = Answer;
  1332. Action.Type = Type;
  1333. // if the query is "error", present it as an "error" state in UI,
  1334. // however it is still handled as query by the action.
  1335. TQueueItem::TStatus ItemStatus =
  1336. (Action.Type == qtError ? TQueueItem::qsError : TQueueItem::qsQuery);
  1337. if (WaitForUserAction(ItemStatus, &Action))
  1338. {
  1339. Answer = Action.Answer;
  1340. }
  1341. }
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. void __fastcall TTerminalItem::TerminalPromptUser(TTerminal * Terminal,
  1345. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  1346. TStrings * Results, bool & Result, void * Arg)
  1347. {
  1348. if (FItem == NULL)
  1349. {
  1350. // sanity, should not occur
  1351. DebugFail();
  1352. Result = false;
  1353. }
  1354. else
  1355. {
  1356. DebugUsedParam(Arg);
  1357. DebugAssert(Arg == NULL);
  1358. TPromptUserAction Action(FQueue->OnPromptUser);
  1359. Action.Terminal = Terminal;
  1360. Action.Kind = Kind;
  1361. Action.Name = Name;
  1362. Action.Instructions = Instructions;
  1363. Action.Prompts = Prompts;
  1364. Action.Results->AddStrings(Results);
  1365. if (WaitForUserAction(TQueueItem::qsPrompt, &Action))
  1366. {
  1367. Results->Clear();
  1368. Results->AddStrings(Action.Results);
  1369. Result = Action.Result;
  1370. }
  1371. }
  1372. }
  1373. //---------------------------------------------------------------------------
  1374. void __fastcall TTerminalItem::TerminalShowExtendedException(
  1375. TTerminal * Terminal, Exception * E, void * Arg)
  1376. {
  1377. DebugUsedParam(Arg);
  1378. DebugAssert(Arg == NULL);
  1379. if ((FItem != NULL) &&
  1380. ShouldDisplayException(E))
  1381. {
  1382. TShowExtendedExceptionAction Action(FQueue->OnShowExtendedException);
  1383. Action.Terminal = Terminal;
  1384. Action.E = E;
  1385. WaitForUserAction(TQueueItem::qsError, &Action);
  1386. }
  1387. }
  1388. //---------------------------------------------------------------------------
  1389. void __fastcall TTerminalItem::OperationFinished(TFileOperation /*Operation*/,
  1390. TOperationSide /*Side*/, bool /*Temp*/, const UnicodeString & /*FileName*/,
  1391. bool /*Success*/, TOnceDoneOperation & /*OnceDoneOperation*/)
  1392. {
  1393. // nothing
  1394. }
  1395. //---------------------------------------------------------------------------
  1396. void __fastcall TTerminalItem::OperationProgress(
  1397. TFileOperationProgressType & ProgressData)
  1398. {
  1399. if (FPause && !FTerminated && !FCancel)
  1400. {
  1401. DebugAssert(FItem != NULL);
  1402. TQueueItem::TStatus PrevStatus = FItem->GetStatus();
  1403. DebugAssert(PrevStatus == TQueueItem::qsProcessing);
  1404. // must be set before TFileOperationProgressType::Suspend(), because
  1405. // it invokes this method back
  1406. FPause = false;
  1407. ProgressData.Suspend();
  1408. try
  1409. {
  1410. FItem->SetStatus(TQueueItem::qsPaused);
  1411. WaitForEvent();
  1412. }
  1413. __finally
  1414. {
  1415. FItem->SetStatus(PrevStatus);
  1416. ProgressData.Resume();
  1417. }
  1418. }
  1419. if (FTerminated || FCancel)
  1420. {
  1421. if (ProgressData.TransferringFile)
  1422. {
  1423. ProgressData.SetCancel(csCancelTransfer);
  1424. }
  1425. else
  1426. {
  1427. ProgressData.SetCancel(csCancel);
  1428. }
  1429. }
  1430. DebugAssert(FItem != NULL);
  1431. FItem->SetProgress(ProgressData);
  1432. }
  1433. //---------------------------------------------------------------------------
  1434. bool __fastcall TTerminalItem::OverrideItemStatus(TQueueItem::TStatus & ItemStatus)
  1435. {
  1436. DebugAssert(FTerminal != NULL);
  1437. bool Result = (FTerminal->Status < ssOpened) && (ItemStatus == TQueueItem::qsProcessing);
  1438. if (Result)
  1439. {
  1440. ItemStatus = TQueueItem::qsConnecting;
  1441. }
  1442. return Result;
  1443. }
  1444. //---------------------------------------------------------------------------
  1445. // TQueueItem
  1446. //---------------------------------------------------------------------------
  1447. __fastcall TQueueItem::TQueueItem() :
  1448. FStatus(qsPending), FTerminalItem(NULL), FSection(NULL), FProgressData(NULL),
  1449. FQueue(NULL), FInfo(NULL), FCompleteEvent(INVALID_HANDLE_VALUE),
  1450. FCPSLimit(-1)
  1451. {
  1452. FSection = new TCriticalSection();
  1453. FInfo = new TInfo();
  1454. FInfo->SingleFile = false;
  1455. FInfo->Primary = true;
  1456. FInfo->GroupToken = this;
  1457. }
  1458. //---------------------------------------------------------------------------
  1459. __fastcall TQueueItem::~TQueueItem()
  1460. {
  1461. // we need to keep the total transfer size even after transfer completes
  1462. delete FProgressData;
  1463. Complete();
  1464. delete FSection;
  1465. delete FInfo;
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. bool __fastcall TQueueItem::Complete()
  1469. {
  1470. TGuard Guard(FSection);
  1471. if (FCompleteEvent != INVALID_HANDLE_VALUE)
  1472. {
  1473. SetEvent(FCompleteEvent);
  1474. FCompleteEvent = INVALID_HANDLE_VALUE;
  1475. }
  1476. return FInfo->Primary;
  1477. }
  1478. //---------------------------------------------------------------------------
  1479. bool __fastcall TQueueItem::IsUserActionStatus(TStatus Status)
  1480. {
  1481. return (Status == qsQuery) || (Status == qsError) || (Status == qsPrompt);
  1482. }
  1483. //---------------------------------------------------------------------------
  1484. TQueueItem::TStatus __fastcall TQueueItem::GetStatus()
  1485. {
  1486. TGuard Guard(FSection);
  1487. return FStatus;
  1488. }
  1489. //---------------------------------------------------------------------------
  1490. void __fastcall TQueueItem::SetStatus(TStatus Status)
  1491. {
  1492. {
  1493. TGuard Guard(FSection);
  1494. FStatus = Status;
  1495. if (FStatus == qsDone)
  1496. {
  1497. FDoneAt = Now();
  1498. }
  1499. }
  1500. DebugAssert((FQueue != NULL) || (Status == qsPending));
  1501. if (FQueue != NULL)
  1502. {
  1503. FQueue->DoQueueItemUpdate(this);
  1504. }
  1505. }
  1506. //---------------------------------------------------------------------------
  1507. void __fastcall TQueueItem::ProgressUpdated()
  1508. {
  1509. // noop
  1510. }
  1511. //---------------------------------------------------------------------------
  1512. void __fastcall TQueueItem::SetProgress(
  1513. TFileOperationProgressType & ProgressData)
  1514. {
  1515. {
  1516. TGuard Guard(FSection);
  1517. // do not lose CPS limit override on "calculate size" operation,
  1518. // wait until the real transfer operation starts
  1519. if ((FCPSLimit >= 0) && ((ProgressData.Operation == foMove) || (ProgressData.Operation == foCopy)))
  1520. {
  1521. ProgressData.SetCPSLimit(static_cast<unsigned long>(FCPSLimit));
  1522. FCPSLimit = -1;
  1523. }
  1524. DebugAssert(FProgressData != NULL);
  1525. FProgressData->Assign(ProgressData);
  1526. FProgressData->Reset();
  1527. }
  1528. ProgressUpdated();
  1529. FQueue->DoQueueItemUpdate(this);
  1530. }
  1531. //---------------------------------------------------------------------------
  1532. void __fastcall TQueueItem::GetData(TQueueItemProxy * Proxy)
  1533. {
  1534. TGuard Guard(FSection);
  1535. DebugAssert(Proxy->FProgressData != NULL);
  1536. if (FProgressData != NULL)
  1537. {
  1538. Proxy->FProgressData->Assign(*FProgressData);
  1539. }
  1540. else
  1541. {
  1542. Proxy->FProgressData->Clear();
  1543. }
  1544. *Proxy->FInfo = *FInfo;
  1545. Proxy->FStatus = FStatus;
  1546. if (FTerminalItem != NULL)
  1547. {
  1548. FTerminalItem->OverrideItemStatus(Proxy->FStatus);
  1549. }
  1550. }
  1551. //---------------------------------------------------------------------------
  1552. void __fastcall TQueueItem::Execute(TTerminalItem * TerminalItem)
  1553. {
  1554. {
  1555. DebugAssert(FProgressData == NULL);
  1556. TGuard Guard(FSection);
  1557. FProgressData = new TFileOperationProgressType();
  1558. }
  1559. DoExecute(TerminalItem->FTerminal);
  1560. }
  1561. //---------------------------------------------------------------------------
  1562. void __fastcall TQueueItem::SetCPSLimit(unsigned long CPSLimit)
  1563. {
  1564. FCPSLimit = static_cast<long>(CPSLimit);
  1565. }
  1566. //---------------------------------------------------------------------------
  1567. unsigned long __fastcall TQueueItem::DefaultCPSLimit()
  1568. {
  1569. return 0;
  1570. }
  1571. //---------------------------------------------------------------------------
  1572. unsigned long __fastcall TQueueItem::GetCPSLimit()
  1573. {
  1574. unsigned long Result;
  1575. if (FCPSLimit >= 0)
  1576. {
  1577. Result = FCPSLimit;
  1578. }
  1579. else if (FProgressData != NULL)
  1580. {
  1581. Result = FProgressData->CPSLimit;
  1582. }
  1583. else
  1584. {
  1585. Result = DefaultCPSLimit();
  1586. }
  1587. return Result;
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. TQueueItem * __fastcall TQueueItem::CreateParallelOperation()
  1591. {
  1592. return NULL;
  1593. }
  1594. //---------------------------------------------------------------------------
  1595. // TQueueItemProxy
  1596. //---------------------------------------------------------------------------
  1597. __fastcall TQueueItemProxy::TQueueItemProxy(TTerminalQueue * Queue,
  1598. TQueueItem * QueueItem) :
  1599. FQueue(Queue), FQueueItem(QueueItem), FProgressData(NULL),
  1600. FQueueStatus(NULL), FInfo(NULL),
  1601. FProcessingUserAction(false), FUserData(NULL)
  1602. {
  1603. FProgressData = new TFileOperationProgressType();
  1604. FInfo = new TQueueItem::TInfo();
  1605. Update();
  1606. }
  1607. //---------------------------------------------------------------------------
  1608. __fastcall TQueueItemProxy::~TQueueItemProxy()
  1609. {
  1610. delete FProgressData;
  1611. delete FInfo;
  1612. }
  1613. //---------------------------------------------------------------------------
  1614. TFileOperationProgressType * __fastcall TQueueItemProxy::GetProgressData()
  1615. {
  1616. return (FProgressData->Operation == foNone) ? NULL : FProgressData;
  1617. }
  1618. //---------------------------------------------------------------------------
  1619. __int64 __fastcall TQueueItemProxy::GetTotalTransferred()
  1620. {
  1621. // want to show total transferred also for "completed" items,
  1622. // for which GetProgressData() is NULL
  1623. return
  1624. (FProgressData->Operation == Info->Operation) || (Status == TQueueItem::qsDone) ?
  1625. FProgressData->TotalTransferred : -1;
  1626. }
  1627. //---------------------------------------------------------------------------
  1628. bool __fastcall TQueueItemProxy::Update()
  1629. {
  1630. DebugAssert(FQueueItem != NULL);
  1631. TQueueItem::TStatus PrevStatus = Status;
  1632. bool Result = FQueue->ItemGetData(FQueueItem, this);
  1633. if ((FQueueStatus != NULL) && (PrevStatus != Status))
  1634. {
  1635. FQueueStatus->ResetStats();
  1636. }
  1637. return Result;
  1638. }
  1639. //---------------------------------------------------------------------------
  1640. bool __fastcall TQueueItemProxy::ExecuteNow()
  1641. {
  1642. return FQueue->ItemExecuteNow(FQueueItem);
  1643. }
  1644. //---------------------------------------------------------------------------
  1645. bool __fastcall TQueueItemProxy::Move(bool Sooner)
  1646. {
  1647. bool Result = false;
  1648. int I = Index;
  1649. if (Sooner)
  1650. {
  1651. if (I > 0)
  1652. {
  1653. Result = Move(FQueueStatus->Items[I - 1]);
  1654. }
  1655. }
  1656. else
  1657. {
  1658. if (I < FQueueStatus->Count - 1)
  1659. {
  1660. Result = FQueueStatus->Items[I + 1]->Move(this);
  1661. }
  1662. }
  1663. return Result;
  1664. }
  1665. //---------------------------------------------------------------------------
  1666. bool __fastcall TQueueItemProxy::Move(TQueueItemProxy * BeforeItem)
  1667. {
  1668. return FQueue->ItemMove(FQueueItem, BeforeItem->FQueueItem);
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. bool __fastcall TQueueItemProxy::Delete()
  1672. {
  1673. return FQueue->ItemDelete(FQueueItem);
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. bool __fastcall TQueueItemProxy::Pause()
  1677. {
  1678. return FQueue->ItemPause(FQueueItem, true);
  1679. }
  1680. //---------------------------------------------------------------------------
  1681. bool __fastcall TQueueItemProxy::Resume()
  1682. {
  1683. return FQueue->ItemPause(FQueueItem, false);
  1684. }
  1685. //---------------------------------------------------------------------------
  1686. bool __fastcall TQueueItemProxy::ProcessUserAction()
  1687. {
  1688. DebugAssert(FQueueItem != NULL);
  1689. bool Result;
  1690. FProcessingUserAction = true;
  1691. try
  1692. {
  1693. Result = FQueue->ItemProcessUserAction(FQueueItem, NULL);
  1694. }
  1695. __finally
  1696. {
  1697. FProcessingUserAction = false;
  1698. }
  1699. return Result;
  1700. }
  1701. //---------------------------------------------------------------------------
  1702. bool __fastcall TQueueItemProxy::GetCPSLimit(unsigned long & CPSLimit)
  1703. {
  1704. return FQueue->ItemGetCPSLimit(FQueueItem, CPSLimit);
  1705. }
  1706. //---------------------------------------------------------------------------
  1707. bool __fastcall TQueueItemProxy::SetCPSLimit(unsigned long CPSLimit)
  1708. {
  1709. return FQueue->ItemSetCPSLimit(FQueueItem, CPSLimit);
  1710. }
  1711. //---------------------------------------------------------------------------
  1712. int __fastcall TQueueItemProxy::GetIndex()
  1713. {
  1714. DebugAssert(FQueueStatus != NULL);
  1715. int Index = FQueueStatus->FList->IndexOf(this);
  1716. DebugAssert(Index >= 0);
  1717. return Index;
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. // TTerminalQueueStatus
  1721. //---------------------------------------------------------------------------
  1722. __fastcall TTerminalQueueStatus::TTerminalQueueStatus() :
  1723. FList(NULL)
  1724. {
  1725. FList = new TList();
  1726. ResetStats();
  1727. }
  1728. //---------------------------------------------------------------------------
  1729. __fastcall TTerminalQueueStatus::~TTerminalQueueStatus()
  1730. {
  1731. for (int Index = 0; Index < FList->Count; Index++)
  1732. {
  1733. delete GetItem(Index);
  1734. }
  1735. delete FList;
  1736. FList = NULL;
  1737. }
  1738. //---------------------------------------------------------------------------
  1739. void __fastcall TTerminalQueueStatus::ResetStats()
  1740. {
  1741. FActiveCount = -1;
  1742. FActivePrimaryCount = -1;
  1743. FActiveAndPendingPrimaryCount = -1;
  1744. }
  1745. //---------------------------------------------------------------------------
  1746. void __fastcall TTerminalQueueStatus::SetDoneCount(int Value)
  1747. {
  1748. FDoneCount = Value;
  1749. ResetStats();
  1750. }
  1751. //---------------------------------------------------------------------------
  1752. void __fastcall TTerminalQueueStatus::NeedStats()
  1753. {
  1754. if (FActiveCount < 0)
  1755. {
  1756. FActiveCount = 0;
  1757. FActivePrimaryCount = 0;
  1758. FActiveAndPendingPrimaryCount = 0;
  1759. for (int Index = DoneCount; Index < Count; Index++)
  1760. {
  1761. bool Primary = GetItem(Index)->Info->Primary;
  1762. if (GetItem(Index)->Status != TQueueItem::qsPending)
  1763. {
  1764. FActiveCount++;
  1765. if (Primary)
  1766. {
  1767. FActivePrimaryCount++;
  1768. }
  1769. }
  1770. if (Primary)
  1771. {
  1772. FActiveAndPendingPrimaryCount++;
  1773. }
  1774. }
  1775. }
  1776. }
  1777. //---------------------------------------------------------------------------
  1778. int __fastcall TTerminalQueueStatus::GetActiveCount()
  1779. {
  1780. NeedStats();
  1781. return FActiveCount;
  1782. }
  1783. //---------------------------------------------------------------------------
  1784. int __fastcall TTerminalQueueStatus::GetDoneAndActiveCount()
  1785. {
  1786. return DoneCount + ActiveCount;
  1787. }
  1788. //---------------------------------------------------------------------------
  1789. int __fastcall TTerminalQueueStatus::GetActivePrimaryCount()
  1790. {
  1791. NeedStats();
  1792. return FActivePrimaryCount;
  1793. }
  1794. //---------------------------------------------------------------------------
  1795. bool __fastcall TTerminalQueueStatus::IsOnlyOneActiveAndNoPending()
  1796. {
  1797. return (ActivePrimaryCount == 1) && (ActiveAndPendingPrimaryCount == 1);
  1798. }
  1799. //---------------------------------------------------------------------------
  1800. int __fastcall TTerminalQueueStatus::GetActiveAndPendingPrimaryCount()
  1801. {
  1802. NeedStats();
  1803. return FActiveAndPendingPrimaryCount;
  1804. }
  1805. //---------------------------------------------------------------------------
  1806. void __fastcall TTerminalQueueStatus::Add(TQueueItemProxy * ItemProxy)
  1807. {
  1808. ItemProxy->FQueueStatus = this;
  1809. int Index = FList->Count;
  1810. if (!ItemProxy->Info->Primary)
  1811. {
  1812. for (int I = 0; I < FList->Count; I++)
  1813. {
  1814. if (Items[I]->Info->GroupToken == ItemProxy->Info->GroupToken)
  1815. {
  1816. Index = I + 1;
  1817. }
  1818. }
  1819. DebugAssert(Index >= 0);
  1820. }
  1821. FList->Insert(Index, ItemProxy);
  1822. ResetStats();
  1823. }
  1824. //---------------------------------------------------------------------------
  1825. void __fastcall TTerminalQueueStatus::Delete(TQueueItemProxy * ItemProxy)
  1826. {
  1827. FList->Extract(ItemProxy);
  1828. ItemProxy->FQueueStatus = NULL;
  1829. ResetStats();
  1830. }
  1831. //---------------------------------------------------------------------------
  1832. int __fastcall TTerminalQueueStatus::GetCount()
  1833. {
  1834. return FList->Count;
  1835. }
  1836. //---------------------------------------------------------------------------
  1837. TQueueItemProxy * __fastcall TTerminalQueueStatus::GetItem(int Index)
  1838. {
  1839. return reinterpret_cast<TQueueItemProxy *>(FList->Items[Index]);
  1840. }
  1841. //---------------------------------------------------------------------------
  1842. TQueueItemProxy * __fastcall TTerminalQueueStatus::FindByQueueItem(
  1843. TQueueItem * QueueItem)
  1844. {
  1845. TQueueItemProxy * Item;
  1846. for (int Index = 0; Index < FList->Count; Index++)
  1847. {
  1848. Item = GetItem(Index);
  1849. if (Item->FQueueItem == QueueItem)
  1850. {
  1851. return Item;
  1852. }
  1853. }
  1854. return NULL;
  1855. }
  1856. //---------------------------------------------------------------------------
  1857. // TBootstrapQueueItem
  1858. //---------------------------------------------------------------------------
  1859. __fastcall TBootstrapQueueItem::TBootstrapQueueItem()
  1860. {
  1861. FInfo->SingleFile = true;
  1862. }
  1863. //---------------------------------------------------------------------------
  1864. void __fastcall TBootstrapQueueItem::DoExecute(TTerminal * DebugUsedArg(Terminal))
  1865. {
  1866. // noop
  1867. }
  1868. //---------------------------------------------------------------------------
  1869. UnicodeString __fastcall TBootstrapQueueItem::StartupDirectory() const
  1870. {
  1871. return UnicodeString();
  1872. }
  1873. //---------------------------------------------------------------------------
  1874. bool __fastcall TBootstrapQueueItem::Complete()
  1875. {
  1876. TQueueItem::Complete();
  1877. // To hide the item, even if "keep done items" is on
  1878. return false;
  1879. }
  1880. //---------------------------------------------------------------------------
  1881. // TLocatedQueueItem
  1882. //---------------------------------------------------------------------------
  1883. __fastcall TLocatedQueueItem::TLocatedQueueItem(TTerminal * Terminal) :
  1884. TQueueItem()
  1885. {
  1886. DebugAssert(Terminal != NULL);
  1887. FCurrentDir = Terminal->CurrentDirectory;
  1888. }
  1889. //---------------------------------------------------------------------------
  1890. __fastcall TLocatedQueueItem::TLocatedQueueItem(const TLocatedQueueItem & Source) :
  1891. TQueueItem()
  1892. {
  1893. FCurrentDir = Source.FCurrentDir;
  1894. }
  1895. //---------------------------------------------------------------------------
  1896. UnicodeString __fastcall TLocatedQueueItem::StartupDirectory() const
  1897. {
  1898. return FCurrentDir;
  1899. }
  1900. //---------------------------------------------------------------------------
  1901. void __fastcall TLocatedQueueItem::DoExecute(TTerminal * Terminal)
  1902. {
  1903. DebugAssert(Terminal != NULL);
  1904. Terminal->CurrentDirectory = FCurrentDir;
  1905. }
  1906. //---------------------------------------------------------------------------
  1907. // TTransferQueueItem
  1908. //---------------------------------------------------------------------------
  1909. __fastcall TTransferQueueItem::TTransferQueueItem(TTerminal * Terminal,
  1910. TStrings * FilesToCopy, const UnicodeString & TargetDir,
  1911. const TCopyParamType * CopyParam, int Params, TOperationSide Side,
  1912. bool SingleFile, bool Parallel) :
  1913. TLocatedQueueItem(Terminal), FFilesToCopy(NULL), FCopyParam(NULL)
  1914. {
  1915. FInfo->Operation = (Params & cpDelete ? foMove : foCopy);
  1916. FInfo->Side = Side;
  1917. FInfo->SingleFile = SingleFile;
  1918. DebugAssert(FilesToCopy != NULL);
  1919. FFilesToCopy = new TStringList();
  1920. for (int Index = 0; Index < FilesToCopy->Count; Index++)
  1921. {
  1922. FFilesToCopy->AddObject(FilesToCopy->Strings[Index],
  1923. ((FilesToCopy->Objects[Index] == NULL) || (Side == osLocal)) ? NULL :
  1924. dynamic_cast<TRemoteFile*>(FilesToCopy->Objects[Index])->Duplicate());
  1925. }
  1926. FTargetDir = TargetDir;
  1927. DebugAssert(CopyParam != NULL);
  1928. FCopyParam = new TCopyParamType(*CopyParam);
  1929. FParams = Params;
  1930. FParallel = Parallel;
  1931. FLastParallelOperationAdded = GetTickCount();
  1932. }
  1933. //---------------------------------------------------------------------------
  1934. __fastcall TTransferQueueItem::~TTransferQueueItem()
  1935. {
  1936. for (int Index = 0; Index < FFilesToCopy->Count; Index++)
  1937. {
  1938. delete FFilesToCopy->Objects[Index];
  1939. }
  1940. delete FFilesToCopy;
  1941. delete FCopyParam;
  1942. }
  1943. //---------------------------------------------------------------------------
  1944. unsigned long __fastcall TTransferQueueItem::DefaultCPSLimit()
  1945. {
  1946. return FCopyParam->CPSLimit;
  1947. }
  1948. //---------------------------------------------------------------------------
  1949. void __fastcall TTransferQueueItem::DoExecute(TTerminal * Terminal)
  1950. {
  1951. TLocatedQueueItem::DoExecute(Terminal);
  1952. DebugAssert(Terminal != NULL);
  1953. TParallelOperation ParallelOperation(FInfo->Side);
  1954. FParallelOperation = &ParallelOperation;
  1955. try
  1956. {
  1957. DoTransferExecute(Terminal, FParallelOperation);
  1958. }
  1959. __finally
  1960. {
  1961. FParallelOperation = NULL;
  1962. }
  1963. }
  1964. //---------------------------------------------------------------------------
  1965. void __fastcall TTransferQueueItem::ProgressUpdated()
  1966. {
  1967. TLocatedQueueItem::ProgressUpdated();
  1968. if (FParallel)
  1969. {
  1970. bool Add = false;
  1971. bool Force = false;
  1972. DWORD LastParallelOperationAddedPrev = 0;
  1973. {
  1974. TGuard Guard(FSection);
  1975. DebugAssert(FParallelOperation != NULL);
  1976. // Won't be initialized, if the operation is not eligible for parallel transfers (like cpDelete).
  1977. // We can probably move the check outside of the guard.
  1978. if (FParallelOperation->IsInitialized())
  1979. {
  1980. DebugAssert((FProgressData->Operation == foCopy) || (FProgressData->Operation == foCalculateSize));
  1981. if (FProgressData->Operation == foCopy)
  1982. {
  1983. Add = FParallelOperation->ShouldAddClient();
  1984. if (Add)
  1985. {
  1986. DWORD Now = GetTickCount();
  1987. Force =
  1988. (Now - FLastParallelOperationAdded >= 5*1000) &&
  1989. (TimeToSeconds(FProgressData->TotalTimeLeft()) >= FQueue->ParallelDurationThreshold);
  1990. LastParallelOperationAddedPrev = FLastParallelOperationAdded;
  1991. // update now already to prevent race condition, but we will have to rollback it back,
  1992. // if we actually do not add the parallel operation
  1993. FLastParallelOperationAdded = Now;
  1994. }
  1995. }
  1996. }
  1997. }
  1998. if (Add)
  1999. {
  2000. if (!FQueue->TryAddParallelOperation(this, Force))
  2001. {
  2002. TGuard Guard(FSection);
  2003. FLastParallelOperationAdded = LastParallelOperationAddedPrev;
  2004. }
  2005. }
  2006. }
  2007. }
  2008. //---------------------------------------------------------------------------
  2009. TQueueItem * __fastcall TTransferQueueItem::CreateParallelOperation()
  2010. {
  2011. DebugAssert(FParallelOperation != NULL);
  2012. FParallelOperation->AddClient();
  2013. return new TParallelTransferQueueItem(this, FParallelOperation);
  2014. }
  2015. //---------------------------------------------------------------------------
  2016. // TUploadQueueItem
  2017. //---------------------------------------------------------------------------
  2018. __fastcall TUploadQueueItem::TUploadQueueItem(TTerminal * Terminal,
  2019. TStrings * FilesToCopy, const UnicodeString & TargetDir,
  2020. const TCopyParamType * CopyParam, int Params, bool SingleFile, bool Parallel) :
  2021. TTransferQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, osLocal, SingleFile, Parallel)
  2022. {
  2023. if (FilesToCopy->Count > 1)
  2024. {
  2025. if (FLAGSET(Params, cpTemporary))
  2026. {
  2027. FInfo->Source = L"";
  2028. FInfo->ModifiedLocal = L"";
  2029. }
  2030. else
  2031. {
  2032. ExtractCommonPath(FilesToCopy, FInfo->Source);
  2033. // this way the trailing backslash is preserved for root directories like D:\\
  2034. FInfo->Source = ExtractFileDir(IncludeTrailingBackslash(FInfo->Source));
  2035. FInfo->ModifiedLocal = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2036. IncludeTrailingBackslash(FInfo->Source);
  2037. }
  2038. }
  2039. else
  2040. {
  2041. if (FLAGSET(Params, cpTemporary))
  2042. {
  2043. FInfo->Source = ExtractFileName(FilesToCopy->Strings[0]);
  2044. FInfo->ModifiedLocal = L"";
  2045. }
  2046. else
  2047. {
  2048. DebugAssert(FilesToCopy->Count > 0);
  2049. FInfo->Source = FilesToCopy->Strings[0];
  2050. FInfo->ModifiedLocal = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2051. IncludeTrailingBackslash(ExtractFilePath(FInfo->Source));
  2052. }
  2053. }
  2054. FInfo->Destination =
  2055. UnixIncludeTrailingBackslash(TargetDir) + CopyParam->FileMask;
  2056. FInfo->ModifiedRemote = UnixIncludeTrailingBackslash(TargetDir);
  2057. }
  2058. //---------------------------------------------------------------------------
  2059. void __fastcall TUploadQueueItem::DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  2060. {
  2061. Terminal->CopyToRemote(FFilesToCopy, FTargetDir, FCopyParam, FParams, ParallelOperation);
  2062. }
  2063. //---------------------------------------------------------------------------
  2064. // TParallelTransferQueueItem
  2065. //---------------------------------------------------------------------------
  2066. __fastcall TParallelTransferQueueItem::TParallelTransferQueueItem(
  2067. const TLocatedQueueItem * ParentItem, TParallelOperation * ParallelOperation) :
  2068. TLocatedQueueItem(*ParentItem),
  2069. FParallelOperation(ParallelOperation)
  2070. {
  2071. // deliberately not copying the ModifiedLocal and ModifiedRemote, not to trigger panel refresh, when sub-item completes
  2072. FInfo->Operation = ParentItem->FInfo->Operation;
  2073. FInfo->Side = ParentItem->FInfo->Side;
  2074. FInfo->Source = ParentItem->FInfo->Source;
  2075. FInfo->Destination = ParentItem->FInfo->Destination;
  2076. FInfo->SingleFile = DebugAlwaysFalse(ParentItem->FInfo->SingleFile);
  2077. FInfo->Primary = false;
  2078. FInfo->GroupToken = ParentItem->FInfo->GroupToken;
  2079. }
  2080. //---------------------------------------------------------------------------
  2081. void __fastcall TParallelTransferQueueItem::DoExecute(TTerminal * Terminal)
  2082. {
  2083. TLocatedQueueItem::DoExecute(Terminal);
  2084. Terminal->LogParallelTransfer(FParallelOperation);
  2085. TFileOperationProgressType OperationProgress(Terminal->OnProgress, Terminal->OnFinished, FParallelOperation->MainOperationProgress);
  2086. TFileOperation Operation = (FLAGSET(FParallelOperation->Params, cpDelete) ? foMove : foCopy);
  2087. bool Temp = FLAGSET(FParallelOperation->Params, cpTemporary);
  2088. OperationProgress.Start(
  2089. // CPS limit inherited from parent OperationProgress.
  2090. // Count not known and won't be needed as we will always have TotalSize as we always transfer a single file at a time.
  2091. Operation, FParallelOperation->Side, -1, Temp, FParallelOperation->TargetDir, 0);
  2092. try
  2093. {
  2094. bool Continue = true;
  2095. do
  2096. {
  2097. int GotNext = Terminal->CopyToParallel(FParallelOperation, &OperationProgress);
  2098. if (GotNext < 0)
  2099. {
  2100. Continue = false;
  2101. }
  2102. else if (!FQueue->ContinueParallelOperation())
  2103. {
  2104. Continue = false;
  2105. }
  2106. }
  2107. while (Continue);
  2108. }
  2109. __finally
  2110. {
  2111. OperationProgress.Stop();
  2112. FParallelOperation->RemoveClient();
  2113. }
  2114. }
  2115. //---------------------------------------------------------------------------
  2116. // TDownloadQueueItem
  2117. //---------------------------------------------------------------------------
  2118. __fastcall TDownloadQueueItem::TDownloadQueueItem(TTerminal * Terminal,
  2119. TStrings * FilesToCopy, const UnicodeString & TargetDir,
  2120. const TCopyParamType * CopyParam, int Params, bool SingleFile, bool Parallel) :
  2121. TTransferQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, osRemote, SingleFile, Parallel)
  2122. {
  2123. if (FilesToCopy->Count > 1)
  2124. {
  2125. if (!UnixExtractCommonPath(FilesToCopy, FInfo->Source))
  2126. {
  2127. FInfo->Source = Terminal->CurrentDirectory;
  2128. }
  2129. FInfo->Source = UnixExcludeTrailingBackslash(FInfo->Source);
  2130. FInfo->ModifiedRemote = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2131. UnixIncludeTrailingBackslash(FInfo->Source);
  2132. }
  2133. else
  2134. {
  2135. DebugAssert(FilesToCopy->Count > 0);
  2136. FInfo->Source = FilesToCopy->Strings[0];
  2137. if (UnixExtractFilePath(FInfo->Source).IsEmpty())
  2138. {
  2139. FInfo->Source = UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2140. FInfo->Source;
  2141. FInfo->ModifiedRemote = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2142. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory);
  2143. }
  2144. else
  2145. {
  2146. FInfo->ModifiedRemote = FLAGCLEAR(Params, cpDelete) ? UnicodeString() :
  2147. UnixExtractFilePath(FInfo->Source);
  2148. }
  2149. }
  2150. if (FLAGSET(Params, cpTemporary))
  2151. {
  2152. FInfo->Destination = L"";
  2153. }
  2154. else
  2155. {
  2156. FInfo->Destination =
  2157. IncludeTrailingBackslash(TargetDir) + CopyParam->FileMask;
  2158. }
  2159. FInfo->ModifiedLocal = IncludeTrailingBackslash(TargetDir);
  2160. }
  2161. //---------------------------------------------------------------------------
  2162. void __fastcall TDownloadQueueItem::DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  2163. {
  2164. Terminal->CopyToLocal(FFilesToCopy, FTargetDir, FCopyParam, FParams, ParallelOperation);
  2165. }
  2166. //---------------------------------------------------------------------------
  2167. // TTerminalThread
  2168. //---------------------------------------------------------------------------
  2169. __fastcall TTerminalThread::TTerminalThread(TTerminal * Terminal) :
  2170. TSignalThread(false), FTerminal(Terminal)
  2171. {
  2172. FAction = NULL;
  2173. FActionEvent = CreateEvent(NULL, false, false, NULL);
  2174. FException = NULL;
  2175. FIdleException = NULL;
  2176. FOnIdle = NULL;
  2177. FUserAction = NULL;
  2178. FCancel = false;
  2179. FAbandoned = false;
  2180. FAllowAbandon = false;
  2181. FMainThread = GetCurrentThreadId();
  2182. FSection = new TCriticalSection();
  2183. FOnInformation = FTerminal->OnInformation;
  2184. FOnQueryUser = FTerminal->OnQueryUser;
  2185. FOnPromptUser = FTerminal->OnPromptUser;
  2186. FOnShowExtendedException = FTerminal->OnShowExtendedException;
  2187. FOnDisplayBanner = FTerminal->OnDisplayBanner;
  2188. FOnChangeDirectory = FTerminal->OnChangeDirectory;
  2189. FOnReadDirectory = FTerminal->OnReadDirectory;
  2190. FOnStartReadDirectory = FTerminal->OnStartReadDirectory;
  2191. FOnReadDirectoryProgress = FTerminal->OnReadDirectoryProgress;
  2192. FOnInitializeLog = FTerminal->OnInitializeLog;
  2193. FTerminal->OnInformation = TerminalInformation;
  2194. FTerminal->OnQueryUser = TerminalQueryUser;
  2195. FTerminal->OnPromptUser = TerminalPromptUser;
  2196. FTerminal->OnShowExtendedException = TerminalShowExtendedException;
  2197. FTerminal->OnDisplayBanner = TerminalDisplayBanner;
  2198. FTerminal->OnChangeDirectory = TerminalChangeDirectory;
  2199. FTerminal->OnReadDirectory = TerminalReadDirectory;
  2200. FTerminal->OnStartReadDirectory = TerminalStartReadDirectory;
  2201. FTerminal->OnReadDirectoryProgress = TerminalReadDirectoryProgress;
  2202. FTerminal->OnInitializeLog = TerminalInitializeLog;
  2203. Start();
  2204. }
  2205. //---------------------------------------------------------------------------
  2206. __fastcall TTerminalThread::~TTerminalThread()
  2207. {
  2208. Close();
  2209. CloseHandle(FActionEvent);
  2210. DebugAssert(FTerminal->OnInformation == TerminalInformation);
  2211. DebugAssert(FTerminal->OnQueryUser == TerminalQueryUser);
  2212. DebugAssert(FTerminal->OnPromptUser == TerminalPromptUser);
  2213. DebugAssert(FTerminal->OnShowExtendedException == TerminalShowExtendedException);
  2214. DebugAssert(FTerminal->OnDisplayBanner == TerminalDisplayBanner);
  2215. DebugAssert(FTerminal->OnChangeDirectory == TerminalChangeDirectory);
  2216. DebugAssert(FTerminal->OnReadDirectory == TerminalReadDirectory);
  2217. DebugAssert(FTerminal->OnStartReadDirectory == TerminalStartReadDirectory);
  2218. DebugAssert(FTerminal->OnReadDirectoryProgress == TerminalReadDirectoryProgress);
  2219. DebugAssert(FTerminal->OnInitializeLog == TerminalInitializeLog);
  2220. FTerminal->OnInformation = FOnInformation;
  2221. FTerminal->OnQueryUser = FOnQueryUser;
  2222. FTerminal->OnPromptUser = FOnPromptUser;
  2223. FTerminal->OnShowExtendedException = FOnShowExtendedException;
  2224. FTerminal->OnDisplayBanner = FOnDisplayBanner;
  2225. FTerminal->OnChangeDirectory = FOnChangeDirectory;
  2226. FTerminal->OnReadDirectory = FOnReadDirectory;
  2227. FTerminal->OnStartReadDirectory = FOnStartReadDirectory;
  2228. FTerminal->OnReadDirectoryProgress = FOnReadDirectoryProgress;
  2229. FTerminal->OnInitializeLog = FOnInitializeLog;
  2230. delete FSection;
  2231. if (FAbandoned)
  2232. {
  2233. delete FTerminal;
  2234. }
  2235. }
  2236. //---------------------------------------------------------------------------
  2237. void __fastcall TTerminalThread::Cancel()
  2238. {
  2239. FCancel = true;
  2240. FCancelAfter = IncMilliSecond(Now(), 1000);
  2241. }
  2242. //---------------------------------------------------------------------------
  2243. void __fastcall TTerminalThread::Idle()
  2244. {
  2245. TGuard Guard(FSection);
  2246. // only when running user action already,
  2247. // so that the exception is caught, saved and actually
  2248. // passed back into the terminal thread, saved again
  2249. // and passed back to us
  2250. if ((FUserAction != NULL) && (FIdleException != NULL))
  2251. {
  2252. Rethrow(FIdleException);
  2253. }
  2254. FPendingIdle = true;
  2255. }
  2256. //---------------------------------------------------------------------------
  2257. void __fastcall TTerminalThread::TerminalOpen()
  2258. {
  2259. RunAction(TerminalOpenEvent);
  2260. }
  2261. //---------------------------------------------------------------------------
  2262. void __fastcall TTerminalThread::TerminalReopen()
  2263. {
  2264. RunAction(TerminalReopenEvent);
  2265. }
  2266. //---------------------------------------------------------------------------
  2267. void __fastcall TTerminalThread::RunAction(TNotifyEvent Action)
  2268. {
  2269. DebugAssert(FAction == NULL);
  2270. DebugAssert(FException == NULL);
  2271. DebugAssert(FIdleException == NULL);
  2272. DebugAssert(FOnIdle != NULL);
  2273. FCancelled = false;
  2274. FAction = Action;
  2275. try
  2276. {
  2277. try
  2278. {
  2279. TriggerEvent();
  2280. bool Done = false;
  2281. const unsigned int MaxWait = 50;
  2282. unsigned int Wait = MaxWait;
  2283. do
  2284. {
  2285. switch (WaitForSingleObject(FActionEvent, Wait))
  2286. {
  2287. case WAIT_OBJECT_0:
  2288. Done = true;
  2289. break;
  2290. case WAIT_TIMEOUT:
  2291. if (FUserAction != NULL)
  2292. {
  2293. try
  2294. {
  2295. FUserAction->Execute(NULL);
  2296. }
  2297. catch (Exception & E)
  2298. {
  2299. SaveException(E, FException);
  2300. }
  2301. FUserAction = NULL;
  2302. TriggerEvent();
  2303. Wait = 0;
  2304. }
  2305. else
  2306. {
  2307. if (FOnIdle != NULL)
  2308. {
  2309. FOnIdle(NULL);
  2310. }
  2311. Wait = std::min(Wait + 10, MaxWait);
  2312. }
  2313. break;
  2314. default:
  2315. throw Exception(L"Error waiting for background session task to complete");
  2316. }
  2317. if (AllowAbandon && !Done && FCancel && (Now() >= FCancelAfter))
  2318. {
  2319. TGuard Guard(FSection);
  2320. if (WaitForSingleObject(FActionEvent, 0) != WAIT_OBJECT_0)
  2321. {
  2322. FAbandoned = true;
  2323. FCancelled = true;
  2324. FatalAbort();
  2325. }
  2326. }
  2327. }
  2328. while (!Done);
  2329. if (Done)
  2330. {
  2331. Rethrow(FException);
  2332. }
  2333. }
  2334. __finally
  2335. {
  2336. FAction = NULL;
  2337. SAFE_DESTROY(FException);
  2338. }
  2339. }
  2340. catch(...)
  2341. {
  2342. if (FCancelled)
  2343. {
  2344. // even if the abort thrown as result of Cancel() was wrapped into
  2345. // some higher-level exception, normalize back to message-less fatal
  2346. // exception here
  2347. FatalAbort();
  2348. }
  2349. else
  2350. {
  2351. throw;
  2352. }
  2353. }
  2354. }
  2355. //---------------------------------------------------------------------------
  2356. void __fastcall TTerminalThread::TerminalOpenEvent(TObject * /*Sender*/)
  2357. {
  2358. FTerminal->Open();
  2359. }
  2360. //---------------------------------------------------------------------------
  2361. void __fastcall TTerminalThread::TerminalReopenEvent(TObject * /*Sender*/)
  2362. {
  2363. FTerminal->Reopen(0);
  2364. }
  2365. //---------------------------------------------------------------------------
  2366. void __fastcall TTerminalThread::ProcessEvent()
  2367. {
  2368. DebugAssert(FEvent != NULL);
  2369. DebugAssert(FException == NULL);
  2370. try
  2371. {
  2372. FAction(NULL);
  2373. }
  2374. catch(Exception & E)
  2375. {
  2376. SaveException(E, FException);
  2377. }
  2378. {
  2379. TGuard Guard(FSection);
  2380. if (!FAbandoned)
  2381. {
  2382. SetEvent(FActionEvent);
  2383. }
  2384. }
  2385. }
  2386. //---------------------------------------------------------------------------
  2387. void __fastcall TTerminalThread::Rethrow(Exception *& Exception)
  2388. {
  2389. if (Exception != NULL)
  2390. {
  2391. try
  2392. {
  2393. RethrowException(Exception);
  2394. }
  2395. __finally
  2396. {
  2397. SAFE_DESTROY(Exception);
  2398. }
  2399. }
  2400. }
  2401. //---------------------------------------------------------------------------
  2402. void __fastcall TTerminalThread::SaveException(Exception & E, Exception *& Exception)
  2403. {
  2404. DebugAssert(Exception == NULL);
  2405. Exception = CloneException(&E);
  2406. }
  2407. //---------------------------------------------------------------------------
  2408. void __fastcall TTerminalThread::FatalAbort()
  2409. {
  2410. if (FAbandoned)
  2411. {
  2412. // We cannot use TTerminal::FatalError as the terminal still runs on a backgroud thread,
  2413. // may have its TCallbackGuard armed right now.
  2414. throw ESshFatal(NULL, L"");
  2415. }
  2416. else
  2417. {
  2418. FTerminal->FatalAbort();
  2419. }
  2420. }
  2421. //---------------------------------------------------------------------------
  2422. void __fastcall TTerminalThread::CheckCancel()
  2423. {
  2424. if (FCancel && !FCancelled)
  2425. {
  2426. FCancelled = true;
  2427. FatalAbort();
  2428. }
  2429. }
  2430. //---------------------------------------------------------------------------
  2431. void __fastcall TTerminalThread::WaitForUserAction(TUserAction * UserAction)
  2432. {
  2433. DWORD Thread = GetCurrentThreadId();
  2434. // we can get called from the main thread from within Idle,
  2435. // should be only to call HandleExtendedException
  2436. if (Thread == FMainThread)
  2437. {
  2438. if (UserAction != NULL)
  2439. {
  2440. UserAction->Execute(NULL);
  2441. }
  2442. }
  2443. else
  2444. {
  2445. // we should be called from our thread only,
  2446. // with exception noted above
  2447. DebugAssert(Thread == FThreadId);
  2448. bool DoCheckCancel =
  2449. DebugAlwaysFalse(UserAction == NULL) || !UserAction->Force() || FAbandoned;
  2450. if (DoCheckCancel)
  2451. {
  2452. CheckCancel();
  2453. }
  2454. // have to save it as we can go recursive via TQueryParams::TimerEvent,
  2455. // see TTerminalThread::TerminalQueryUser
  2456. TUserAction * PrevUserAction = FUserAction;
  2457. try
  2458. {
  2459. FUserAction = UserAction;
  2460. while (true)
  2461. {
  2462. {
  2463. TGuard Guard(FSection);
  2464. // If idle exception is already set, we are only waiting
  2465. // for the main thread to pick it up
  2466. // (or at least to finish handling the user action, so
  2467. // that we rethrow the idle exception below)
  2468. // Also if idle exception is set, it is probable that terminal
  2469. // is not active anyway.
  2470. if (FTerminal->Active && FPendingIdle && (FIdleException == NULL))
  2471. {
  2472. FPendingIdle = false;
  2473. try
  2474. {
  2475. FTerminal->Idle();
  2476. }
  2477. catch (Exception & E)
  2478. {
  2479. SaveException(E, FIdleException);
  2480. }
  2481. }
  2482. }
  2483. int WaitResult = WaitForEvent(1000);
  2484. if (WaitResult == 0)
  2485. {
  2486. SAFE_DESTROY(FIdleException);
  2487. FatalAbort();
  2488. }
  2489. else if (WaitResult > 0)
  2490. {
  2491. break;
  2492. }
  2493. }
  2494. Rethrow(FException);
  2495. if (FIdleException != NULL)
  2496. {
  2497. // idle exception was not used to cancel the user action
  2498. // (if it where it would be already cloned into the FException above
  2499. // and rethrown)
  2500. Rethrow(FIdleException);
  2501. }
  2502. }
  2503. __finally
  2504. {
  2505. FUserAction = PrevUserAction;
  2506. SAFE_DESTROY(FException);
  2507. }
  2508. // Contrary to a call before, this is unconditional,
  2509. // otherwise cancelling authentication won't work,
  2510. // if it is tried only after the last user action
  2511. // (what is common, when cancelling while waiting for
  2512. // resolving of unresolvable host name, where the last user action is
  2513. // "resolving hostname" information action)
  2514. CheckCancel();
  2515. }
  2516. }
  2517. //---------------------------------------------------------------------------
  2518. void __fastcall TTerminalThread::TerminalInformation(
  2519. TTerminal * Terminal, const UnicodeString & Str, bool Status, int Phase)
  2520. {
  2521. TInformationUserAction Action(FOnInformation);
  2522. Action.Terminal = Terminal;
  2523. Action.Str = Str;
  2524. Action.Status = Status;
  2525. Action.Phase = Phase;
  2526. WaitForUserAction(&Action);
  2527. }
  2528. //---------------------------------------------------------------------------
  2529. void __fastcall TTerminalThread::TerminalQueryUser(TObject * Sender,
  2530. const UnicodeString Query, TStrings * MoreMessages, unsigned int Answers,
  2531. const TQueryParams * Params, unsigned int & Answer, TQueryType Type, void * Arg)
  2532. {
  2533. DebugUsedParam(Arg);
  2534. DebugAssert(Arg == NULL);
  2535. // note about TQueryParams::TimerEvent
  2536. // So far there is only one use for this, the TSecureShell::SendBuffer,
  2537. // which should be thread-safe, as long as the terminal thread,
  2538. // is stopped waiting for OnQueryUser to finish.
  2539. // note about TQueryButtonAlias::OnClick
  2540. // So far there is only one use for this, the TClipboardHandler,
  2541. // which is thread-safe.
  2542. TQueryUserAction Action(FOnQueryUser);
  2543. Action.Sender = Sender;
  2544. Action.Query = Query;
  2545. Action.MoreMessages = MoreMessages;
  2546. Action.Answers = Answers;
  2547. Action.Params = Params;
  2548. Action.Answer = Answer;
  2549. Action.Type = Type;
  2550. WaitForUserAction(&Action);
  2551. Answer = Action.Answer;
  2552. }
  2553. //---------------------------------------------------------------------------
  2554. void __fastcall TTerminalThread::TerminalInitializeLog(TObject * Sender)
  2555. {
  2556. if (FOnInitializeLog != NULL)
  2557. {
  2558. // never used, so not tested either
  2559. DebugFail();
  2560. TNotifyAction Action(FOnInitializeLog);
  2561. Action.Sender = Sender;
  2562. WaitForUserAction(&Action);
  2563. }
  2564. }
  2565. //---------------------------------------------------------------------------
  2566. void __fastcall TTerminalThread::TerminalPromptUser(TTerminal * Terminal,
  2567. TPromptKind Kind, UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  2568. TStrings * Results, bool & Result, void * Arg)
  2569. {
  2570. DebugUsedParam(Arg);
  2571. DebugAssert(Arg == NULL);
  2572. TPromptUserAction Action(FOnPromptUser);
  2573. Action.Terminal = Terminal;
  2574. Action.Kind = Kind;
  2575. Action.Name = Name;
  2576. Action.Instructions = Instructions;
  2577. Action.Prompts = Prompts;
  2578. Action.Results->AddStrings(Results);
  2579. WaitForUserAction(&Action);
  2580. Results->Clear();
  2581. Results->AddStrings(Action.Results);
  2582. Result = Action.Result;
  2583. }
  2584. //---------------------------------------------------------------------------
  2585. void __fastcall TTerminalThread::TerminalShowExtendedException(
  2586. TTerminal * Terminal, Exception * E, void * Arg)
  2587. {
  2588. DebugUsedParam(Arg);
  2589. DebugAssert(Arg == NULL);
  2590. TShowExtendedExceptionAction Action(FOnShowExtendedException);
  2591. Action.Terminal = Terminal;
  2592. Action.E = E;
  2593. WaitForUserAction(&Action);
  2594. }
  2595. //---------------------------------------------------------------------------
  2596. void __fastcall TTerminalThread::TerminalDisplayBanner(TTerminal * Terminal,
  2597. UnicodeString SessionName, const UnicodeString & Banner,
  2598. bool & NeverShowAgain, int Options, unsigned int & Params)
  2599. {
  2600. TDisplayBannerAction Action(FOnDisplayBanner);
  2601. Action.Terminal = Terminal;
  2602. Action.SessionName = SessionName;
  2603. Action.Banner = Banner;
  2604. Action.NeverShowAgain = NeverShowAgain;
  2605. Action.Options = Options;
  2606. Action.Params = Params;
  2607. WaitForUserAction(&Action);
  2608. NeverShowAgain = Action.NeverShowAgain;
  2609. Params = Action.Params;
  2610. }
  2611. //---------------------------------------------------------------------------
  2612. void __fastcall TTerminalThread::TerminalChangeDirectory(TObject * Sender)
  2613. {
  2614. TNotifyAction Action(FOnChangeDirectory);
  2615. Action.Sender = Sender;
  2616. WaitForUserAction(&Action);
  2617. }
  2618. //---------------------------------------------------------------------------
  2619. void __fastcall TTerminalThread::TerminalReadDirectory(TObject * Sender, Boolean ReloadOnly)
  2620. {
  2621. TReadDirectoryAction Action(FOnReadDirectory);
  2622. Action.Sender = Sender;
  2623. Action.ReloadOnly = ReloadOnly;
  2624. WaitForUserAction(&Action);
  2625. }
  2626. //---------------------------------------------------------------------------
  2627. void __fastcall TTerminalThread::TerminalStartReadDirectory(TObject * Sender)
  2628. {
  2629. TNotifyAction Action(FOnStartReadDirectory);
  2630. Action.Sender = Sender;
  2631. WaitForUserAction(&Action);
  2632. }
  2633. //---------------------------------------------------------------------------
  2634. void __fastcall TTerminalThread::TerminalReadDirectoryProgress(
  2635. TObject * Sender, int Progress, int ResolvedLinks, bool & Cancel)
  2636. {
  2637. TReadDirectoryProgressAction Action(FOnReadDirectoryProgress);
  2638. Action.Sender = Sender;
  2639. Action.Progress = Progress;
  2640. Action.ResolvedLinks = ResolvedLinks;
  2641. Action.Cancel = Cancel;
  2642. WaitForUserAction(&Action);
  2643. Cancel = Action.Cancel;
  2644. }
  2645. //---------------------------------------------------------------------------
  2646. bool __fastcall TTerminalThread::Release()
  2647. {
  2648. bool Result = !FAbandoned;
  2649. if (Result)
  2650. {
  2651. delete this;
  2652. }
  2653. return Result;
  2654. }
  2655. //---------------------------------------------------------------------------
  2656. bool __fastcall TTerminalThread::Finished()
  2657. {
  2658. return TSimpleThread::Finished() || FAbandoned;
  2659. }