Queue.cpp 85 KB

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