1
0

Queue.cpp 89 KB

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