1
0

Queue.cpp 86 KB

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