Queue.cpp 87 KB

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