Queue.cpp 85 KB

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