Queue.cpp 70 KB

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