CustomScpExplorer.cpp 389 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <Common.h>
  6. #include "CustomScpExplorer.h"
  7. #include <algorithm>
  8. #include <Bookmarks.h>
  9. #include <Interface.h>
  10. #include <Exceptions.h>
  11. #include <CoreMain.h>
  12. #include <FileSystems.h>
  13. #include <TextsCore.h>
  14. #include <TextsWin.h>
  15. #include <HelpWin.h>
  16. #include <VCLCommon.h>
  17. #include <Progress.h>
  18. #include <SynchronizeProgress.h>
  19. #include <DragExt.h>
  20. #include <WinApi.h>
  21. #include "GUITools.h"
  22. #include "NonVisual.h"
  23. #include "Glyphs.h"
  24. #include "Tools.h"
  25. #include "WinConfiguration.h"
  26. #include "TerminalManager.h"
  27. #include "EditorManager.h"
  28. #include "ProgParams.h"
  29. #include "Setup.h"
  30. #include <Consts.hpp>
  31. #include <DateUtils.hpp>
  32. #include <TB2Common.hpp>
  33. #include <DirectoryMonitor.hpp>
  34. #include <System.IOUtils.hpp>
  35. //---------------------------------------------------------------------------
  36. #pragma package(smart_init)
  37. #pragma link "CustomDirView"
  38. #pragma link "CustomUnixDirView"
  39. #pragma link "IEListView"
  40. #pragma link "NortonLikeListView"
  41. #pragma link "UnixDirView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "UnixDriveView"
  44. #pragma link "CustomDriveView"
  45. #pragma link "TB2Dock"
  46. #pragma link "TBXStatusBars"
  47. #pragma link "TB2Item"
  48. #pragma link "TB2Toolbar"
  49. #pragma link "ThemePageControl"
  50. #pragma link "PathLabel"
  51. #pragma resource "*.dfm"
  52. //---------------------------------------------------------------------------
  53. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  54. static const int SessionPanelCount = 3;
  55. //---------------------------------------------------------------------------
  56. class TMutexGuard
  57. {
  58. public:
  59. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  60. int Timeout = 5000)
  61. {
  62. FMutex = NULL;
  63. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  64. if (WaitResult == WAIT_TIMEOUT)
  65. {
  66. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  67. }
  68. else
  69. {
  70. FMutex = AMutex;
  71. }
  72. }
  73. ~TMutexGuard()
  74. {
  75. if (FMutex != NULL)
  76. {
  77. ReleaseMutex(FMutex);
  78. }
  79. }
  80. private:
  81. HANDLE FMutex;
  82. };
  83. //---------------------------------------------------------------------------
  84. class TWindowLock
  85. {
  86. public:
  87. TWindowLock(TCustomScpExplorerForm * Form) :
  88. FForm(Form)
  89. {
  90. FForm->LockWindow();
  91. }
  92. ~TWindowLock()
  93. {
  94. FForm->UnlockWindow();
  95. }
  96. private:
  97. TCustomScpExplorerForm * FForm;
  98. };
  99. //---------------------------------------------------------------------------
  100. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  101. FForm(Form)
  102. {
  103. FForm->BatchStart(FBatchStorage);
  104. }
  105. //---------------------------------------------------------------------------
  106. TAutoBatch::~TAutoBatch()
  107. {
  108. FForm->BatchEnd(FBatchStorage);
  109. }
  110. //---------------------------------------------------------------------------
  111. struct TTransferOperationParam
  112. {
  113. TTransferOperationParam();
  114. UnicodeString TargetDirectory;
  115. bool Temp;
  116. bool DragDrop;
  117. int Options;
  118. TAutoSwitch Queue;
  119. };
  120. //---------------------------------------------------------------------------
  121. TTransferOperationParam::TTransferOperationParam()
  122. {
  123. Temp = false;
  124. DragDrop = false;
  125. Options = 0;
  126. Queue = asAuto;
  127. }
  128. //---------------------------------------------------------------------------
  129. class TTransferPresetNoteData : public TObject
  130. {
  131. public:
  132. UnicodeString Message;
  133. };
  134. //---------------------------------------------------------------------------
  135. class TTerminalNoteData : public TObject
  136. {
  137. public:
  138. TManagedTerminal * Terminal;
  139. };
  140. //---------------------------------------------------------------------------
  141. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  142. FFormRestored(false),
  143. TForm(Owner)
  144. {
  145. AddStartupSequence(L"F");
  146. FInvalid = false;
  147. FCurrentSide = osRemote;
  148. FEverShown = false;
  149. FDocks = new TList();
  150. InitControls();
  151. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  152. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  153. NonVisualDataModule->ScpExplorer = this;
  154. RestoreParams();
  155. ConfigurationChanged();
  156. RemoteDirView->Invalidate();
  157. FAutoOperation = false;
  158. FOnFileOperationFinished = NULL;
  159. FPrimaryOperation = foNone;
  160. FForceExecution = false;
  161. FIgnoreNextDialogChar = 0;
  162. FErrorList = NULL;
  163. FSynchronizeProgressForm = NULL;
  164. FProgressForm = NULL;
  165. FRefreshLocalDirectory = false;
  166. FRefreshRemoteDirectory = false;
  167. FDDExtMapFile = NULL;
  168. // CreateMutexW keeps failing with ERROR_NOACCESS
  169. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  170. DebugAssert(FDDExtMutex != NULL);
  171. FDDTargetControl = NULL;
  172. FDelayedDeletionTimer = NULL;
  173. FDelayedDeletionList = new TStringList();
  174. FDDFileList = NULL;
  175. FPendingTempSpaceWarn = false;
  176. FCapturedLog = NULL;
  177. FDragDropOperation = false;
  178. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  179. FAllowTransferPresetAutoSelect = true;
  180. FSessionChanging = false;
  181. FCopyParamDefault = L"";
  182. FSynchronizeController = NULL;
  183. FPendingQueueActionItem = NULL;
  184. FLockLevel = 0;
  185. FLockSuspendLevel = 0;
  186. FDisabledOnLockSuspend = false;
  187. FAlternativeDelete = false;
  188. FTrayIcon = new ::TTrayIcon(0);
  189. FTrayIcon->OnClick = TrayIconClick;
  190. FMaxQueueLength = 0;
  191. FLastContextPopupScreenPoint = TPoint(-1, -1);
  192. FTransferResumeList = NULL;
  193. FDeletedFiles = NULL;
  194. FMoveToQueue = false;
  195. StandaloneOperation = false;
  196. FOnFeedSynchronizeError = NULL;
  197. FOnSynchronizeAbort = NULL;
  198. FSynchronizeTerminal = NULL;
  199. FNeedSession = false;
  200. FDoNotIdleCurrentTerminal = 0;
  201. FIncrementalSearching = 0;
  202. FIncrementalSearchHaveNext = false;
  203. FQueueFileList.reset(new TQueueFileList());
  204. FProgressSide = osCurrent;
  205. FCalculateSizeOperation = NULL;
  206. FDownloadingFromClipboard = false;
  207. FClipboardFakeMonitorsPendingReset = false;
  208. FEditorManager = new TEditorManager();
  209. FEditorManager->OnFileChange = ExecutedFileChanged;
  210. FEditorManager->OnFileReload = ExecutedFileReload;
  211. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  212. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  213. FLocalEditors = new TList();
  214. FQueueStatus = NULL;
  215. FQueueStatusSection = new TCriticalSection();
  216. FQueueStatusInvalidated = false;
  217. FQueueItemInvalidated = false;
  218. FQueueStatusUpdating = false;
  219. FQueueActedItem = NULL;
  220. FQueueController = new TQueueController(QueueView3);
  221. FUserActionTimer = new TTimer(this);
  222. FUserActionTimer->Enabled = false;
  223. FUserActionTimer->Interval = 10;
  224. FUserActionTimer->OnTimer = UserActionTimer;
  225. FNotes = new TStringList();
  226. FNoteTimer = new TTimer(this);
  227. FNoteTimer->Enabled = false;
  228. FNoteTimer->OnTimer = NoteTimer;
  229. FOnNoteClick = NULL;
  230. FOle32Library = LoadLibrary(L"Ole32.dll");
  231. FDragMoveCursor = FOle32Library != NULL ?
  232. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  233. UseSystemSettings(this);
  234. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  235. static_cast<TObject*>(GetComponent(fcTransferList)));
  236. DebugAssert(TransferList != NULL);
  237. FTransferListHoverIndex = -1;
  238. TransferList->OnChange = TransferListChange;
  239. TransferList->OnDrawItem = TransferListDrawItem;
  240. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  241. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  242. UseDesktopFont(SessionsPageControl);
  243. UpdateSessionsPageControlHeight();
  244. UseDesktopFont(RemoteDirView);
  245. UseDesktopFont(RemoteDriveView);
  246. UseDesktopFont(QueueView3);
  247. UseDesktopFont(QueueFileList);
  248. UseDesktopFont(QueueLabel);
  249. UseDesktopFont(RemoteStatusBar);
  250. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  251. QueueSplitter->ShowHint = true;
  252. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  253. QueueFileListSplitter->ShowHint = true;
  254. RemotePanelSplitter->ShowHint = true;
  255. UpdateImages();
  256. FCustomCommandMenu = CreateTBXPopupMenu(this);
  257. FCustomCommandLocalFileList = NULL;
  258. FCustomCommandRemoteFileList = NULL;
  259. FSessionColors = new TPngImageList(this);
  260. FSessionColors->ColorDepth = cd32Bit;
  261. AddFixedSessionImages();
  262. SessionsPageControl->Images = FSessionColors;
  263. UpdateQueueLabel();
  264. CheckStoreTransition();
  265. CreateHiddenWindow();
  266. StartUpdates();
  267. }
  268. //---------------------------------------------------------------------------
  269. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  270. {
  271. FInvalid = true;
  272. // this has to be one of the very first things to do
  273. StopUpdateThread();
  274. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  275. TTerminalManager::Instance()->ScpExplorer = NULL;
  276. delete FCustomCommandLocalFileList;
  277. delete FCustomCommandRemoteFileList;
  278. delete FCustomCommandMenu;
  279. delete FTrayIcon;
  280. FTrayIcon = NULL;
  281. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  282. delete FEditorManager;
  283. ForceCloseLocalEditors();
  284. delete FLocalEditors;
  285. HideFileFindDialog();
  286. if (FDelayedDeletionTimer)
  287. {
  288. DoDelayedDeletion(NULL);
  289. SAFE_DESTROY(FDelayedDeletionTimer);
  290. }
  291. SAFE_DESTROY(FDelayedDeletionList);
  292. // sometimes we do not get DDEnd so the list is not released
  293. SAFE_DESTROY(FDDFileList);
  294. DebugAssert(FSynchronizeController == NULL);
  295. CloseHandle(FDDExtMutex);
  296. FDDExtMutex = NULL;
  297. FreeLibrary(FOle32Library);
  298. FOle32Library = NULL;
  299. FDragMoveCursor = NULL;
  300. DebugAssert(!FErrorList);
  301. if (FEverShown)
  302. {
  303. // when window is never shown (like when running command-line operation),
  304. // particularly window site is not restored correctly (BoundsRect value set
  305. // in RestoreForm gets lost during handle allocation), so we do not want
  306. // it to be stored
  307. StoreParams();
  308. }
  309. ManagedSession = NULL;
  310. Queue = NULL;
  311. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  312. NonVisualDataModule->ScpExplorer = NULL;
  313. delete FQueueController;
  314. FQueueController = NULL;
  315. delete FQueueStatusSection;
  316. FQueueStatusSection = NULL;
  317. delete FQueueStatus;
  318. FQueueStatus = NULL;
  319. delete FUserActionTimer;
  320. FUserActionTimer = NULL;
  321. delete FNoteTimer;
  322. delete FNotes;
  323. delete FNoteData;
  324. SAFE_DESTROY(FDocks);
  325. SessionsPageControl->Images = NULL;
  326. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  327. SAFE_DESTROY(FSessionColors);
  328. SAFE_DESTROY(FSessionsDragDropFilesEx);
  329. SAFE_DESTROY(FHistoryMenu[0][0]);
  330. SAFE_DESTROY(FHistoryMenu[0][1]);
  331. SAFE_DESTROY(FHistoryMenu[1][0]);
  332. SAFE_DESTROY(FHistoryMenu[1][1]);
  333. if (FHiddenWindow != NULL)
  334. {
  335. DestroyWindow(FHiddenWindow);
  336. FHiddenWindow = NULL;
  337. }
  338. }
  339. //---------------------------------------------------------------------------
  340. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  341. {
  342. std::unique_ptr<TSessionData> Data;
  343. if (!Session.IsEmpty())
  344. {
  345. bool DefaultsOnly;
  346. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  347. }
  348. TTerminalManager * Manager = TTerminalManager::Instance();
  349. for (int Index = 0; Index < Manager->Count; Index++)
  350. {
  351. TTerminal * Terminal = Manager->Sessions[Index];
  352. if (Session.IsEmpty() ||
  353. Manager->IsActiveTerminalForSite(Terminal, Data.get()))
  354. {
  355. if (Path.IsEmpty())
  356. {
  357. Terminal->ClearCaches();
  358. }
  359. else
  360. {
  361. Terminal->DirectoryModified(Path, true);
  362. }
  363. }
  364. }
  365. // We should flag a pending refresh for the background terminals or busy foreground terminals
  366. if (HasActiveTerminal() &&
  367. CanCommandLineFromAnotherInstance() &&
  368. (Session.IsEmpty() || Manager->IsActiveTerminalForSite(Terminal, Data.get())) &&
  369. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  370. {
  371. Terminal->ReloadDirectory();
  372. }
  373. }
  374. //---------------------------------------------------------------------------
  375. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  376. {
  377. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  378. size_t MessageSize = sizeof(TCopyDataMessage);
  379. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  380. if (Result)
  381. {
  382. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  383. Result = (Message.Version == TCopyDataMessage::Version1);
  384. if (Result)
  385. {
  386. switch (Message.Command)
  387. {
  388. case TCopyDataMessage::CommandCanCommandLine:
  389. Result = CanCommandLineFromAnotherInstance();
  390. break;
  391. case TCopyDataMessage::CommandCommandLine:
  392. {
  393. UnicodeString CommandLine(Message.CommandLine);
  394. Result = CommandLineFromAnotherInstance(CommandLine);
  395. }
  396. break;
  397. case TCopyDataMessage::RefreshPanel:
  398. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  399. break;
  400. case TCopyDataMessage::MainWindowCheck:
  401. Result = true;
  402. break;
  403. default:
  404. Result = false;
  405. break;
  406. }
  407. }
  408. }
  409. Message.Result = Result ? 1 : 0;
  410. }
  411. //---------------------------------------------------------------------------
  412. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  413. {
  414. WNDCLASS WindowClass = {0};
  415. WindowClass.lpfnWndProc = DefWindowProc;
  416. WindowClass.hInstance = HInstance;
  417. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  418. FHiddenWindow = NULL;
  419. if (RegisterClass(&WindowClass))
  420. {
  421. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  422. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  423. }
  424. }
  425. //---------------------------------------------------------------------------
  426. bool __fastcall TCustomScpExplorerForm::CanConsole()
  427. {
  428. return
  429. HasActiveTerminal() &&
  430. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  431. }
  432. //---------------------------------------------------------------------------
  433. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  434. {
  435. bool Result = Visible && !NonVisualDataModule->Busy;
  436. return Result;
  437. }
  438. //---------------------------------------------------------------------------
  439. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  440. const UnicodeString & CommandLine)
  441. {
  442. TProgramParams Params(CommandLine);
  443. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  444. if (Result)
  445. {
  446. NonVisualDataModule->StartBusy();
  447. try
  448. {
  449. // this action is initiated from another process,
  450. // so it's likely that our window is not visible,
  451. // and user won't see what is going on
  452. Application->BringToFront();
  453. // reload sessions as we may be asked to open a session
  454. // just stored by another instance
  455. StoredSessions->Reload();
  456. UnicodeString SessionName = Params.Param[1];
  457. std::unique_ptr<TObjectList> DataList(new TObjectList());
  458. try
  459. {
  460. UnicodeString DownloadFile; // unused
  461. int Flags = GetCommandLineParseUrlFlags(&Params);
  462. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  463. }
  464. catch (EAbort &)
  465. {
  466. // Happens when opening session in PuTTY and in other situations,
  467. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  468. // to process the command-line on its own (or to pass it to yet another instance)
  469. }
  470. if (DataList->Count > 0)
  471. {
  472. TTerminalManager * Manager = TTerminalManager::Instance();
  473. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  474. }
  475. }
  476. __finally
  477. {
  478. NonVisualDataModule->EndBusy();
  479. }
  480. }
  481. return Result;
  482. }
  483. //---------------------------------------------------------------------------
  484. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  485. {
  486. TManagedTerminal * Result;
  487. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  488. {
  489. Result = FManagedSession;
  490. }
  491. else
  492. {
  493. Result = NULL;
  494. }
  495. return Result;
  496. }
  497. //---------------------------------------------------------------------------
  498. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  499. {
  500. if (FManagedSession != value)
  501. {
  502. SessionChanging();
  503. DoSetManagedSession(value, false);
  504. }
  505. }
  506. //---------------------------------------------------------------------------
  507. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  508. {
  509. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  510. FManagedSession = value;
  511. {
  512. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect);
  513. FAllowTransferPresetAutoSelect = false;
  514. TAutoFlag SessionChangingFlag(FSessionChanging);
  515. SessionChanged(Replace);
  516. }
  517. if (Terminal != NULL)
  518. {
  519. TransferPresetAutoSelect();
  520. }
  521. // Update app and tab titles, prevented above by FSessionChanging.
  522. UpdateControls();
  523. }
  524. //---------------------------------------------------------------------------
  525. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  526. {
  527. DoSetManagedSession(value, true);
  528. }
  529. //---------------------------------------------------------------------------
  530. void __fastcall TCustomScpExplorerForm::SessionChanging()
  531. {
  532. if (ManagedSession != NULL)
  533. {
  534. UpdateSession(ManagedSession);
  535. }
  536. }
  537. //---------------------------------------------------------------------------
  538. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  539. {
  540. if (ManagedSession != NULL)
  541. {
  542. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  543. }
  544. if (!TTerminalManager::Instance()->Updating)
  545. {
  546. SessionListChanged();
  547. }
  548. if (Terminal != NULL)
  549. {
  550. TObject * State = NULL;
  551. if (WinConfiguration->PreservePanelState)
  552. {
  553. State = Terminal->RemoteExplorerState;
  554. DirView(osRemote)->AnnounceState(State);
  555. }
  556. try
  557. {
  558. if (Replaced)
  559. {
  560. RemoteDirView->ReplaceTerminal(Terminal);
  561. }
  562. else
  563. {
  564. RemoteDirView->Terminal = Terminal;
  565. }
  566. if (Terminal->Active)
  567. {
  568. Terminal->RefreshDirectory();
  569. }
  570. if (State != NULL)
  571. {
  572. DirView(osRemote)->RestoreState(State);
  573. }
  574. }
  575. __finally
  576. {
  577. DirView(osRemote)->AnnounceState(NULL);
  578. }
  579. }
  580. else
  581. {
  582. RemoteDirView->Terminal = NULL;
  583. }
  584. InitStatusBar();
  585. UpdateTransferList();
  586. // Update panels Enable state before refreshing the labels
  587. UpdateControls();
  588. }
  589. //---------------------------------------------------------------------------
  590. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  591. {
  592. if (Queue != value)
  593. {
  594. if (FQueue != NULL)
  595. {
  596. FQueue->OnListUpdate = NULL;
  597. FQueue->OnQueueItemUpdate = NULL;
  598. }
  599. FQueue = value;
  600. if (FQueue != NULL)
  601. {
  602. DebugAssert(FQueue->OnListUpdate == NULL);
  603. FQueue->OnListUpdate = QueueListUpdate;
  604. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  605. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  606. }
  607. QueueChanged();
  608. }
  609. }
  610. //---------------------------------------------------------------------------
  611. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  612. TListItem * Item)
  613. {
  614. if (FQueueActedItem == Item)
  615. {
  616. FQueueActedItem = NULL;
  617. if ((QueueView3->PopupMenu != NULL) &&
  618. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  619. {
  620. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  621. ReleaseCapture();
  622. }
  623. }
  624. if (Item->Data == FPendingQueueActionItem)
  625. {
  626. FPendingQueueActionItem = NULL;
  627. }
  628. }
  629. //---------------------------------------------------------------------------
  630. bool TCustomScpExplorerForm::IsAnythingQueued()
  631. {
  632. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  633. }
  634. //---------------------------------------------------------------------------
  635. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  636. {
  637. {
  638. TGuard Guard(FQueueStatusSection);
  639. FQueueStatusInvalidated = false;
  640. if (FQueue != NULL)
  641. {
  642. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  643. }
  644. }
  645. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  646. {
  647. FMaxQueueLength = FQueueStatus->Count;
  648. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  649. }
  650. {
  651. TAutoFlag Flag(FQueueStatusUpdating);
  652. FQueueController->UpdateQueueStatus(FQueueStatus);
  653. }
  654. UpdateQueueFileList();
  655. SetQueueProgress();
  656. UpdateQueueView();
  657. bool IsEmpty = !IsAnythingQueued();
  658. if (IsEmpty && (Terminal != NULL))
  659. {
  660. TOnceDoneOperation OnceDoneOperation =
  661. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  662. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  663. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  664. {
  665. FQueue->Enabled = false;
  666. }
  667. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  668. {
  669. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  670. }
  671. }
  672. }
  673. //---------------------------------------------------------------------------
  674. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  675. {
  676. UnicodeString Result;
  677. if (FQueueStatus != NULL)
  678. {
  679. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  680. {
  681. TFileOperationProgressType * ProgressData =
  682. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  683. if ((ProgressData != NULL) && ProgressData->InProgress)
  684. {
  685. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  686. }
  687. }
  688. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  689. {
  690. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  691. }
  692. }
  693. return Result;
  694. }
  695. //---------------------------------------------------------------------------
  696. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  697. {
  698. ComponentVisible[fcQueueView] =
  699. !IsLocalBrowserMode() &&
  700. ((WinConfiguration->QueueView.Show == qvShow) ||
  701. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  702. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  703. }
  704. //---------------------------------------------------------------------------
  705. void __fastcall TCustomScpExplorerForm::QueueChanged()
  706. {
  707. if (FQueueStatus != NULL)
  708. {
  709. // UpdateFileList implementation relies on the status being recreated when session changes
  710. delete FQueueStatus;
  711. FQueueStatus = NULL;
  712. }
  713. UpdateQueueStatus(true);
  714. }
  715. //---------------------------------------------------------------------------
  716. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  717. {
  718. if (FQueue == Queue)
  719. {
  720. FQueueStatusInvalidated = true;
  721. }
  722. }
  723. //---------------------------------------------------------------------------
  724. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  725. TQueueItem * Item)
  726. {
  727. if (FQueue == Queue)
  728. {
  729. TGuard Guard(FQueueStatusSection);
  730. // this may be running in parallel with QueueChanged
  731. if (FQueueStatus != NULL)
  732. {
  733. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  734. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  735. {
  736. FRefreshLocalDirectory = (QueueItem == NULL) ||
  737. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  738. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  739. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  740. }
  741. if (QueueItem != NULL)
  742. {
  743. QueueItem->UserData = (void*)true;
  744. FQueueItemInvalidated = true;
  745. }
  746. }
  747. }
  748. }
  749. //---------------------------------------------------------------------------
  750. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  751. {
  752. // during standalone editing, we have no way to see/control queue,
  753. // so we have to always popup prompts automatically
  754. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  755. }
  756. //---------------------------------------------------------------------------
  757. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  758. {
  759. if (FQueueStatus != NULL)
  760. {
  761. bool QueueAutoPopup = IsQueueAutoPopup();
  762. bool NeedRefresh = FQueueController->NeedRefresh();
  763. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  764. FQueueItemInvalidated = false;
  765. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  766. bool Updated = false;
  767. TQueueItemProxy * QueueItem;
  768. bool WasUserAction;
  769. for (int Index = 0; Index < Limit; Index++)
  770. {
  771. bool Update = false;
  772. QueueItem = FQueueStatus->Items[Index];
  773. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  774. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  775. (FPendingQueueActionItem == NULL))
  776. {
  777. FPendingQueueActionItem = QueueItem;
  778. FUserActionTimer->Enabled = true;
  779. }
  780. if ((bool)QueueItem->UserData)
  781. {
  782. QueueItem->UserData = (void*)false;
  783. QueueItem->Update();
  784. Updated = true;
  785. Update = true;
  786. }
  787. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  788. {
  789. Update = true;
  790. }
  791. if (Update)
  792. {
  793. FQueueController->RefreshQueueItem(QueueItem);
  794. }
  795. }
  796. if (Updated)
  797. {
  798. NonVisualDataModule->UpdateNonVisibleActions();
  799. SetQueueProgress();
  800. UpdateQueueFileList();
  801. }
  802. }
  803. }
  804. //---------------------------------------------------------------------------
  805. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  806. {
  807. if (FTaskbarList != NULL)
  808. {
  809. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  810. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  811. }
  812. }
  813. //---------------------------------------------------------------------------
  814. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  815. {
  816. if (Progress >= 0)
  817. {
  818. if (FTaskbarList != NULL)
  819. {
  820. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  821. }
  822. }
  823. else
  824. {
  825. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  826. }
  827. }
  828. //---------------------------------------------------------------------------
  829. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  830. {
  831. int OverallProgress;
  832. // FProgressForm is null when this is called from SetQueueProgress
  833. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  834. {
  835. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  836. }
  837. else if (!ProgressData->IsIndeterminate())
  838. {
  839. OverallProgress = ProgressData->OverallProgress();
  840. }
  841. else
  842. {
  843. OverallProgress = -1;
  844. }
  845. SetTaskbarListProgressValue(OverallProgress);
  846. }
  847. //---------------------------------------------------------------------------
  848. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  849. {
  850. TTerminalManager::Instance()->QueueStatusUpdated();
  851. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  852. {
  853. // Do not animate task bar button, when items are queued, but processing is disabled
  854. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  855. {
  856. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  857. {
  858. TFileOperationProgressType * ProgressData = NULL;
  859. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  860. {
  861. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  862. }
  863. if ((ProgressData != NULL) &&
  864. ProgressData->InProgress)
  865. {
  866. SetTaskbarListProgressValue(ProgressData);
  867. }
  868. else
  869. {
  870. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  871. }
  872. }
  873. else
  874. {
  875. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  876. }
  877. }
  878. else
  879. {
  880. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  881. }
  882. }
  883. UpdateQueueLabel();
  884. }
  885. //---------------------------------------------------------------------------
  886. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  887. {
  888. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  889. if (FQueueStatus != NULL)
  890. {
  891. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  892. if (ActiveAndPendingPrimaryCount > 0)
  893. {
  894. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  895. }
  896. }
  897. QueueLabel->Caption = Caption;
  898. }
  899. //---------------------------------------------------------------------------
  900. void TCustomScpExplorerForm::CheckStoreTransition()
  901. {
  902. if (WinConfiguration->StoreTransition == stInit)
  903. {
  904. if (IsUWP())
  905. {
  906. WinConfiguration->StoreTransition = stStoreFresh;
  907. AppLog(L"Fresh UWP/store installation");
  908. }
  909. else
  910. {
  911. WinConfiguration->StoreTransition = stStandard;
  912. AppLog(L"Fresh standard installation");
  913. }
  914. }
  915. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  916. {
  917. WinConfiguration->StoreTransition = stStoreMigrated;
  918. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  919. AppLog(L"Standard installation migrated to store installation");
  920. }
  921. if (WinConfiguration->StoreTransition == stStoreMigrated)
  922. {
  923. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  924. Toolbar->Parent = MessageDock;
  925. Toolbar->FullSize = true;
  926. Toolbar->Color = Application->HintColor;
  927. TTBXLabelItem * LabelItem;
  928. LabelItem = new TTBXLabelItem(Toolbar);
  929. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  930. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  931. Toolbar->Items->Add(LabelItem);
  932. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  933. LinkItem->FontSettings->Color = LinkColor;
  934. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  935. LinkItem->OnClick = StoreTransitionLinkClick;
  936. Toolbar->Items->Add(LinkItem);
  937. AddMenuSeparator(Toolbar->Items);
  938. TTBCustomItem * CloseItem = new TTBXItem(Toolbar);
  939. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  940. CloseItem->OnClick = StoreTransitionCloseClick;
  941. Toolbar->Items->Add(CloseItem);
  942. GiveTBItemPriority(CloseItem);
  943. }
  944. }
  945. //---------------------------------------------------------------------------
  946. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  947. {
  948. ShowHelp(HELP_STORE_TRANSITION);
  949. }
  950. //---------------------------------------------------------------------------
  951. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  952. {
  953. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  954. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  955. delete Toolbar;
  956. WinConfiguration->StoreTransition = stStoreAcknowledged;
  957. UpdateControls();
  958. }
  959. //---------------------------------------------------------------------------
  960. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  961. {
  962. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  963. static_cast<TComponent*>(GetComponent(fcTransferList)));
  964. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  965. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  966. TransferList->Strings->BeginUpdate();
  967. try
  968. {
  969. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  970. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  971. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  972. if (FTransferDropDownHint.IsEmpty())
  973. {
  974. FTransferDropDownHint = TransferDropDown->Hint;
  975. }
  976. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  977. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  978. TransferDropDown->Text = StripHotkey(Name);
  979. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  980. (FTransferDropDownHint, StripHotkey(Name),
  981. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  982. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  983. // update the label, otherwise when it is updated only on the first draw
  984. // of the list, it is drawn "bold" for some reason
  985. FTransferListHoverIndex = TransferList->ItemIndex;
  986. UpdateTransferLabel();
  987. }
  988. __finally
  989. {
  990. TransferList->Strings->EndUpdate();
  991. }
  992. }
  993. //---------------------------------------------------------------------------
  994. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  995. {
  996. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  997. DebugAssert(Toolbar != NULL);
  998. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  999. }
  1000. //---------------------------------------------------------------------------
  1001. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1002. {
  1003. TForm::UpdateActions();
  1004. if (ComponentVisible[fcCustomCommandsBand])
  1005. {
  1006. UpdateCustomCommandsToolbar();
  1007. }
  1008. }
  1009. //---------------------------------------------------------------------------
  1010. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1011. {
  1012. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1013. }
  1014. //---------------------------------------------------------------------------
  1015. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1016. {
  1017. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1018. {
  1019. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1020. // Without this, the panel turns gray and unused part of header turns black
  1021. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1022. }
  1023. }
  1024. //---------------------------------------------------------------------------
  1025. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1026. {
  1027. Color = GetBtnFaceColor();
  1028. DebugAssert(Configuration && RemoteDirView);
  1029. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1030. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1031. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1032. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1033. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1034. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1035. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1036. UpdateRowSelect(RemoteDirView);
  1037. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1038. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1039. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1040. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1041. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1042. UpdateSessionsPageControlHeight();
  1043. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1044. UpdateToolbarDisplayMode();
  1045. UpdateTransferList();
  1046. if (Terminal != NULL)
  1047. {
  1048. TransferPresetAutoSelect();
  1049. }
  1050. UpdateQueueView();
  1051. UpdateControls();
  1052. // this can be called even before constuctor finishes.
  1053. if (FEditorManager != NULL)
  1054. {
  1055. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1056. }
  1057. // this can be called even before constuctor finishes.
  1058. if (FLocalEditors != NULL)
  1059. {
  1060. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1061. {
  1062. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1063. }
  1064. }
  1065. if (ComponentVisible[fcCustomCommandsBand])
  1066. {
  1067. UpdateCustomCommandsToolbar();
  1068. }
  1069. // show only when keeping queue items forever,
  1070. // otherwise, it's enough to have it in the context menu
  1071. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1072. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1073. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1074. {
  1075. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1076. FFileColorsCurrent = WinConfiguration->FileColors;
  1077. FileColorsChanged();
  1078. }
  1079. }
  1080. //---------------------------------------------------------------------------
  1081. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1082. {
  1083. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1084. DirView->Invalidate();
  1085. }
  1086. //---------------------------------------------------------------------------
  1087. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1088. {
  1089. DoFileColorsChanged(RemoteDirView);
  1090. }
  1091. //---------------------------------------------------------------------------
  1092. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1093. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1094. void * /*Arg*/)
  1095. {
  1096. if (Token != NULL)
  1097. {
  1098. TForm * Editor = dynamic_cast<TForm*>(Token);
  1099. DebugAssert(Editor != NULL);
  1100. ReconfigureEditorForm(Editor);
  1101. }
  1102. }
  1103. //---------------------------------------------------------------------------
  1104. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1105. {
  1106. WinConfiguration->DDTransferConfirmation = asOn;
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1110. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1111. {
  1112. // noop
  1113. }
  1114. //---------------------------------------------------------------------------
  1115. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1116. {
  1117. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1121. {
  1122. if (DoNotShowAgain)
  1123. {
  1124. if (DragDrop)
  1125. {
  1126. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1127. {
  1128. PopupTrayBalloon(
  1129. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1130. }
  1131. WinConfiguration->DDTransferConfirmation = asOff;
  1132. }
  1133. else
  1134. {
  1135. WinConfiguration->ConfirmTransferring = false;
  1136. }
  1137. }
  1138. else
  1139. {
  1140. // User explicitly unchecked "do not show again",
  1141. // so show him the dialog the next time
  1142. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1143. {
  1144. WinConfiguration->DDTransferConfirmation = asOn;
  1145. }
  1146. }
  1147. }
  1148. //---------------------------------------------------------------------------
  1149. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1150. TTransferDirection Direction, TTransferType Type, bool Temp,
  1151. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1152. bool Confirm, bool DragDrop, int Options)
  1153. {
  1154. bool Result = true;
  1155. DebugAssert(HasActiveTerminal());
  1156. // these parameters are known in advance
  1157. int Params =
  1158. FLAGMASK(Type == ttMove, cpDelete);
  1159. bool ToTemp = (Temp && (Direction == tdToLocal));
  1160. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1161. {
  1162. bool DisableNewerOnly =
  1163. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1164. ToTemp;
  1165. Options |=
  1166. FLAGMASK(ToTemp, coTemp) |
  1167. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1168. coDoNotShowAgain;
  1169. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1170. int CopyParamAttrs = (Direction == tdToRemote ?
  1171. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1172. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1173. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1174. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1175. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1176. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1177. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1178. if (Result)
  1179. {
  1180. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1181. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1182. }
  1183. }
  1184. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1185. {
  1186. Configuration->Usage->Inc(L"TransfersOnBackground");
  1187. // these parameter are known only after transfer dialog
  1188. Params |=
  1189. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1190. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1191. Result = false;
  1192. ClearTransferSourceSelection(Direction);
  1193. }
  1194. return Result;
  1195. }
  1196. //---------------------------------------------------------------------------
  1197. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1198. {
  1199. if (FOnFileOperationFinished != NULL)
  1200. {
  1201. FOnFileOperationFinished(Side, UnicodeString(), true);
  1202. }
  1203. else
  1204. {
  1205. if (HasDirView[Side])
  1206. {
  1207. DirView(Side)->SelectAll(smNone);
  1208. }
  1209. }
  1210. }
  1211. //---------------------------------------------------------------------------
  1212. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1213. {
  1214. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1215. ClearOperationSelection(Side);
  1216. }
  1217. //---------------------------------------------------------------------------
  1218. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1219. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1220. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1221. int Params)
  1222. {
  1223. DebugAssert(Queue != NULL);
  1224. bool SingleFile = false;
  1225. if (FileList->Count == 1)
  1226. {
  1227. if (Direction == tdToRemote)
  1228. {
  1229. UnicodeString FileName = FileList->Strings[0];
  1230. SingleFile = FileExists(ApiPath(FileName));
  1231. }
  1232. else
  1233. {
  1234. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1235. SingleFile = !File->IsDirectory;
  1236. }
  1237. }
  1238. TQueueItem * QueueItem;
  1239. if (Direction == tdToRemote)
  1240. {
  1241. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1242. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1243. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1244. }
  1245. else
  1246. {
  1247. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1248. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1249. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1250. }
  1251. AddQueueItem(Queue, QueueItem, Terminal);
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1255. {
  1256. if (Queue->IsEmpty)
  1257. {
  1258. Terminal->QueueOperationStart = Now();
  1259. }
  1260. Queue->AddItem(QueueItem);
  1261. }
  1262. //---------------------------------------------------------------------------
  1263. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1264. {
  1265. }
  1266. //---------------------------------------------------------------------------
  1267. void __fastcall TCustomScpExplorerForm::InitControls()
  1268. {
  1269. DebugAssert(FDocks != NULL);
  1270. for (int Index = 0; Index < ComponentCount; Index++)
  1271. {
  1272. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1273. if ((Dock != NULL) && (Dock->Tag == 0))
  1274. {
  1275. FDocks->Add(Dock);
  1276. }
  1277. }
  1278. CollectItemsWithTextDisplayMode(this);
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1282. {
  1283. ConfigurationChanged();
  1284. QueuePanel->Height =
  1285. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1286. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1287. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1288. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1289. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1290. QueueFileList->Height =
  1291. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1292. if (QueueFileList->Visible)
  1293. {
  1294. AdjustQueueLayout();
  1295. }
  1296. UpdateCustomCommandsToolbar();
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. void __fastcall TCustomScpExplorerForm::StoreParams()
  1300. {
  1301. int APixelsPerInch = GetControlPixelsPerInch(this);
  1302. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1303. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1304. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1305. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1306. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1307. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1308. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1309. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1313. {
  1314. if (!FFormRestored)
  1315. {
  1316. FFormRestored = true;
  1317. RestoreFormParams();
  1318. }
  1319. TForm::CreateParams(Params);
  1320. }
  1321. //---------------------------------------------------------------------------
  1322. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1323. {
  1324. DebugAssert(FDocks != NULL);
  1325. for (int Index = 0; Index < FDocks->Count; Index++)
  1326. {
  1327. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1328. }
  1329. }
  1330. //---------------------------------------------------------------------------
  1331. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1332. {
  1333. SetDockAllowDrag(true);
  1334. while (!ButtonsStr.IsEmpty())
  1335. {
  1336. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1337. UnicodeString Name = CutToChar(S, L'=', true);
  1338. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1339. {
  1340. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1341. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1342. {
  1343. while (!S.IsEmpty())
  1344. {
  1345. UnicodeString S2 = CutToChar(S, L',', true);
  1346. UnicodeString Name = CutToChar(S2, L':', true);
  1347. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1348. {
  1349. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1350. if (SameText(GetToolbarItemName(Item), Name))
  1351. {
  1352. // forward compatibility
  1353. UnicodeString S3 = CutToChar(S2, L':', true);
  1354. bool Visible = StrToIntDef(S3, 0);
  1355. Item->Visible = Visible;
  1356. }
  1357. }
  1358. }
  1359. }
  1360. }
  1361. }
  1362. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1363. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1367. {
  1368. UnicodeString Result;
  1369. SetDockAllowDrag(true);
  1370. Result = ::GetToolbarsLayoutStr(this);
  1371. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1372. return Result;
  1373. }
  1374. //---------------------------------------------------------------------------
  1375. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1376. {
  1377. UnicodeString Result;
  1378. if (Item->Action != NULL)
  1379. {
  1380. Result = Item->Action->Name;
  1381. Result = RemoveSuffix(Result, L"Action", true);
  1382. }
  1383. else
  1384. {
  1385. Result = Item->Name;
  1386. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1387. Result = RemoveSuffix(Result, L"Item", true);
  1388. }
  1389. return Result;
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1393. {
  1394. UnicodeString Result;
  1395. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1396. {
  1397. UnicodeString ToolbarStr;
  1398. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1399. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1400. {
  1401. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1402. {
  1403. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1404. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1405. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1406. // and save the changes here only.
  1407. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1408. {
  1409. UnicodeString Name = GetToolbarItemName(Item);
  1410. DebugAssert(Name.Pos(L"TBX") == 0);
  1411. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1412. }
  1413. }
  1414. }
  1415. if (!ToolbarStr.IsEmpty())
  1416. {
  1417. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1418. }
  1419. }
  1420. return Result;
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1424. {
  1425. DebugAssert(FProgressForm == NULL);
  1426. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1427. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1428. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1429. FProgressForm->DeleteLocalToRecycleBin =
  1430. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1431. FProgressForm->DeleteRemoteToRecycleBin =
  1432. HasActiveTerminal() &&
  1433. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1434. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1435. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1436. LockWindow();
  1437. // Actually, do not know what hides the progress once the operation finishes
  1438. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1439. SetTaskbarListProgressState(TBPF_NORMAL);
  1440. }
  1441. //---------------------------------------------------------------------------
  1442. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1443. {
  1444. SAFE_DESTROY(FProgressForm);
  1445. UnlockWindow();
  1446. SetQueueProgress();
  1447. }
  1448. //---------------------------------------------------------------------------
  1449. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1450. TFileOperationProgressType & ProgressData)
  1451. {
  1452. // Download to temporary local directory
  1453. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1454. {
  1455. bool Continue = true;
  1456. FPendingTempSpaceWarn = false;
  1457. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1458. if (!Continue)
  1459. {
  1460. Abort();
  1461. }
  1462. }
  1463. // operation is being executed and we still didn't show up progress form
  1464. if (ProgressData.InProgress && !FProgressForm)
  1465. {
  1466. CreateProgressForm(NULL);
  1467. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1468. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1469. }
  1470. // operation is finished (or terminated), so we hide progress form
  1471. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1472. {
  1473. DestroyProgressForm();
  1474. if (ProgressData.Operation == foCalculateSize)
  1475. {
  1476. // When calculating size before transfer, the abort caused by
  1477. // cancel flag set due to "MoveToQueue" below,
  1478. // is not propagated back to us in ExecuteFileOperation,
  1479. // as it is silently swallowed.
  1480. // So we explicitly (re)throw it here.
  1481. if (FMoveToQueue)
  1482. {
  1483. Abort();
  1484. }
  1485. }
  1486. else
  1487. {
  1488. if ((ProgressData.Cancel == csContinue) &&
  1489. !FAutoOperation)
  1490. {
  1491. OperationComplete(ProgressData.StartTime);
  1492. }
  1493. }
  1494. }
  1495. if (FProgressForm &&
  1496. // Can happen only during synchronization, when ending one of the operations
  1497. ProgressData.InProgress)
  1498. {
  1499. FProgressForm->SetProgressData(ProgressData);
  1500. DebugAssert(ProgressData.InProgress);
  1501. SetTaskbarListProgressValue(&ProgressData);
  1502. if (FProgressForm->Cancel > csContinue)
  1503. {
  1504. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1505. if (FProgressForm->Cancel == csCancelFile)
  1506. {
  1507. FProgressForm->ClearCancel();
  1508. }
  1509. // cancel cancels even the move
  1510. FMoveToQueue = false;
  1511. }
  1512. else if (FProgressForm->MoveToQueue)
  1513. {
  1514. FMoveToQueue = true;
  1515. ProgressData.SetCancelAtLeast(csCancel);
  1516. }
  1517. if ((FTransferResumeList != NULL) &&
  1518. ProgressData.InProgress &&
  1519. ProgressData.IsTransfer() &&
  1520. !ProgressData.FullFileName.IsEmpty())
  1521. {
  1522. if ((FTransferResumeList->Count == 0) ||
  1523. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1524. {
  1525. // note that we do not recognize directories from files here
  1526. FTransferResumeList->Add(ProgressData.FullFileName);
  1527. }
  1528. }
  1529. }
  1530. }
  1531. //---------------------------------------------------------------------------
  1532. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1533. const TDateTime & StartTime)
  1534. {
  1535. if (GUIConfiguration->BeepOnFinish &&
  1536. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1537. {
  1538. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1539. DWORD Sound;
  1540. if (!ExtractFileExt(BeepSound).IsEmpty())
  1541. {
  1542. Sound = SND_FILENAME;
  1543. }
  1544. else
  1545. {
  1546. Sound = SND_ALIAS;
  1547. }
  1548. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1549. }
  1550. }
  1551. //---------------------------------------------------------------------------
  1552. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1553. TFileOperationProgressType & ProgressData)
  1554. {
  1555. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1556. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1557. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1558. FileOperationProgress(ProgressData);
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1562. {
  1563. UnicodeString Result;
  1564. if (FProgressForm != NULL)
  1565. {
  1566. Result = FProgressForm->ProgressStr();
  1567. }
  1568. return Result;
  1569. }
  1570. //---------------------------------------------------------------------------
  1571. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1572. bool DragDrop)
  1573. {
  1574. return (!DragDrop && (DropSourceControl == NULL)) ||
  1575. (DropSourceControl == DirView(osOther));
  1576. }
  1577. //---------------------------------------------------------------------------
  1578. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1579. {
  1580. TCustomDirView * ADirView = DirView(Side);
  1581. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1582. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1583. // this can happen when local drive is unplugged in the middle of the operation
  1584. if (Item != NULL)
  1585. {
  1586. if (Unselect)
  1587. {
  1588. Item->Selected = false;
  1589. }
  1590. ADirView->MakeProgressVisible(Item);
  1591. }
  1592. return Item;
  1593. }
  1594. //---------------------------------------------------------------------------
  1595. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1596. TFileOperation Operation, TOperationSide Side,
  1597. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1598. TOnceDoneOperation & OnceDoneOperation)
  1599. {
  1600. if (!FAutoOperation)
  1601. {
  1602. // no selection on "/upload", form serves only as event handler
  1603. // (it is not displayed)
  1604. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1605. ((Operation == FPrimaryOperation) ||
  1606. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1607. {
  1608. TOperationSide DViewSide;
  1609. if ((FProgressSide != osCurrent) &&
  1610. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1611. {
  1612. // assume the operation is over the focused panel
  1613. DViewSide = FProgressSide;
  1614. }
  1615. else
  1616. {
  1617. DViewSide = Side;
  1618. }
  1619. if (FOnFileOperationFinished != NULL)
  1620. {
  1621. FOnFileOperationFinished(DViewSide, FileName, Success);
  1622. }
  1623. else
  1624. {
  1625. VisualiseOperationFinished(DViewSide, FileName, Success);
  1626. }
  1627. }
  1628. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1629. {
  1630. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1631. {
  1632. if (Side == osLocal)
  1633. {
  1634. Configuration->Usage->Inc(L"UploadedFiles");
  1635. }
  1636. else
  1637. {
  1638. Configuration->Usage->Inc(L"DownloadedFiles");
  1639. }
  1640. }
  1641. }
  1642. }
  1643. if (Success && (FSynchronizeController != NULL))
  1644. {
  1645. DebugAssert(!IsSideLocalBrowser(osRemote));
  1646. if (Operation == foCopy)
  1647. {
  1648. DebugAssert(Side == osLocal);
  1649. FSynchronizeController->LogOperation(soUpload, FileName);
  1650. }
  1651. else if (Operation == foDelete)
  1652. {
  1653. DebugAssert(Side == osRemote);
  1654. FSynchronizeController->LogOperation(soDelete, FileName);
  1655. }
  1656. }
  1657. if (FProgressForm)
  1658. {
  1659. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1660. }
  1661. }
  1662. //---------------------------------------------------------------------------
  1663. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1664. TFileOperation Operation, TOperationSide Side,
  1665. bool Temp, const UnicodeString & FileName, Boolean Success,
  1666. TOnceDoneOperation & OnceDoneOperation)
  1667. {
  1668. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1669. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1670. OnceDoneOperation);
  1671. }
  1672. //---------------------------------------------------------------------------
  1673. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1674. {
  1675. return false;
  1676. }
  1677. //---------------------------------------------------------------------------
  1678. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1679. {
  1680. return false;
  1681. }
  1682. //---------------------------------------------------------------------------
  1683. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1684. {
  1685. return false;
  1686. }
  1687. //---------------------------------------------------------------------------
  1688. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1689. {
  1690. return NULL;
  1691. }
  1692. //---------------------------------------------------------------------------
  1693. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1694. {
  1695. DebugAssert(GetSide(Side) == osRemote);
  1696. DebugUsedParam(Side);
  1697. return RemoteDirView;
  1698. }
  1699. //---------------------------------------------------------------------------
  1700. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1701. {
  1702. DebugAssert(GetSide(Side) == osRemote);
  1703. DebugUsedParam(Side);
  1704. return RemoteDriveView;
  1705. }
  1706. //---------------------------------------------------------------------------
  1707. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1708. {
  1709. DebugAssert(GetSide(Side) == osRemote);
  1710. DebugUsedParam(Side);
  1711. return HasActiveTerminal();
  1712. }
  1713. //---------------------------------------------------------------------------
  1714. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1715. TOperationSide Side, int FilesOnly)
  1716. {
  1717. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1721. TOperationSide Side, int FilesOnly)
  1722. {
  1723. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1724. }
  1725. //---------------------------------------------------------------------------
  1726. struct THistoryItemData
  1727. {
  1728. short int Side;
  1729. short int Index;
  1730. };
  1731. //---------------------------------------------------------------------------
  1732. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1733. {
  1734. DirView(Side)->HistoryGo(Index);
  1735. }
  1736. //---------------------------------------------------------------------------
  1737. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1738. {
  1739. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1740. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1741. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1742. }
  1743. //---------------------------------------------------------------------------
  1744. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1745. bool Back)
  1746. {
  1747. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1748. {
  1749. TCustomDirView * DView = DirView(Side);
  1750. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1751. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1752. if (ICount > 10)
  1753. {
  1754. ICount = 10;
  1755. }
  1756. Menu->Items->Clear();
  1757. THistoryItemData Data;
  1758. Data.Side = Side;
  1759. for (short int i = 1; i <= ICount; i++)
  1760. {
  1761. TTBCustomItem * Item = new TTBXItem(Menu);
  1762. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1763. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1764. Item->Hint = DView->HistoryPath[Data.Index];
  1765. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1766. Item->Tag = *reinterpret_cast<int*>(&Data);
  1767. Item->OnClick = HistoryItemClick;
  1768. Menu->Items->Add(Item);
  1769. }
  1770. }
  1771. }
  1772. //---------------------------------------------------------------------------
  1773. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1774. TOperationSide Side, bool Back)
  1775. {
  1776. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1777. {
  1778. // workaround
  1779. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1780. // operator new allocates memory in Pascal code, but calls inline
  1781. // contructor in C++, leading in problems, the function does
  1782. // both in Pascal code
  1783. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1784. UpdateHistoryMenu(Side, Back);
  1785. }
  1786. return FHistoryMenu[Side == osLocal][Back];
  1787. }
  1788. //---------------------------------------------------------------------------
  1789. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1790. TCustomDirView *Sender)
  1791. {
  1792. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1793. UpdateHistoryMenu(Side, true);
  1794. UpdateHistoryMenu(Side, false);
  1795. }
  1796. //---------------------------------------------------------------------------
  1797. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1798. {
  1799. // remote custom commands can be executed only if the server supports shell commands
  1800. // or have secondary shell
  1801. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1802. }
  1803. //---------------------------------------------------------------------------
  1804. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1805. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1806. {
  1807. // -1 = hidden, 0 = disabled, 1 = enabled
  1808. int Result;
  1809. TFileCustomCommand RemoteCustomCommand;
  1810. TLocalCustomCommand LocalCustomCommand;
  1811. TFileCustomCommand * NonInteractiveCustomCommand =
  1812. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1813. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1814. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1815. if (FLAGCLEAR(Command.Params, ccLocal))
  1816. {
  1817. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1818. // custom command that does not operate with files can be executed anytime ...
  1819. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1820. {
  1821. // ... but do not show such command in remote file menu
  1822. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1823. {
  1824. Result = AllowedState;
  1825. }
  1826. else
  1827. {
  1828. Result = -1;
  1829. }
  1830. }
  1831. else
  1832. {
  1833. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1834. {
  1835. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1836. }
  1837. else
  1838. {
  1839. Result = -1;
  1840. }
  1841. }
  1842. }
  1843. else
  1844. {
  1845. // custom command that does not operate with files can be executed anytime
  1846. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1847. {
  1848. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1849. }
  1850. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1851. {
  1852. if ((ListType == ccltAll) || (ListType == ccltFile))
  1853. {
  1854. // special case is "diff"-style command that can be executed over any side,
  1855. // if we have both sides
  1856. Result =
  1857. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1858. // directly (instead of EnableSelectedOperation) to pass
  1859. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1860. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1861. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1862. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1863. }
  1864. else if (ListType == ccltBoth)
  1865. {
  1866. DebugAssert(!IsLocalBrowserMode());
  1867. Result = 1;
  1868. }
  1869. else
  1870. {
  1871. Result = -1;
  1872. }
  1873. }
  1874. else
  1875. {
  1876. if ((ListType == ccltAll) ||
  1877. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1878. {
  1879. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1880. }
  1881. else
  1882. {
  1883. Result = -1;
  1884. }
  1885. }
  1886. if ((Result > 0) &&
  1887. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1888. !HasActiveTerminal())
  1889. {
  1890. Result = 0;
  1891. }
  1892. }
  1893. return Result;
  1894. }
  1895. //---------------------------------------------------------------------------
  1896. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1897. TStrings * FileList, const TCustomCommandType & ACommand,
  1898. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1899. {
  1900. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1901. {
  1902. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1903. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1904. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1905. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1906. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1907. bool Capture =
  1908. FLAGSET(ACommand.Params, ccShowResults) ||
  1909. FLAGSET(ACommand.Params, ccCopyResults) ||
  1910. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1911. TCaptureOutputEvent OutputEvent = NULL;
  1912. DebugAssert(FCapturedLog == NULL);
  1913. if (Capture)
  1914. {
  1915. FCapturedLog = new TStringList();
  1916. OutputEvent = TerminalCaptureLog;
  1917. }
  1918. try
  1919. {
  1920. if (!RemoteCustomCommand.IsFileCommand(Command))
  1921. {
  1922. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1923. OutputEvent);
  1924. }
  1925. else
  1926. {
  1927. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1928. }
  1929. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1930. {
  1931. if (FLAGSET(ACommand.Params, ccCopyResults))
  1932. {
  1933. CopyToClipboard(FCapturedLog);
  1934. }
  1935. if (FLAGSET(ACommand.Params, ccShowResults))
  1936. {
  1937. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1938. }
  1939. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1940. {
  1941. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1942. }
  1943. }
  1944. }
  1945. __finally
  1946. {
  1947. SAFE_DESTROY(FCapturedLog);
  1948. }
  1949. }
  1950. }
  1951. //---------------------------------------------------------------------------
  1952. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1953. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1954. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1955. {
  1956. DebugAssert(!IsLocalBrowserMode());
  1957. TStrings * LocalFileList = NULL;
  1958. TStrings * RemoteFileList = NULL;
  1959. TStrings * RemoteFileListFull = NULL;
  1960. try
  1961. {
  1962. if (LocalFileCommand)
  1963. {
  1964. if (ALocalFileList == NULL)
  1965. {
  1966. DebugAssert(HasDirView[osLocal]);
  1967. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1968. // directly (instead of EnableSelectedOperation) to pass
  1969. // false to FocusedFileOnlyWhenFocused
  1970. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1971. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1972. }
  1973. else
  1974. {
  1975. LocalFileList = ALocalFileList;
  1976. }
  1977. if (FileListCommand)
  1978. {
  1979. if (LocalFileList->Count != 1)
  1980. {
  1981. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  1982. }
  1983. }
  1984. else
  1985. {
  1986. if ((LocalFileList->Count != 1) &&
  1987. (FileList->Count != 1) &&
  1988. (LocalFileList->Count != FileList->Count))
  1989. {
  1990. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  1991. }
  1992. }
  1993. }
  1994. UnicodeString RootTempDir;
  1995. UnicodeString TempDir;
  1996. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  1997. if (!RemoteFiles)
  1998. {
  1999. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true);
  2000. }
  2001. try
  2002. {
  2003. TDateTimes RemoteFileTimes;
  2004. if (RemoteFiles)
  2005. {
  2006. RemoteFileList = FileList;
  2007. }
  2008. else
  2009. {
  2010. RemoteFileList = new TStringList();
  2011. TMakeLocalFileListParams MakeFileListParam;
  2012. MakeFileListParam.FileList = RemoteFileList;
  2013. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2014. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2015. MakeFileListParam.Recursive =
  2016. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2017. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2018. if (!MakeFileListParam.Recursive)
  2019. {
  2020. RemoteFileTimes.clear();
  2021. RemoteFileListFull = new TStringList();
  2022. MakeFileListParam.FileList = RemoteFileListFull;
  2023. MakeFileListParam.Recursive = true;
  2024. MakeFileListParam.IncludeDirs = false;
  2025. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2026. }
  2027. else
  2028. {
  2029. RemoteFileListFull = RemoteFileList;
  2030. }
  2031. }
  2032. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2033. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2034. if (!NonBlocking)
  2035. {
  2036. int Count;
  2037. if (FileListCommand)
  2038. {
  2039. Count = 1;
  2040. }
  2041. else if (LocalFileCommand)
  2042. {
  2043. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2044. }
  2045. else
  2046. {
  2047. Count = RemoteFileList->Count;
  2048. }
  2049. Progress.Start(foCustomCommand, osRemote, Count);
  2050. DebugAssert(FProgressForm != NULL);
  2051. FProgressForm->ReadOnly = true;
  2052. }
  2053. try
  2054. {
  2055. if (FileListCommand)
  2056. {
  2057. UnicodeString LocalFile;
  2058. // MakeFileList does not delimit filenames
  2059. UnicodeString FileList = MakeFileList(RemoteFileList);
  2060. if (LocalFileCommand)
  2061. {
  2062. DebugAssert(LocalFileList->Count == 1);
  2063. LocalFile = LocalFileList->Strings[0];
  2064. }
  2065. TLocalCustomCommand CustomCommand(Data,
  2066. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2067. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2068. if (NonBlocking)
  2069. {
  2070. DebugAssert(!POutput);
  2071. ExecuteShellChecked(ShellCommand);
  2072. }
  2073. else
  2074. {
  2075. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2076. }
  2077. }
  2078. else if (LocalFileCommand)
  2079. {
  2080. if (LocalFileList->Count == 1)
  2081. {
  2082. UnicodeString LocalFile = LocalFileList->Strings[0];
  2083. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2084. {
  2085. UnicodeString FileName = RemoteFileList->Strings[Index];
  2086. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2087. Progress.SetFile(FileNameForProgress);
  2088. TLocalCustomCommand CustomCommand(Data,
  2089. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2090. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2091. TOnceDoneOperation OnceDoneOperation;
  2092. // Do not unselect anything, as it won't work with two panels anyway
  2093. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2094. }
  2095. }
  2096. else if (RemoteFileList->Count == 1)
  2097. {
  2098. UnicodeString FileName = RemoteFileList->Strings[0];
  2099. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2100. {
  2101. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2102. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2103. Progress.SetFile(LocalFileNameOnly);
  2104. TLocalCustomCommand CustomCommand(
  2105. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2106. FileName, LocalFileName, L"");
  2107. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2108. TOnceDoneOperation OnceDoneOperation;
  2109. // Do not unselect anything, as it won't work with two panels anyway
  2110. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2111. }
  2112. }
  2113. else
  2114. {
  2115. if (LocalFileList->Count != RemoteFileList->Count)
  2116. {
  2117. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2118. }
  2119. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2120. {
  2121. UnicodeString FileName = RemoteFileList->Strings[Index];
  2122. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2123. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2124. Progress.SetFile(LocalFileNameOnly); // sic
  2125. TLocalCustomCommand CustomCommand(
  2126. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2127. FileName, LocalFileName, L"");
  2128. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2129. TOnceDoneOperation OnceDoneOperation;
  2130. // Do not unselect anything, as it won't work with two panels anyway
  2131. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2132. }
  2133. }
  2134. }
  2135. else
  2136. {
  2137. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2138. {
  2139. UnicodeString FileName = RemoteFileList->Strings[Index];
  2140. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2141. Progress.SetFile(FileNameForProgress);
  2142. TLocalCustomCommand CustomCommand(Data,
  2143. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2144. FileName, L"", L"");
  2145. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2146. TOnceDoneOperation OnceDoneOperation;
  2147. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2148. }
  2149. }
  2150. }
  2151. __finally
  2152. {
  2153. if (!NonBlocking)
  2154. {
  2155. Progress.Stop();
  2156. }
  2157. }
  2158. DebugAssert(!FAutoOperation);
  2159. if (!RemoteFiles)
  2160. {
  2161. TempDir = IncludeTrailingBackslash(TempDir);
  2162. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2163. {
  2164. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2165. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2166. // Skip directories, process only nested files.
  2167. // The check is redundant as FileAge fails for directories anyway.
  2168. !DirectoryExists(FileName))
  2169. {
  2170. UnicodeString RemoteDir =
  2171. UnixExtractFileDir(
  2172. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2173. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2174. TDateTime NewTime;
  2175. if (FileAge(FileName, NewTime) &&
  2176. (NewTime != RemoteFileTimes[Index]))
  2177. {
  2178. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2179. TemporaryFileCopyParam(CopyParam);
  2180. CopyParam.FileMask = L"";
  2181. FAutoOperation = true;
  2182. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2183. TemporaryFilesList->Add(FileName);
  2184. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2185. }
  2186. }
  2187. }
  2188. }
  2189. }
  2190. __finally
  2191. {
  2192. FAutoOperation = false;
  2193. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2194. {
  2195. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  2196. }
  2197. }
  2198. }
  2199. __finally
  2200. {
  2201. if (RemoteFileList != FileList)
  2202. {
  2203. delete RemoteFileList;
  2204. }
  2205. if (LocalFileList != ALocalFileList)
  2206. {
  2207. delete LocalFileList;
  2208. }
  2209. if (RemoteFileListFull != RemoteFileList)
  2210. {
  2211. delete RemoteFileListFull;
  2212. }
  2213. }
  2214. }
  2215. //---------------------------------------------------------------------------
  2216. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2217. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2218. bool FileListCommand, UnicodeString * POutput)
  2219. {
  2220. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2221. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2222. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2223. {
  2224. UnicodeString FileName = SelectedFileList->Strings[Index];
  2225. if (DirectoryExists(FileName))
  2226. {
  2227. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2228. {
  2229. LocalFileList->Add(FileName);
  2230. }
  2231. if (FLAGSET(ACommand.Params, ccRecursive))
  2232. {
  2233. TMakeLocalFileListParams MakeFileListParam;
  2234. MakeFileListParam.FileList = LocalFileList.get();
  2235. MakeFileListParam.FileTimes = NULL;
  2236. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2237. MakeFileListParam.Recursive = true;
  2238. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2239. }
  2240. }
  2241. else
  2242. {
  2243. LocalFileList->Add(FileName);
  2244. }
  2245. }
  2246. UnicodeString RemotePath;
  2247. if (Terminal != NULL)
  2248. {
  2249. RemotePath = Terminal->CurrentDirectory;
  2250. }
  2251. if (FileListCommand)
  2252. {
  2253. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2254. TLocalCustomCommand CustomCommand(
  2255. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2256. L"", L"", FileList);
  2257. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2258. }
  2259. else
  2260. {
  2261. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2262. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2263. DebugAssert(FProgressForm != NULL);
  2264. FProgressForm->ReadOnly = true;
  2265. try
  2266. {
  2267. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2268. {
  2269. UnicodeString FileName = LocalFileList->Strings[Index];
  2270. Progress.SetFile(FileName);
  2271. TLocalCustomCommand CustomCommand(
  2272. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2273. FileName, L"", L"");
  2274. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2275. TOnceDoneOperation OnceDoneOperation;
  2276. Progress.Finish(FileName, true, OnceDoneOperation);
  2277. }
  2278. }
  2279. __finally
  2280. {
  2281. Progress.Stop();
  2282. }
  2283. }
  2284. }
  2285. //---------------------------------------------------------------------------
  2286. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2287. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2288. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2289. {
  2290. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2291. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2292. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2293. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2294. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2295. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2296. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2297. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2298. std::unique_ptr<UnicodeString> POutput;
  2299. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2300. FLAGSET(ACommand.Params, ccCopyResults))
  2301. {
  2302. POutput.reset(new UnicodeString());
  2303. }
  2304. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  2305. FProgressSide = FCurrentSide;
  2306. if (!LocalCustomCommand.IsFileCommand(Command))
  2307. {
  2308. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2309. }
  2310. // remote files?
  2311. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2312. {
  2313. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2314. }
  2315. // local files
  2316. else
  2317. {
  2318. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2319. }
  2320. if (POutput.get() != NULL)
  2321. {
  2322. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2323. int P = POutput->Pos(sLineBreak);
  2324. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2325. {
  2326. POutput->SetLength(P - 1);
  2327. }
  2328. // Copy even empty output to clipboard
  2329. if (FLAGSET(ACommand.Params, ccCopyResults))
  2330. {
  2331. CopyToClipboard(*POutput);
  2332. }
  2333. // But do not show an empty message box.
  2334. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2335. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2336. !POutput->IsEmpty())
  2337. {
  2338. TClipboardHandler ClipboardHandler;
  2339. ClipboardHandler.Text = *POutput;
  2340. TMessageParams Params;
  2341. TQueryButtonAlias Aliases[1];
  2342. Aliases[0].Button = qaRetry;
  2343. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2344. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2345. Params.Aliases = Aliases;
  2346. Params.AliasesCount = LENOF(Aliases);
  2347. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2348. }
  2349. }
  2350. }
  2351. //---------------------------------------------------------------------------
  2352. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2353. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2354. {
  2355. TCustomCommandData Data;
  2356. UnicodeString Site;
  2357. UnicodeString RemotePath;
  2358. if (HasActiveTerminal())
  2359. {
  2360. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2361. Data = TCustomCommandData(SessionData.get());
  2362. Site = Terminal->SessionData->SessionKey;
  2363. RemotePath = Terminal->CurrentDirectory;
  2364. }
  2365. UnicodeString HelpKeyword = ACommand.HomePage;
  2366. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2367. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2368. {
  2369. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2370. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2371. {
  2372. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2373. }
  2374. else
  2375. {
  2376. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2377. }
  2378. if (!DoCustomCommandOptionsDialog(
  2379. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2380. {
  2381. Abort();
  2382. }
  2383. }
  2384. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2385. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2386. {
  2387. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2388. }
  2389. else
  2390. {
  2391. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2392. }
  2393. }
  2394. //---------------------------------------------------------------------------
  2395. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2396. const TCustomCommandType & Command)
  2397. {
  2398. DebugAssert(FCustomCommandLocalFileList != NULL);
  2399. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2400. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2401. TStrings * LocalFileList = new TStringList();
  2402. TStrings * RemoteFileList = new TStringList();
  2403. try
  2404. {
  2405. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2406. {
  2407. LocalFileList->Clear();
  2408. LocalFileList->AddObject(
  2409. FCustomCommandLocalFileList->Strings[Index],
  2410. FCustomCommandLocalFileList->Objects[Index]);
  2411. RemoteFileList->Clear();
  2412. RemoteFileList->AddObject(
  2413. FCustomCommandRemoteFileList->Strings[Index],
  2414. FCustomCommandRemoteFileList->Objects[Index]);
  2415. CustomCommand(RemoteFileList, Command, LocalFileList);
  2416. }
  2417. }
  2418. __finally
  2419. {
  2420. delete LocalFileList;
  2421. delete RemoteFileList;
  2422. }
  2423. }
  2424. //---------------------------------------------------------------------------
  2425. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2426. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2427. {
  2428. delete FCustomCommandLocalFileList;
  2429. delete FCustomCommandRemoteFileList;
  2430. // takeover ownership,
  2431. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2432. FCustomCommandLocalFileList = LocalFileList;
  2433. FCustomCommandRemoteFileList = RemoteFileList;
  2434. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2435. if (Button != NULL)
  2436. {
  2437. FCustomCommandMenu->Items->Clear();
  2438. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2439. MenuPopup(FCustomCommandMenu, Button);
  2440. }
  2441. else
  2442. {
  2443. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2444. }
  2445. }
  2446. //---------------------------------------------------------------------------
  2447. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2448. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2449. {
  2450. DebugAssert(FCapturedLog != NULL);
  2451. if ((OutputType == cotOutput) || (OutputType == cotError))
  2452. {
  2453. FCapturedLog->Add(AddedLine);
  2454. }
  2455. }
  2456. //---------------------------------------------------------------------------
  2457. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2458. TOperationSide Side)
  2459. {
  2460. return
  2461. (Side == osOther) &&
  2462. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2463. }
  2464. //---------------------------------------------------------------------------
  2465. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2466. TOperationSide Side, TTBXCustomItem * Item,
  2467. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2468. {
  2469. TCustomDirView * DView = DirView(Side);
  2470. bool IsDefault = false;
  2471. if (DView->ItemFocused != NULL)
  2472. {
  2473. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2474. TResolvedDoubleClickAction DefaultAction =
  2475. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2476. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2477. }
  2478. TTBItemOptions O = Item->Options;
  2479. if (IsDefault)
  2480. {
  2481. Item->Options = O << tboDefault;
  2482. }
  2483. else
  2484. {
  2485. Item->Options = O >> tboDefault;
  2486. }
  2487. }
  2488. //---------------------------------------------------------------------------
  2489. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2490. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2491. {
  2492. TCustomDirView * DView = DirView(Side);
  2493. TListItem * Item = DView->ItemFocused;
  2494. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2495. EnableFocusedOperation[Side])
  2496. {
  2497. TPoint ClientPoint;
  2498. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2499. TPoint(0, 0) : MousePos;
  2500. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2501. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2502. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2503. }
  2504. }
  2505. //---------------------------------------------------------------------------
  2506. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2507. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2508. {
  2509. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2510. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2511. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2512. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2513. Handled = true;
  2514. }
  2515. //---------------------------------------------------------------------------
  2516. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2517. {
  2518. }
  2519. //---------------------------------------------------------------------------
  2520. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2521. {
  2522. DebugAssert(FErrorList == NULL);
  2523. if (WinConfiguration->ContinueOnError)
  2524. {
  2525. FErrorList = new TStringList();
  2526. Configuration->Usage->Inc(L"ContinuationsOnError");
  2527. }
  2528. NonVisualDataModule->StartBusy();
  2529. }
  2530. //---------------------------------------------------------------------------
  2531. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2532. {
  2533. NonVisualDataModule->EndBusy();
  2534. if (FErrorList)
  2535. {
  2536. HandleErrorList(FErrorList);
  2537. }
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2541. const TCopyParamType & CopyParam)
  2542. {
  2543. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2544. {
  2545. Configuration->Usage->Inc(L"FileMaskUses");
  2546. }
  2547. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2548. {
  2549. Configuration->Usage->Inc(L"OperationMaskUses");
  2550. }
  2551. }
  2552. //---------------------------------------------------------------------------
  2553. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2554. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2555. {
  2556. DebugAssert(!IsLocalBrowserMode());
  2557. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2558. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2559. TTransferOperationParam DefaultParam;
  2560. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2561. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2562. switch (Param.Queue)
  2563. {
  2564. case asOn:
  2565. CopyParam.Queue = true;
  2566. break;
  2567. case asOff:
  2568. CopyParam.Queue = false;
  2569. break;
  2570. case asAuto:
  2571. default:
  2572. // keep default
  2573. break;
  2574. }
  2575. bool Result =
  2576. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2577. if (Result)
  2578. {
  2579. DebugAssert(Terminal);
  2580. bool SelectionRestored = false;
  2581. TCustomDirView * DView = NULL;
  2582. if (HasDirView[Side])
  2583. {
  2584. DView = DirView(Side);
  2585. DView->SaveSelection();
  2586. DView->SaveSelectedNames();
  2587. }
  2588. UpdateCopyParamCounters(CopyParam);
  2589. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2590. DebugAssert(FTransferResumeList == NULL);
  2591. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2592. FMoveToQueue = false;
  2593. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2594. try
  2595. {
  2596. TStrings * PermanentFileList;
  2597. std::unique_ptr<TStrings> PermanentFileListOwner;
  2598. try
  2599. {
  2600. if (Side == osLocal)
  2601. {
  2602. PermanentFileList = FileList;
  2603. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2604. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2605. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2606. if (Operation == foMove)
  2607. {
  2608. ReloadLocalDirectory();
  2609. if (DView != NULL)
  2610. {
  2611. DView->RestoreSelection();
  2612. }
  2613. SelectionRestored = true;
  2614. }
  2615. }
  2616. else
  2617. {
  2618. // Clone the file list as it may refer to current directory files,
  2619. // which get destroyed, when the source directory is reloaded after foMove operation.
  2620. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2621. // But for a hotfix, we are not going to do such a big change.
  2622. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2623. PermanentFileList = PermanentFileListOwner.get();
  2624. try
  2625. {
  2626. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2627. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2628. }
  2629. __finally
  2630. {
  2631. if (Operation == foMove)
  2632. {
  2633. if (DView != NULL)
  2634. {
  2635. DView->RestoreSelection();
  2636. }
  2637. SelectionRestored = true;
  2638. }
  2639. ReloadLocalDirectory(Param.TargetDirectory);
  2640. }
  2641. }
  2642. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2643. if (FMoveToQueue)
  2644. {
  2645. Abort();
  2646. }
  2647. }
  2648. catch (EAbort &)
  2649. {
  2650. if (FMoveToQueue)
  2651. {
  2652. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2653. DebugAssert(CopyParam.TransferSkipList == NULL);
  2654. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2655. if (TransferResumeList->Count > 0)
  2656. {
  2657. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2658. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2659. }
  2660. CopyParam.TransferSkipList = TransferResumeList.release();
  2661. // not really needed, just to keep it consistent with TransferResumeList
  2662. FTransferResumeList = NULL;
  2663. FMoveToQueue = false;
  2664. Configuration->Usage->Inc("MovesToBackground");
  2665. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2666. ClearTransferSourceSelection(Direction);
  2667. }
  2668. throw;
  2669. }
  2670. }
  2671. __finally
  2672. {
  2673. if (!SelectionRestored && (DView != NULL))
  2674. {
  2675. DView->DiscardSavedSelection();
  2676. }
  2677. FTransferResumeList = NULL;
  2678. }
  2679. }
  2680. return Result;
  2681. }
  2682. //---------------------------------------------------------------------------
  2683. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2684. TOperationSide Side, TStrings * FileList, void * Param)
  2685. {
  2686. DebugAssert(FileList->Count);
  2687. // We deliberately do not toggle alternative flag (Param), but use OR,
  2688. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2689. // shortcut of CurrentDeleteAlternativeAction
  2690. bool Alternative =
  2691. bool(Param) || UseAlternativeFunction();
  2692. bool Recycle;
  2693. if (IsSideLocalBrowser(Side))
  2694. {
  2695. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2696. }
  2697. else
  2698. {
  2699. Recycle =
  2700. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2701. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2702. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2703. }
  2704. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2705. if (!Result)
  2706. {
  2707. UnicodeString Query;
  2708. if (FileList->Count == 1)
  2709. {
  2710. if (IsSideLocalBrowser(Side))
  2711. {
  2712. Query = ExtractFileName(FileList->Strings[0]);
  2713. }
  2714. else
  2715. {
  2716. Query = UnixExtractFileName(FileList->Strings[0]);
  2717. }
  2718. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2719. }
  2720. else
  2721. {
  2722. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2723. }
  2724. TMessageParams Params(mpNeverAskAgainCheck);
  2725. Params.ImageName = L"Delete file";
  2726. unsigned int Answer =
  2727. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2728. if (Answer == qaNeverAskAgain)
  2729. {
  2730. Result = true;
  2731. if (Recycle)
  2732. {
  2733. WinConfiguration->ConfirmRecycling = false;
  2734. }
  2735. else
  2736. {
  2737. WinConfiguration->ConfirmDeleting = false;
  2738. }
  2739. }
  2740. else
  2741. {
  2742. Result = (Answer == qaOK);
  2743. }
  2744. }
  2745. if (Result)
  2746. {
  2747. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2748. }
  2749. return Result;
  2750. }
  2751. //---------------------------------------------------------------------------
  2752. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2753. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2754. {
  2755. TAutoBatch AutoBatch(this);
  2756. bool Result;
  2757. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2758. {
  2759. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2760. }
  2761. else if (Operation == foRename)
  2762. {
  2763. DebugAssert(DirView(Side)->ItemFocused);
  2764. DirView(Side)->ItemFocused->EditCaption();
  2765. Result = true;
  2766. }
  2767. else if (Operation == foDelete)
  2768. {
  2769. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2770. }
  2771. else if (Operation == foSetProperties)
  2772. {
  2773. DirView(osRemote)->SaveSelectedNames();
  2774. Result = SetProperties(Side, FileList);
  2775. }
  2776. else if (Operation == foCustomCommand)
  2777. {
  2778. DebugAssert(Param);
  2779. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2780. DirView(osRemote)->SaveSelectedNames();
  2781. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2782. CustomCommand(FileList, *Command, NULL);
  2783. Result = true;
  2784. }
  2785. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2786. {
  2787. DebugAssert(!IsSideLocalBrowser(Side));
  2788. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2789. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2790. }
  2791. else if (Operation == foLock)
  2792. {
  2793. DebugAssert(!IsSideLocalBrowser(Side));
  2794. LockFiles(FileList, true);
  2795. Result = true;
  2796. }
  2797. else if (Operation == foUnlock)
  2798. {
  2799. DebugAssert(!IsSideLocalBrowser(Side));
  2800. LockFiles(FileList, false);
  2801. Result = true;
  2802. }
  2803. else
  2804. {
  2805. DebugFail();
  2806. }
  2807. return Result;
  2808. }
  2809. //---------------------------------------------------------------------------
  2810. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2811. {
  2812. if (Side == osCurrent)
  2813. {
  2814. Side = FCurrentSide;
  2815. }
  2816. return Side;
  2817. }
  2818. //---------------------------------------------------------------------------
  2819. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2820. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2821. {
  2822. Side = GetSide(Side);
  2823. bool FullPath = IsSideLocalBrowser(Side);
  2824. TCustomDirView * ADirView = DirView(Side);
  2825. std::unique_ptr<TStringList> FileList(new TStringList());
  2826. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2827. bool ReloadProperties =
  2828. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2829. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2830. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2831. if (Result && ReloadProperties)
  2832. {
  2833. std::unique_ptr<TStringList> FileList2(new TStringList());
  2834. FileList->CaseSensitive = true;
  2835. FileList->Sort();
  2836. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2837. {
  2838. TListItem * Item = ADirView->Items->Item[Index];
  2839. UnicodeString FileName = ADirView->ItemFileName(Item);
  2840. int Index2;
  2841. if (FileList->Find(FileName, Index2))
  2842. {
  2843. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2844. }
  2845. }
  2846. LoadFilesProperties(FileList2.get());
  2847. }
  2848. return Result;
  2849. }
  2850. //---------------------------------------------------------------------------
  2851. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2852. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2853. bool NoConfirmation, void * Param)
  2854. {
  2855. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2856. {
  2857. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2858. {
  2859. DebugAssert(!IsLocalBrowserMode());
  2860. if (GetSide(Side) == osLocal)
  2861. {
  2862. Configuration->Usage->Inc(L"UploadsCommand");
  2863. }
  2864. else
  2865. {
  2866. Configuration->Usage->Inc(L"DownloadsCommand");
  2867. }
  2868. }
  2869. }
  2870. }
  2871. //---------------------------------------------------------------------------
  2872. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2873. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2874. {
  2875. TTransferOperationParam Param;
  2876. if ((WinConfiguration->Interface != ifCommander) ||
  2877. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2878. {
  2879. Flags &= ~cocShortCutHint;
  2880. }
  2881. TCustomDirView * DView = DirView(Side);
  2882. Param.Options =
  2883. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2884. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2885. if (FLAGSET(Flags, cocQueue))
  2886. {
  2887. Param.Queue = asOn;
  2888. }
  2889. else if (FLAGSET(Flags, cocNonQueue))
  2890. {
  2891. Param.Queue = asOff;
  2892. }
  2893. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2894. }
  2895. //---------------------------------------------------------------------------
  2896. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2897. {
  2898. int Count = ErrorList->Count;
  2899. try
  2900. {
  2901. if (ErrorList->Count)
  2902. {
  2903. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2904. if (MessageDialog(Message, qtError,
  2905. qaOK | qaCancel, HELP_NONE) == qaOK)
  2906. {
  2907. unsigned int Answer;
  2908. int Index = 0;
  2909. do
  2910. {
  2911. DebugAssert(Index >= 0 && Index < Count);
  2912. TQueryButtonAlias Aliases[2];
  2913. Aliases[0].Button = qaYes;
  2914. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2915. Aliases[1].Button = qaNo;
  2916. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2917. TMessageParams Params;
  2918. Params.Aliases = Aliases;
  2919. Params.AliasesCount = LENOF(Aliases);
  2920. int No = Index + 1;
  2921. UnicodeString Message = ErrorList->Strings[Index];
  2922. UnicodeString AMainInstructions;
  2923. UnicodeString Details;
  2924. if (ExtractMainInstructions(Message, AMainInstructions))
  2925. {
  2926. Details = Message;
  2927. Message = AMainInstructions;
  2928. }
  2929. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2930. Answer = MoreMessageDialog(
  2931. Message,
  2932. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2933. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2934. qaOK, HELP_NONE, &Params);
  2935. if (Answer == qaNo)
  2936. {
  2937. Index++;
  2938. }
  2939. if (Answer == qaYes)
  2940. {
  2941. Index--;
  2942. }
  2943. }
  2944. while (Answer != qaOK);
  2945. }
  2946. }
  2947. }
  2948. __finally
  2949. {
  2950. TStrings * List = ErrorList;
  2951. ErrorList = NULL;
  2952. for (int i = 0; i < Count; i++)
  2953. {
  2954. delete List->Objects[i];
  2955. }
  2956. delete List;
  2957. }
  2958. }
  2959. //---------------------------------------------------------------------------
  2960. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  2961. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  2962. {
  2963. // needed for checking filemasks, as there's no directory object
  2964. // associated with the file object
  2965. File->FullFileName = FullFileName;
  2966. TFileMasks::TParams MaskParams;
  2967. MaskParams.Size = File->Size;
  2968. MaskParams.Modification = File->Modification;
  2969. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  2970. }
  2971. //---------------------------------------------------------------------------
  2972. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  2973. {
  2974. DebugAssert(!WinConfiguration->DisableOpenEdit);
  2975. Side = GetSide(Side);
  2976. TCustomDirView * DView = DirView(Side);
  2977. TListItem * FocusedItem = DView->ItemFocused;
  2978. UnicodeString Name;
  2979. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  2980. {
  2981. Name = DView->ItemFileName(FocusedItem);
  2982. }
  2983. else
  2984. {
  2985. Name = LoadStr(NEW_FILE);
  2986. }
  2987. UnicodeString Names = Name;
  2988. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  2989. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  2990. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  2991. {
  2992. while (!Names.IsEmpty())
  2993. {
  2994. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  2995. CustomWinConfiguration->History[L"EditFile"] = History.get();
  2996. UnicodeString TargetFileName;
  2997. UnicodeString LocalFileName;
  2998. UnicodeString RootTempDir;
  2999. UnicodeString TempDir;
  3000. UnicodeString RemoteDirectory;
  3001. bool ExistingFile = false;
  3002. if (!IsSideLocalBrowser(Side))
  3003. {
  3004. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3005. TRemoteFile * File = NULL;
  3006. if (Terminal->FileExists(Name, &File) &&
  3007. !File->IsDirectory)
  3008. {
  3009. try
  3010. {
  3011. ExecuteRemoteFile(Name, File, efDefaultEditor);
  3012. ExistingFile = true;
  3013. }
  3014. __finally
  3015. {
  3016. delete File;
  3017. }
  3018. }
  3019. if (!ExistingFile)
  3020. {
  3021. RemoteDirectory = UnixExtractFilePath(Name);
  3022. TemporaryDirectoryForRemoteFiles(
  3023. RemoteDirectory, GUIConfiguration->CurrentCopyParam, TempDir, RootTempDir);
  3024. TargetFileName = UnixExtractFileName(Name);
  3025. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3026. LocalFileName = TempDir +
  3027. // We probably do not want to trim the VMS version here
  3028. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3029. }
  3030. }
  3031. else
  3032. {
  3033. if (ExtractFilePath(Name).IsEmpty())
  3034. {
  3035. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3036. }
  3037. else
  3038. {
  3039. LocalFileName = ExpandFileName(Name);
  3040. }
  3041. TargetFileName = ExtractFileName(Name);
  3042. }
  3043. if (!ExistingFile)
  3044. {
  3045. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3046. if (NewFile)
  3047. {
  3048. int File = FileCreate(ApiPath(LocalFileName));
  3049. if (File < 0)
  3050. {
  3051. if (!RootTempDir.IsEmpty())
  3052. {
  3053. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3054. }
  3055. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3056. }
  3057. else
  3058. {
  3059. FileClose(File);
  3060. }
  3061. }
  3062. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3063. const TEditorData * ExternalEditor = NULL;
  3064. TFileMasks::TParams MaskParams; // size not known
  3065. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3066. false, MaskParams);
  3067. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3068. ExternalEditor, RootTempDir, RemoteDirectory, NewFile);
  3069. }
  3070. }
  3071. }
  3072. }
  3073. //---------------------------------------------------------------------------
  3074. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3075. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3076. {
  3077. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3078. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3079. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3080. return
  3081. ((ExecuteFileBy == efInternalEditor)) ||
  3082. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3083. }
  3084. //---------------------------------------------------------------------------
  3085. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3086. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3087. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3088. UnicodeString RemoteDirectory, bool NewFile)
  3089. {
  3090. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3091. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3092. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3093. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3094. Side = GetSide(Side);
  3095. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3096. if (!IsSideLocalBrowser(Side))
  3097. {
  3098. Data->Terminal = Terminal;
  3099. Data->Queue = Queue;
  3100. Data->SessionData = CloneCurrentSessionData();
  3101. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3102. Data->RemoteDirectory = RemoteDirectory;
  3103. Data->SessionName = Terminal->SessionData->SessionName;
  3104. Data->LocalRootDirectory = LocalRootDirectory;
  3105. Data->OriginalFileName = OriginalFileName;
  3106. Data->Command = L""; // will be changed later for external editor
  3107. }
  3108. if (ExecuteFileBy == efInternalEditor)
  3109. {
  3110. if (!IsSideLocalBrowser(Side))
  3111. {
  3112. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3113. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3114. TForm * Editor;
  3115. try
  3116. {
  3117. Editor =
  3118. ShowEditorForm(
  3119. FileName, this,
  3120. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3121. SaveAllInternalEditors, AnyInternalEditorModified,
  3122. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3123. }
  3124. catch(...)
  3125. {
  3126. if (!LocalRootDirectory.IsEmpty())
  3127. {
  3128. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory), false);
  3129. }
  3130. throw;
  3131. }
  3132. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3133. }
  3134. else
  3135. {
  3136. DebugAssert(!StandaloneOperation);
  3137. TForm * Editor =
  3138. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3139. SaveAllInternalEditors, AnyInternalEditorModified,
  3140. L"", false, SessionColor, -1, NewFile);
  3141. FLocalEditors->Add(Editor);
  3142. }
  3143. }
  3144. else
  3145. {
  3146. HANDLE Process;
  3147. if (ExecuteFileBy == efExternalEditor)
  3148. {
  3149. UnicodeString Program, Params, Dir;
  3150. Data->Command = ExternalEditor->ExternalEditor;
  3151. ReformatFileNameCommand(Data->Command);
  3152. SplitCommand(Data->Command, Program, Params, Dir);
  3153. Params = ExpandFileNameCommand(Params, FileName);
  3154. Program = ExpandEnvironmentVariables(Program);
  3155. if (!ExecuteShell(Program, Params, Process))
  3156. {
  3157. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3158. }
  3159. }
  3160. else
  3161. {
  3162. DebugAssert(!IsSideLocalBrowser(Side));
  3163. if (!ExecuteShell(FileName, L"", Process))
  3164. {
  3165. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3166. }
  3167. }
  3168. if (IsSideLocalBrowser(Side) ||
  3169. ((ExecuteFileBy == efShell) &&
  3170. !WinConfiguration->Editor.SDIShellEditor) ||
  3171. ((ExecuteFileBy == efExternalEditor) &&
  3172. !ExternalEditor->SDIExternalEditor))
  3173. {
  3174. // no need for handle
  3175. if (Process != NULL)
  3176. {
  3177. DebugCheck(CloseHandle(Process));
  3178. }
  3179. Process = INVALID_HANDLE_VALUE;
  3180. }
  3181. else
  3182. {
  3183. if (Process == NULL)
  3184. {
  3185. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3186. }
  3187. }
  3188. if (!IsSideLocalBrowser(Side))
  3189. {
  3190. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3191. }
  3192. }
  3193. }
  3194. //---------------------------------------------------------------------------
  3195. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3196. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3197. void * /*Arg*/)
  3198. {
  3199. if (Token != NULL)
  3200. {
  3201. EditorFormFileSave(static_cast<TForm *>(Token));
  3202. }
  3203. }
  3204. //---------------------------------------------------------------------------
  3205. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3206. {
  3207. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3208. {
  3209. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3210. }
  3211. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3212. }
  3213. //---------------------------------------------------------------------------
  3214. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3215. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3216. void * Arg)
  3217. {
  3218. if ((Token != NULL) &&
  3219. IsEditorFormModified(static_cast<TForm *>(Token)))
  3220. {
  3221. *static_cast<bool *>(Arg) = true;
  3222. }
  3223. }
  3224. //---------------------------------------------------------------------------
  3225. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3226. TObject * /*Sender*/, bool & Modified)
  3227. {
  3228. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3229. {
  3230. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3231. {
  3232. Modified = true;
  3233. }
  3234. }
  3235. if (!Modified)
  3236. {
  3237. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3238. }
  3239. }
  3240. //---------------------------------------------------------------------------
  3241. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3242. {
  3243. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3244. }
  3245. //---------------------------------------------------------------------------
  3246. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3247. UnicodeString RemoteDirectory, TCopyParamType CopyParam,
  3248. UnicodeString & Result, UnicodeString & RootDirectory)
  3249. {
  3250. if (!WinConfiguration->TemporaryDirectoryDeterministic)
  3251. {
  3252. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3253. Result = RootDirectory;
  3254. }
  3255. else
  3256. {
  3257. RootDirectory = L"";
  3258. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3259. Result = IncludeTrailingBackslash(Result);
  3260. }
  3261. if (WinConfiguration->TemporaryDirectoryAppendSession)
  3262. {
  3263. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3264. }
  3265. if (WinConfiguration->TemporaryDirectoryAppendPath)
  3266. {
  3267. if (!RemoteDirectory.IsEmpty() && (RemoteDirectory[1] == L'/'))
  3268. {
  3269. RemoteDirectory.Delete(1, 1);
  3270. }
  3271. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(RemoteDirectory)));
  3272. }
  3273. if (!ForceDirectories(ApiPath(Result)))
  3274. {
  3275. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3276. }
  3277. }
  3278. //---------------------------------------------------------------------------
  3279. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3280. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3281. bool GetTargetNames, bool AutoOperation)
  3282. {
  3283. DebugAssert(!IsLocalBrowserMode());
  3284. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3285. if (ForceText)
  3286. {
  3287. CopyParam.TransferMode = tmAscii;
  3288. }
  3289. TemporaryFileCopyParam(CopyParam);
  3290. if (TempDir.IsEmpty())
  3291. {
  3292. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, TempDir, RootTempDir);
  3293. }
  3294. DebugAssert(!FAutoOperation);
  3295. FAutoOperation = AutoOperation;
  3296. Terminal->ExceptionOnFail = true;
  3297. try
  3298. {
  3299. try
  3300. {
  3301. // turn off confirmations, as for MDI editors we may possibly download
  3302. // the same file over
  3303. Terminal->CopyToLocal(
  3304. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3305. if (GetTargetNames)
  3306. {
  3307. for (int i = 0; i < FileList->Count; i++)
  3308. {
  3309. FileList->Strings[i] =
  3310. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3311. }
  3312. }
  3313. }
  3314. catch(...)
  3315. {
  3316. if (!RootTempDir.IsEmpty())
  3317. {
  3318. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3319. }
  3320. throw;
  3321. }
  3322. }
  3323. __finally
  3324. {
  3325. FAutoOperation = false;
  3326. Terminal->ExceptionOnFail = false;
  3327. }
  3328. }
  3329. //---------------------------------------------------------------------------
  3330. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3331. {
  3332. // Do not waste time checking for default editor list the next time,
  3333. // or testing if default editor is not notepad.
  3334. bool TryNextTime = false;
  3335. UnicodeString UsageState;
  3336. if (!WinConfiguration->EditorList->IsDefaultList())
  3337. {
  3338. UsageState = "H";
  3339. }
  3340. else
  3341. {
  3342. UnicodeString Executable;
  3343. UnicodeString ExecutableDescription;
  3344. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3345. {
  3346. UnicodeString Message =
  3347. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3348. unsigned int Answer =
  3349. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3350. if (Answer != qaOK)
  3351. {
  3352. UsageState = "R";
  3353. }
  3354. else
  3355. {
  3356. UsageState = "A";
  3357. TEditorData EditorData;
  3358. EditorData.Editor = edExternal;
  3359. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3360. EditorData.ExternalEditorOptionsAutodetect();
  3361. TEditorList EditorList;
  3362. EditorList = *WinConfiguration->EditorList;
  3363. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3364. WinConfiguration->EditorList = &EditorList;
  3365. }
  3366. }
  3367. }
  3368. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3369. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3370. }
  3371. //---------------------------------------------------------------------------
  3372. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3373. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3374. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3375. {
  3376. if (ExecuteFileBy == efDefaultEditor)
  3377. {
  3378. if (!WinConfiguration->OfferedEditorAutoConfig)
  3379. {
  3380. EditorAutoConfig();
  3381. }
  3382. const TEditorPreferences * Editor =
  3383. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3384. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3385. {
  3386. ExecuteFileBy = efInternalEditor;
  3387. ExternalEditor = NULL;
  3388. }
  3389. else if (Editor->Data->Editor == edOpen)
  3390. {
  3391. ExecuteFileBy = efShell;
  3392. ExternalEditor = NULL;
  3393. }
  3394. else
  3395. {
  3396. ExecuteFileBy = efExternalEditor;
  3397. ExternalEditor = Editor->Data;
  3398. }
  3399. }
  3400. }
  3401. //---------------------------------------------------------------------------
  3402. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3403. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3404. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3405. {
  3406. UnicodeString OriginalFileName;
  3407. UnicodeString LocalRootDirectory;
  3408. UnicodeString RemoteDirectory;
  3409. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3410. IsSideLocalBrowser(Side), MaskParams);
  3411. UnicodeString Counter;
  3412. UnicodeString LocalFileName;
  3413. bool Handled = false;
  3414. if (!IsSideLocalBrowser(Side))
  3415. {
  3416. // We need to trim VMS version here, so that we use name without version
  3417. // when uploading back to create a new version of the file
  3418. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3419. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3420. TObject * Token = NULL;
  3421. UnicodeString LocalDirectory;
  3422. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3423. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3424. LocalDirectory))
  3425. {
  3426. if (Token != NULL)
  3427. {
  3428. TForm * Form = dynamic_cast<TForm *>(Token);
  3429. if (Form->WindowState == wsMinimized)
  3430. {
  3431. ShowWindow(Form->Handle, SW_RESTORE);
  3432. }
  3433. else
  3434. {
  3435. Form->SetFocus();
  3436. }
  3437. Handled = true;
  3438. }
  3439. else
  3440. {
  3441. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3442. }
  3443. }
  3444. if (!Handled)
  3445. {
  3446. TStringList * FileList1 = new TStringList();
  3447. try
  3448. {
  3449. FileList1->AddObject(FullFileName, Object);
  3450. TemporarilyDownloadFiles(FileList1,
  3451. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3452. LocalRootDirectory, LocalDirectory, true, true);
  3453. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3454. }
  3455. __finally
  3456. {
  3457. delete FileList1;
  3458. }
  3459. switch (ExecuteFileBy)
  3460. {
  3461. case efShell:
  3462. Counter = "RemoteFilesExecuted";
  3463. break;
  3464. case efInternalEditor:
  3465. Counter = "RemoteFilesOpenedInInternalEditor";
  3466. break;
  3467. case efExternalEditor:
  3468. Counter = "RemoteFilesOpenedInExternalEditor";
  3469. break;
  3470. default:
  3471. DebugFail();
  3472. }
  3473. }
  3474. }
  3475. else
  3476. {
  3477. LocalFileName = FullFileName;
  3478. OriginalFileName = ExtractFileName(FullFileName);
  3479. switch (ExecuteFileBy)
  3480. {
  3481. case efShell:
  3482. Counter = "LocalFilesExecuted";
  3483. break;
  3484. case efInternalEditor:
  3485. Counter = "LocalFilesOpenedInInternalEditor";
  3486. break;
  3487. case efExternalEditor:
  3488. Counter = "LocalFilesOpenedInExternalEditor";
  3489. break;
  3490. default:
  3491. DebugFail();
  3492. }
  3493. }
  3494. if (!Handled)
  3495. {
  3496. Configuration->Usage->Inc(Counter);
  3497. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3498. ExternalEditor, LocalRootDirectory, RemoteDirectory, false);
  3499. }
  3500. }
  3501. //---------------------------------------------------------------------------
  3502. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3503. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3504. bool AllSelected, bool OnFocused)
  3505. {
  3506. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3507. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3508. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3509. Side = GetSide(Side);
  3510. TCustomDirView * DView = DirView(Side);
  3511. TStrings * FileList =
  3512. AllSelected ?
  3513. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3514. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3515. try
  3516. {
  3517. DebugAssert(AllSelected || (FileList->Count == 1));
  3518. for (int i = 0; i < FileList->Count; i++)
  3519. {
  3520. UnicodeString ListFileName = FileList->Strings[i];
  3521. UnicodeString FileNameOnly =
  3522. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3523. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3524. if (!DView->ItemIsDirectory(Item))
  3525. {
  3526. UnicodeString FullFileName;
  3527. if (!IsSideLocalBrowser(Side))
  3528. {
  3529. FullFileName = DirView(Side)->Path + ListFileName;
  3530. }
  3531. else
  3532. {
  3533. FullFileName = ListFileName;
  3534. }
  3535. TObject * Object = FileList->Objects[i];
  3536. TFileMasks::TParams MaskParams;
  3537. MaskParams.Size = DView->ItemFileSize(Item);
  3538. TDateTimePrecision Precision;
  3539. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3540. std::unique_ptr<TRemoteFile> FileOwner;
  3541. if (!IsSideLocalBrowser(Side))
  3542. {
  3543. TRemoteFile * File = NULL;
  3544. Terminal->FileExists(FullFileName, &File);
  3545. if (File != NULL)
  3546. {
  3547. File->FullFileName = FullFileName;
  3548. Object = File;
  3549. FileOwner.reset(File);
  3550. MaskParams.Size = File->Size;
  3551. MaskParams.Modification = File->Modification;
  3552. }
  3553. }
  3554. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3555. }
  3556. }
  3557. }
  3558. __finally
  3559. {
  3560. delete FileList;
  3561. }
  3562. }
  3563. //---------------------------------------------------------------------------
  3564. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3565. {
  3566. CopyParam.FileNameCase = ncNoChange;
  3567. CopyParam.PreserveRights = false;
  3568. CopyParam.PreserveReadOnly = false;
  3569. CopyParam.ReplaceInvalidChars = true;
  3570. CopyParam.IncludeFileMask = TFileMasks();
  3571. CopyParam.NewerOnly = false;
  3572. CopyParam.FileMask = L"";
  3573. }
  3574. //---------------------------------------------------------------------------
  3575. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3576. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3577. {
  3578. TTerminalManager * Manager = TTerminalManager::Instance();
  3579. if (!IsActiveTerminal(Data->Terminal))
  3580. {
  3581. if (!NonVisualDataModule->Busy)
  3582. {
  3583. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3584. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3585. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3586. if (Data->Terminal == NULL)
  3587. {
  3588. TTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3589. if (SameSiteTerminal != NULL)
  3590. {
  3591. UnicodeString Message =
  3592. FMTLOAD(EDIT_SESSION_REATTACH,
  3593. (FileNameOnly, Data->SessionName, FileNameOnly));
  3594. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3595. {
  3596. Data->Terminal = Terminal;
  3597. Data->Queue = Manager->FindQueueForTerminal(Terminal);
  3598. Data->SessionName = Terminal->SessionData->SessionName;
  3599. // We might also overwrite session data
  3600. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3601. }
  3602. else
  3603. {
  3604. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3605. Abort();
  3606. }
  3607. }
  3608. }
  3609. // foreground session should reconnect itself
  3610. else if (Terminal != Data->Terminal)
  3611. {
  3612. UnicodeString Message =
  3613. MainInstructions(
  3614. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3615. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3616. {
  3617. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3618. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3619. }
  3620. else
  3621. {
  3622. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3623. Abort();
  3624. }
  3625. }
  3626. }
  3627. if (!IsActiveTerminal(Data->Terminal))
  3628. {
  3629. Configuration->Usage->Inc(L"EditInactiveSession");
  3630. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3631. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3632. (ExtractFileName(FileName), Data->SessionName)));
  3633. }
  3634. }
  3635. TStrings * FileList = new TStringList();
  3636. try
  3637. {
  3638. FileList->Add(FileName);
  3639. // consider using the same settings (preset) as when the file was downloaded
  3640. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3641. TemporaryFileCopyParam(CopyParam);
  3642. if (Data->ForceText)
  3643. {
  3644. CopyParam.TransferMode = tmAscii;
  3645. }
  3646. // so i do not need to worry if masking algorithm works in all cases
  3647. // ("" means "copy file name", no masking is actually done)
  3648. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3649. {
  3650. CopyParam.FileMask = L"";
  3651. }
  3652. else
  3653. {
  3654. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3655. }
  3656. int Params = cpNoConfirmation | cpTemporary;
  3657. if (Terminal->IsCapable[fcBackgroundTransfers])
  3658. {
  3659. DebugAssert(Data->Queue != NULL);
  3660. TQueueItem * QueueItem = new TUploadQueueItem(Data->Terminal, FileList,
  3661. Data->RemoteDirectory, &CopyParam, Params, true, false);
  3662. QueueItem->CompleteEvent = UploadCompleteEvent;
  3663. AddQueueItem(Data->Queue, QueueItem, Data->Terminal);
  3664. }
  3665. else
  3666. {
  3667. if (NonVisualDataModule->Busy)
  3668. {
  3669. Retry = true;
  3670. }
  3671. else
  3672. {
  3673. Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3674. SetEvent(UploadCompleteEvent);
  3675. }
  3676. }
  3677. }
  3678. __finally
  3679. {
  3680. delete FileList;
  3681. }
  3682. }
  3683. //---------------------------------------------------------------------------
  3684. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3685. const UnicodeString FileName, const TEditedFileData * Data)
  3686. {
  3687. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3688. DebugAssert(!NonVisualDataModule->Busy);
  3689. if (!IsActiveTerminal(Data->Terminal))
  3690. {
  3691. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3692. (ExtractFileName(FileName), Data->SessionName)));
  3693. }
  3694. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3695. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3696. NonVisualDataModule->StartBusy();
  3697. try
  3698. {
  3699. std::unique_ptr<TRemoteFile> File;
  3700. UnicodeString RemoteFileName =
  3701. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3702. Terminal->ExceptionOnFail = true;
  3703. try
  3704. {
  3705. TRemoteFile * AFile = NULL;
  3706. Terminal->ReadFile(RemoteFileName, AFile);
  3707. File.reset(AFile);
  3708. if (!File->HaveFullFileName)
  3709. {
  3710. File->FullFileName = RemoteFileName;
  3711. }
  3712. }
  3713. __finally
  3714. {
  3715. Terminal->ExceptionOnFail = false;
  3716. }
  3717. std::unique_ptr<TStrings> FileList(new TStringList());
  3718. FileList->AddObject(RemoteFileName, File.get());
  3719. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3720. UnicodeString TempDir = ExtractFilePath(FileName);
  3721. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true);
  3722. // sanity check, the target file name should be still the same
  3723. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3724. }
  3725. __finally
  3726. {
  3727. NonVisualDataModule->EndBusy();
  3728. // it actually may not exist anymore...
  3729. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3730. }
  3731. }
  3732. //---------------------------------------------------------------------------
  3733. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3734. const TEditedFileData * Data, bool & KeepOpen)
  3735. {
  3736. // Command is set for external editors only (not for "shell" open).
  3737. if (!Data->Command.IsEmpty())
  3738. {
  3739. bool AnyFound = false;
  3740. bool AnyMDI = false;
  3741. bool AnyNonMDI = false;
  3742. bool AnyDetect = false;
  3743. TEditorList * EditorList = new TEditorList();
  3744. try
  3745. {
  3746. *EditorList = *WinConfiguration->EditorList;
  3747. for (int i = 0; i < EditorList->Count; i++)
  3748. {
  3749. const TEditorPreferences * Editor = EditorList->Editors[i];
  3750. if ((Editor->Data->Editor == edExternal) &&
  3751. (Editor->Data->ExternalEditor == Data->Command))
  3752. {
  3753. AnyFound = true;
  3754. if (Editor->Data->SDIExternalEditor)
  3755. {
  3756. AnyNonMDI = true;
  3757. if (Editor->Data->DetectMDIExternalEditor)
  3758. {
  3759. AnyDetect = true;
  3760. }
  3761. }
  3762. else
  3763. {
  3764. AnyMDI = true;
  3765. }
  3766. }
  3767. }
  3768. bool EnableMDI = false;
  3769. bool DisableDetect = false;
  3770. if (AnyMDI)
  3771. {
  3772. KeepOpen = true;
  3773. if (AnyNonMDI)
  3774. {
  3775. // there is at least one instance of the editor with MDI support enabled,
  3776. // and one with disabled, enable it for all instances
  3777. EnableMDI = true;
  3778. }
  3779. }
  3780. else if (AnyFound && !AnyDetect)
  3781. {
  3782. // at least once instance found but all have MDI autodetection disabled
  3783. // => close the file (default action)
  3784. }
  3785. else
  3786. {
  3787. // no instance of the editor has MDI support enabled
  3788. TMessageParams Params;
  3789. if (AnyFound)
  3790. {
  3791. // there is at least one instance of the editor
  3792. Params.Params |= mpNeverAskAgainCheck;
  3793. }
  3794. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3795. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3796. switch (Answer)
  3797. {
  3798. case qaNeverAskAgain:
  3799. DisableDetect = true;
  3800. break;
  3801. case qaNo:
  3802. EnableMDI = true;
  3803. KeepOpen = true;
  3804. break;
  3805. }
  3806. }
  3807. if (AnyFound && (EnableMDI || DisableDetect))
  3808. {
  3809. bool Changed = false;
  3810. for (int i = 0; i < EditorList->Count; i++)
  3811. {
  3812. const TEditorPreferences * Editor = EditorList->Editors[i];
  3813. if ((Editor->Data->Editor == edExternal) &&
  3814. (Editor->Data->ExternalEditor == Data->Command) &&
  3815. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3816. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3817. {
  3818. Changed = true;
  3819. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3820. if (EnableMDI)
  3821. {
  3822. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3823. }
  3824. if (DisableDetect)
  3825. {
  3826. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3827. }
  3828. EditorList->Change(i, UpdatedEditor);
  3829. }
  3830. }
  3831. if (Changed)
  3832. {
  3833. WinConfiguration->EditorList = EditorList;
  3834. }
  3835. }
  3836. }
  3837. __finally
  3838. {
  3839. delete EditorList;
  3840. }
  3841. }
  3842. else
  3843. {
  3844. // "open" case
  3845. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  3846. qaOK, HELP_APP_EARLY_CLOSED);
  3847. }
  3848. }
  3849. //---------------------------------------------------------------------------
  3850. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  3851. {
  3852. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  3853. }
  3854. //---------------------------------------------------------------------------
  3855. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  3856. {
  3857. SideEnter(osRemote);
  3858. }
  3859. //---------------------------------------------------------------------------
  3860. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  3861. {
  3862. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  3863. SideEnter(osRemote);
  3864. }
  3865. //---------------------------------------------------------------------------
  3866. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  3867. {
  3868. FCurrentSide = Side;
  3869. if (Visible)
  3870. {
  3871. UpdateControls();
  3872. }
  3873. }
  3874. //---------------------------------------------------------------------------
  3875. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  3876. {
  3877. VisualiseOperationFinished(Side, FileName, Success);
  3878. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  3879. {
  3880. FDeletedFiles->Add(FileName);
  3881. }
  3882. }
  3883. //---------------------------------------------------------------------------
  3884. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  3885. TStrings * FileList, bool Alternative)
  3886. {
  3887. TCustomDirView * DView = DirView(Side);
  3888. DView->SaveSelection();
  3889. DView->SaveSelectedNames();
  3890. DebugAssert(!FAlternativeDelete);
  3891. FAlternativeDelete = Alternative;
  3892. try
  3893. {
  3894. if (!IsSideLocalBrowser(Side))
  3895. {
  3896. DebugAssert(Terminal != NULL);
  3897. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  3898. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  3899. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  3900. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  3901. int Params = FLAGMASK(Alternative, dfAlternative);
  3902. try
  3903. {
  3904. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles);
  3905. DebugAssert(FDeletedFiles == NULL);
  3906. FDeletedFiles = DeletedFiles.get();
  3907. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  3908. FOnFileOperationFinished = FileDeleted;
  3909. FMoveToQueue = false;
  3910. Terminal->DeleteFiles(FileList, Params);
  3911. // Probably not needed for deleting, just for consistency with transfer code
  3912. if (FMoveToQueue)
  3913. {
  3914. Abort();
  3915. }
  3916. }
  3917. catch (EAbort &)
  3918. {
  3919. if (FMoveToQueue)
  3920. {
  3921. DeletedFiles->Sorted = true;
  3922. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  3923. {
  3924. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  3925. {
  3926. // We should always be deleting the first item => what can be used to optimize this code, if needed
  3927. DebugAssert(Index == 0);
  3928. PermanentFileList->Delete(Index);
  3929. Index--;
  3930. }
  3931. }
  3932. Configuration->Usage->Inc("MovesToBackgroundDelete");
  3933. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  3934. AddQueueItem(Queue, QueueItem, Terminal);
  3935. ClearOperationSelection(osRemote);
  3936. }
  3937. }
  3938. }
  3939. else
  3940. {
  3941. if (IsLocalBrowserMode())
  3942. {
  3943. Configuration->Usage->Inc(L"LocalLocalDeletes");
  3944. }
  3945. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  3946. FProgressSide = FCurrentSide;
  3947. try
  3948. {
  3949. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  3950. }
  3951. __finally
  3952. {
  3953. ReloadLocalDirectory();
  3954. }
  3955. }
  3956. FAlternativeDelete = false;
  3957. }
  3958. catch(...)
  3959. {
  3960. FAlternativeDelete = false;
  3961. DView->DiscardSavedSelection();
  3962. throw;
  3963. }
  3964. DView->RestoreSelection();
  3965. }
  3966. //---------------------------------------------------------------------------
  3967. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  3968. {
  3969. DebugAssert(Terminal);
  3970. DebugAssert(!IsLocalBrowserMode());
  3971. RemoteDirView->SaveSelection();
  3972. RemoteDirView->SaveSelectedNames();
  3973. try
  3974. {
  3975. if (Lock)
  3976. {
  3977. Terminal->LockFiles(FileList);
  3978. }
  3979. else
  3980. {
  3981. Terminal->UnlockFiles(FileList);
  3982. }
  3983. }
  3984. catch(...)
  3985. {
  3986. RemoteDirView->DiscardSavedSelection();
  3987. throw;
  3988. }
  3989. RemoteDirView->RestoreSelection();
  3990. }
  3991. //---------------------------------------------------------------------------
  3992. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  3993. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  3994. bool NoConfirmation, bool Move)
  3995. {
  3996. DebugAssert(Terminal != NULL);
  3997. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  3998. DebugAssert(!IsLocalBrowserMode());
  3999. if (Session == NULL)
  4000. {
  4001. Session = Terminal;
  4002. }
  4003. if (Session == Terminal)
  4004. {
  4005. if (RemoteDriveView->DropTarget != NULL)
  4006. {
  4007. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4008. }
  4009. else if (RemoteDirView->DropTarget != NULL)
  4010. {
  4011. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4012. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4013. }
  4014. else
  4015. {
  4016. Target = RemoteDirView->Path;
  4017. }
  4018. }
  4019. else
  4020. {
  4021. Target = GetSessionPath(Session, osRemote);
  4022. }
  4023. Target = UnixIncludeTrailingBackslash(Target);
  4024. if (FileList->Count == 1)
  4025. {
  4026. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4027. }
  4028. else
  4029. {
  4030. FileMask = AnyMask;
  4031. }
  4032. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4033. bool Result = true;
  4034. if (!NoConfirmation)
  4035. {
  4036. bool Multi = (FileList->Count > 1);
  4037. if (Move)
  4038. {
  4039. Result = DoRemoteMoveDialog(Multi, Target, FileMask);
  4040. }
  4041. else
  4042. {
  4043. std::unique_ptr<TStrings> Sessions(new TStringList);
  4044. std::unique_ptr<TStrings> Directories(new TStringList);
  4045. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4046. for (int Index = 0; Index < SessionList->Count; Index++)
  4047. {
  4048. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4049. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4050. {
  4051. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4052. Directories->Add(GetSessionPath(ASession, osRemote));
  4053. }
  4054. }
  4055. TDirectRemoteCopy AllowDirectCopy;
  4056. if (Terminal->IsCapable[fcRemoteCopy] || Terminal->CommandSessionOpened)
  4057. {
  4058. DebugAssert(DirectCopy);
  4059. AllowDirectCopy = drcAllow;
  4060. }
  4061. else if (Terminal->IsCapable[fcSecondaryShell])
  4062. {
  4063. DebugAssert(DirectCopy);
  4064. AllowDirectCopy = drcConfirmCommandSession;
  4065. }
  4066. else
  4067. {
  4068. DebugAssert(!DirectCopy);
  4069. AllowDirectCopy = drcDisallow;
  4070. }
  4071. void * ASession = Session;
  4072. Result = DoRemoteCopyDialog(
  4073. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal);
  4074. Session = static_cast<TManagedTerminal *>(ASession);
  4075. }
  4076. }
  4077. return Result;
  4078. }
  4079. //---------------------------------------------------------------------------
  4080. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4081. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4082. {
  4083. DebugAssert(!IsLocalBrowserMode());
  4084. bool DirectCopy;
  4085. UnicodeString Target, FileMask;
  4086. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4087. if (Result)
  4088. {
  4089. if (!Move && !DirectCopy)
  4090. {
  4091. Configuration->Usage->Inc("RemoteCopyTemp");
  4092. UnicodeString RootTempDir;
  4093. UnicodeString TempDir;
  4094. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false);
  4095. TStrings * TemporaryFilesList = new TStringList();
  4096. try
  4097. {
  4098. TMakeLocalFileListParams MakeFileListParam;
  4099. MakeFileListParam.FileList = TemporaryFilesList;
  4100. MakeFileListParam.FileTimes = NULL;
  4101. MakeFileListParam.IncludeDirs = true;
  4102. MakeFileListParam.Recursive = false;
  4103. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4104. TTerminalManager::Instance()->ActiveSession = Session;
  4105. if (TemporaryFilesList->Count > 0)
  4106. {
  4107. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4108. CopyParam.FileMask = FileMask;
  4109. DebugAssert(!FAutoOperation);
  4110. FAutoOperation = true;
  4111. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4112. }
  4113. }
  4114. __finally
  4115. {
  4116. delete TemporaryFilesList;
  4117. FAutoOperation = false;
  4118. if (!RootTempDir.IsEmpty())
  4119. {
  4120. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  4121. }
  4122. }
  4123. }
  4124. else
  4125. {
  4126. RemoteDirView->SaveSelection();
  4127. RemoteDirView->SaveSelectedNames();
  4128. try
  4129. {
  4130. if (Move)
  4131. {
  4132. Configuration->Usage->Inc("RemoteMove");
  4133. Terminal->MoveFiles(FileList, Target, FileMask);
  4134. }
  4135. else
  4136. {
  4137. Configuration->Usage->Inc("RemoteCopyDirect");
  4138. DebugAssert(DirectCopy);
  4139. DebugAssert(Session == Terminal);
  4140. if (Terminal->IsCapable[fcRemoteCopy] ||
  4141. Terminal->CommandSessionOpened ||
  4142. CommandSessionFallback())
  4143. {
  4144. Terminal->CopyFiles(FileList, Target, FileMask);
  4145. }
  4146. }
  4147. }
  4148. catch(...)
  4149. {
  4150. RemoteDirView->DiscardSavedSelection();
  4151. throw;
  4152. }
  4153. RemoteDirView->RestoreSelection();
  4154. }
  4155. }
  4156. return Result;
  4157. }
  4158. //---------------------------------------------------------------------------
  4159. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4160. const UnicodeString & Path, TRemoteProperties & Properties)
  4161. {
  4162. DebugAssert(!IsLocalBrowserMode());
  4163. Properties.Valid = Properties.Valid << vpEncrypt;
  4164. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4165. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4166. }
  4167. //---------------------------------------------------------------------------
  4168. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4169. {
  4170. Side = GetSide(Side);
  4171. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4172. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4173. UnicodeString Name = LoadStr(NEW_FOLDER);
  4174. int AllowedChanges =
  4175. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4176. bool SaveSettings = false;
  4177. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4178. {
  4179. TWindowLock Lock(this);
  4180. if (!IsSideLocalBrowser(Side))
  4181. {
  4182. if (SaveSettings)
  4183. {
  4184. GUIConfiguration->NewDirectoryProperties = Properties;
  4185. }
  4186. CreateRemoteDirectory(Name, Properties);
  4187. }
  4188. else
  4189. {
  4190. DirView(Side)->CreateDirectory(Name);
  4191. }
  4192. }
  4193. }
  4194. //---------------------------------------------------------------------------
  4195. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4196. {
  4197. TWindowLock Lock(this);
  4198. DirView(Side)->ExecuteHomeDirectory();
  4199. }
  4200. //---------------------------------------------------------------------------
  4201. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4202. {
  4203. DoOpenDirectoryDialog(odBrowse, Side);
  4204. }
  4205. //---------------------------------------------------------------------------
  4206. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4207. {
  4208. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4209. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4210. bool Result = !Path.IsEmpty();
  4211. if (Result)
  4212. {
  4213. TryOpenDirectory(Side, Path);
  4214. }
  4215. return Result;
  4216. }
  4217. //---------------------------------------------------------------------------
  4218. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4219. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4220. bool & Close)
  4221. {
  4222. // terminal can be already closed (e.g. dropped connection)
  4223. if (Terminal != NULL)
  4224. {
  4225. try
  4226. {
  4227. TCalculateSizeParams Params;
  4228. Params.Stats = &Stats;
  4229. Terminal->CalculateFilesSize(FileList, Size, Params);
  4230. }
  4231. catch(...)
  4232. {
  4233. if (!Terminal->Active)
  4234. {
  4235. Close = true;
  4236. }
  4237. throw;
  4238. }
  4239. }
  4240. }
  4241. //---------------------------------------------------------------------------
  4242. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4243. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4244. bool & Close)
  4245. {
  4246. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4247. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4248. {
  4249. Configuration->Usage->Inc(L"ChecksumCalculated");
  4250. try
  4251. {
  4252. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4253. }
  4254. catch(...)
  4255. {
  4256. if (!Terminal->Active)
  4257. {
  4258. Close = true;
  4259. }
  4260. throw;
  4261. }
  4262. }
  4263. }
  4264. //---------------------------------------------------------------------------
  4265. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4266. {
  4267. if (Terminal->LoadFilesProperties(FileList))
  4268. {
  4269. RemoteDirView->Invalidate();
  4270. }
  4271. }
  4272. //---------------------------------------------------------------------------
  4273. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4274. {
  4275. bool Result;
  4276. if (!IsSideLocalBrowser(Side))
  4277. {
  4278. TRemoteTokenList * GroupList = NULL;
  4279. TRemoteTokenList * UserList = NULL;
  4280. try
  4281. {
  4282. TRemoteProperties CurrentProperties;
  4283. LoadFilesProperties(FileList);
  4284. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4285. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4286. if (CapableGroupChanging || CapableOwnerChanging)
  4287. {
  4288. if (CapableGroupChanging)
  4289. {
  4290. GroupList = Terminal->Groups->Duplicate();
  4291. }
  4292. if (CapableOwnerChanging)
  4293. {
  4294. UserList = Terminal->Users->Duplicate();
  4295. }
  4296. TRemoteDirectory * Files = Terminal->Files;
  4297. int Count = Files->Count;
  4298. if (Count > 100)
  4299. {
  4300. Count = 100;
  4301. }
  4302. for (int Index = 0; Index < Count; Index++)
  4303. {
  4304. TRemoteFile * File = Files->Files[Index];
  4305. if (CapableGroupChanging)
  4306. {
  4307. GroupList->AddUnique(File->Group);
  4308. }
  4309. if (CapableOwnerChanging)
  4310. {
  4311. UserList->AddUnique(File->Owner);
  4312. }
  4313. }
  4314. // if we haven't collected tokens for all files in current directory,
  4315. // make sure we collect them at least for all selected files.
  4316. // (note that so far the files in FileList has to be from current direcotry)
  4317. if (Count < Files->Count)
  4318. {
  4319. for (int Index = 0; Index < FileList->Count; Index++)
  4320. {
  4321. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4322. if (CapableGroupChanging)
  4323. {
  4324. GroupList->AddUnique(File->Group);
  4325. }
  4326. if (CapableOwnerChanging)
  4327. {
  4328. UserList->AddUnique(File->Owner);
  4329. }
  4330. }
  4331. }
  4332. }
  4333. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4334. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4335. for (int Index = 0; (Index < FileList->Count) && CapableAclChanging; Index++)
  4336. {
  4337. if (dynamic_cast<TRemoteFile *>(FileList->Objects[Index])->IsDirectory)
  4338. {
  4339. CapableAclChanging = false;
  4340. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4341. }
  4342. }
  4343. int Flags = 0;
  4344. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4345. if (CapableAclChanging) Flags |= cpAcl;
  4346. if (CapableOwnerChanging) Flags |= cpOwner;
  4347. if (CapableGroupChanging) Flags |= cpGroup;
  4348. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4349. if (Terminal->IsCapable[fcCalculatingChecksum] ||
  4350. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles()))
  4351. {
  4352. CalculateChecksumEvent = CalculateChecksum;
  4353. }
  4354. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4355. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4356. TRemoteProperties NewProperties = CurrentProperties;
  4357. Result =
  4358. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4359. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4360. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4361. CalculateSize, CalculateChecksumEvent);
  4362. if (Result)
  4363. {
  4364. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4365. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4366. }
  4367. }
  4368. __finally
  4369. {
  4370. delete GroupList;
  4371. delete UserList;
  4372. }
  4373. }
  4374. else
  4375. {
  4376. DirView(Side)->DisplayPropertiesMenu();
  4377. Result = true;
  4378. }
  4379. return Result;
  4380. }
  4381. //---------------------------------------------------------------------------
  4382. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4383. {
  4384. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4385. {
  4386. FIgnoreNextDialogChar = Key;
  4387. }
  4388. Key = 0;
  4389. }
  4390. //---------------------------------------------------------------------------
  4391. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4392. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4393. {
  4394. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4395. if (Command != NULL)
  4396. {
  4397. KeyProcessed(Key, Shift);
  4398. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4399. {
  4400. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4401. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4402. false, false, const_cast<TCustomCommandType *>(Command));
  4403. }
  4404. }
  4405. }
  4406. //---------------------------------------------------------------------------
  4407. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4408. {
  4409. if (!NonVisualDataModule->Busy)
  4410. {
  4411. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4412. {
  4413. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4414. }
  4415. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4416. {
  4417. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4418. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4419. {
  4420. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4421. // But so far it's not a problem, as it does what we want.
  4422. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4423. if (((Action->ShortCut == KeyShortCut) ||
  4424. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4425. AllowedAction(Action, aaShortCut))
  4426. {
  4427. // Has to be called before the action as the dialog char is already in queue.
  4428. // So when the action consumes message queue, we already need to have the
  4429. // FIgnoreNextDialogChar set
  4430. KeyProcessed(Key, Shift);
  4431. // Reset reference to previous component (when menu/toolbar was clicked).
  4432. // Needed to detect that action was invoked by keyboard shortcut
  4433. // in TNonVisualDataModule::ExplorerActionsExecute
  4434. Action->ActionComponent = NULL;
  4435. Action->Execute();
  4436. return;
  4437. }
  4438. }
  4439. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4440. {
  4441. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4442. {
  4443. KeyProcessed(Key, Shift);
  4444. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4445. return;
  4446. }
  4447. }
  4448. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4449. {
  4450. KeyProcessed(Key, Shift);
  4451. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4452. }
  4453. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4454. if (IsCustomShortCut(CustomShortCut))
  4455. {
  4456. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4457. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4458. if (WinConfiguration->SharedBookmarks != NULL)
  4459. {
  4460. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4461. if ((Bookmark != NULL) &&
  4462. OpenBookmark(FCurrentSide, Bookmark))
  4463. {
  4464. KeyProcessed(Key, Shift);
  4465. }
  4466. }
  4467. }
  4468. }
  4469. }
  4470. TForm::KeyDown(Key, Shift);
  4471. }
  4472. //---------------------------------------------------------------------------
  4473. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4474. {
  4475. bool OpenedTerminal = false;
  4476. UnicodeString ProtocolName;
  4477. UnicodeString ProtocolNameHint;
  4478. UnicodeString SecurityProtocolName;
  4479. UnicodeString DurationHint;
  4480. // See the comment in TScpCommanderForm::UpdateControls()
  4481. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4482. if (ActiveTerminal != NULL)
  4483. {
  4484. // Active is not enough here
  4485. if (ActiveTerminal->Status == ssOpened)
  4486. {
  4487. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4488. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4489. if (FileSystemInfo.ProtocolName.IsEmpty())
  4490. {
  4491. ProtocolName = SessionInfo.ProtocolName;
  4492. }
  4493. else
  4494. {
  4495. ProtocolName = FileSystemInfo.ProtocolName;
  4496. }
  4497. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4498. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4499. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4500. OpenedTerminal = true;
  4501. }
  4502. else if (ActiveTerminal->Status > ssClosed)
  4503. {
  4504. ProtocolName = LoadStr(STATUS_CONNECTING);
  4505. }
  4506. else
  4507. {
  4508. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4509. }
  4510. }
  4511. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4512. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4513. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4514. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4515. if (ProtocolStatusPanel->Caption != ProtocolName)
  4516. {
  4517. ProtocolStatusPanel->Caption = ProtocolName;
  4518. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4519. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4520. }
  4521. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4522. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4523. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4524. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4525. SecurityStatusPanel->Enabled = SecurityEnabled;
  4526. UnicodeString SecurityProtocolHint;
  4527. if (SecurityEnabled)
  4528. {
  4529. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4530. }
  4531. else
  4532. {
  4533. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4534. }
  4535. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4536. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4537. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4538. DurationStatusPanel->Hint = DurationHint;
  4539. UpdateStatusBar();
  4540. }
  4541. //---------------------------------------------------------------------------
  4542. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4543. {
  4544. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4545. DebugAssert(SessionStatusBar != NULL);
  4546. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4547. if (!FNote.IsEmpty())
  4548. {
  4549. NoteStatusPanel->Caption = FNote;
  4550. }
  4551. else
  4552. {
  4553. UpdateStatusPanelText(NoteStatusPanel);
  4554. }
  4555. NoteStatusPanel->Hint = FNoteHints;
  4556. UnicodeString LoginTime;
  4557. // See the comment in TScpCommanderForm::UpdateControls()
  4558. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4559. // Active is not enough here
  4560. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4561. {
  4562. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4563. LoginTime = FormatDateTimeSpan(Configuration->TimeFormat, Now() - SessionInfo.LoginTime);
  4564. }
  4565. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4566. DurationStatusPanel->Caption = LoginTime;
  4567. }
  4568. //---------------------------------------------------------------------------
  4569. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4570. {
  4571. Panel->Caption = L"";
  4572. }
  4573. //---------------------------------------------------------------------------
  4574. void __fastcall TCustomScpExplorerForm::Idle()
  4575. {
  4576. if (FShowing ||
  4577. // Particularly for
  4578. // - Standalone editing
  4579. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4580. // while "keeping remote directory up to date".
  4581. StandaloneOperation)
  4582. {
  4583. FEditorManager->Check();
  4584. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4585. // that needs to know if queue view is visible (and it may be closed after queue update)
  4586. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4587. }
  4588. if (FShowing)
  4589. {
  4590. if (!NonVisualDataModule->Busy &&
  4591. // Menu is opened or drag&drop is going on
  4592. (Mouse->Capture == NULL))
  4593. {
  4594. if (FRefreshRemoteDirectory)
  4595. {
  4596. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4597. {
  4598. Terminal->RefreshDirectory();
  4599. }
  4600. FRefreshRemoteDirectory = false;
  4601. }
  4602. if (FRefreshLocalDirectory)
  4603. {
  4604. ReloadLocalDirectory();
  4605. FRefreshLocalDirectory = false;
  4606. }
  4607. if (WinConfiguration->RefreshRemotePanel)
  4608. {
  4609. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4610. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4611. {
  4612. RemoteDirView->ReloadDirectory();
  4613. }
  4614. }
  4615. }
  4616. }
  4617. if (FShowing || StandaloneOperation)
  4618. {
  4619. if (FQueueStatusInvalidated)
  4620. {
  4621. UpdateQueueStatus(false);
  4622. }
  4623. RefreshQueueItems();
  4624. }
  4625. if (FShowing)
  4626. {
  4627. UpdateStatusBar();
  4628. }
  4629. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4630. {
  4631. FClipboardFakeMonitorsPendingReset = false;
  4632. FClipboardFakeMonitors.reset(NULL);
  4633. }
  4634. FIgnoreNextDialogChar = 0;
  4635. }
  4636. //---------------------------------------------------------------------------
  4637. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4638. {
  4639. try
  4640. {
  4641. FUserActionTimer->Enabled = false;
  4642. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4643. {
  4644. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4645. {
  4646. FPendingQueueActionItem->ProcessUserAction();
  4647. }
  4648. }
  4649. }
  4650. __finally
  4651. {
  4652. FPendingQueueActionItem = NULL;
  4653. }
  4654. }
  4655. //---------------------------------------------------------------------------
  4656. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4657. {
  4658. if (WinConfiguration->MinimizeToTray)
  4659. {
  4660. UpdateTrayIcon();
  4661. FTrayIcon->Visible = true;
  4662. if (Visible)
  4663. {
  4664. ShowWindow(Handle, SW_HIDE);
  4665. }
  4666. }
  4667. }
  4668. //---------------------------------------------------------------------------
  4669. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4670. {
  4671. // WORKAROUND
  4672. // When restoring maximized window from minimization,
  4673. // rarely some controls do not align properly.
  4674. // Two instances seen (both for Commander):
  4675. // - When restoring, window is temporarily narrower (not maximized),
  4676. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4677. // Once maximized already, top dock shinks back, but the session PageControl,
  4678. // do not align up, leaving space between TopDock and PageControl.
  4679. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4680. for (int Index = 0; Index < ControlCount; Index++)
  4681. {
  4682. RealignControl(Controls[Index]);
  4683. }
  4684. if (FTrayIcon->Visible)
  4685. {
  4686. FTrayIcon->Visible = false;
  4687. if (Visible)
  4688. {
  4689. ShowWindow(Handle, SW_SHOW);
  4690. }
  4691. }
  4692. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4693. {
  4694. FNeedSession = false;
  4695. NonVisualDataModule->StartBusy();
  4696. try
  4697. {
  4698. NeedSession(true);
  4699. }
  4700. __finally
  4701. {
  4702. NonVisualDataModule->EndBusy();
  4703. }
  4704. }
  4705. }
  4706. //---------------------------------------------------------------------------
  4707. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4708. {
  4709. FTrayIcon->Hint = GetMainForm()->Caption;
  4710. }
  4711. //---------------------------------------------------------------------------
  4712. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4713. {
  4714. UpdateTrayIcon();
  4715. }
  4716. //---------------------------------------------------------------------------
  4717. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4718. {
  4719. // workaround
  4720. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4721. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4722. // But WM_ACTIVATEAPP message can be received even when
  4723. // the main window is minimized to the tray and internal editor window is focused
  4724. // (after another application was previously active)
  4725. if (::IsIconic(Handle))
  4726. {
  4727. if (!IsAppIconic())
  4728. {
  4729. SetAppIconic(true);
  4730. }
  4731. }
  4732. ::ApplicationRestore();
  4733. Application->BringToFront();
  4734. }
  4735. //---------------------------------------------------------------------------
  4736. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4737. {
  4738. RestoreApp();
  4739. }
  4740. //---------------------------------------------------------------------------
  4741. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4742. {
  4743. if (OpenInNewWindow())
  4744. {
  4745. ExecuteNewInstance(SessionUrl);
  4746. }
  4747. else
  4748. {
  4749. TTerminalManager::Instance()->NewSession(SessionUrl);
  4750. }
  4751. }
  4752. //---------------------------------------------------------------------------
  4753. void TCustomScpExplorerForm::NewTab(TOperationSide)
  4754. {
  4755. NewSession();
  4756. }
  4757. //---------------------------------------------------------------------------
  4758. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4759. {
  4760. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4761. StoredSessions->NewSession(SessionName, SessionData);
  4762. // modified only, explicit
  4763. StoredSessions->Save(false, true);
  4764. // encode session name because of slashes in hierarchical sessions
  4765. return EncodeUrlString(SessionName);
  4766. }
  4767. //---------------------------------------------------------------------------
  4768. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4769. {
  4770. // current working directories become defaults here, what is not right
  4771. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4772. return SaveHiddenDuplicateSession(SessionData.get());
  4773. }
  4774. //---------------------------------------------------------------------------
  4775. void __fastcall TCustomScpExplorerForm::DuplicateSession()
  4776. {
  4777. if (OpenInNewWindow())
  4778. {
  4779. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4780. }
  4781. else
  4782. {
  4783. // current working directories become defaults here, what is not right
  4784. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4785. TTerminalManager * Manager = TTerminalManager::Instance();
  4786. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4787. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4788. // We definitelly want these
  4789. ASession->Disconnected = ManagedSession->Disconnected;
  4790. // Not sure about these two
  4791. ASession->Permanent = ManagedSession->Permanent;
  4792. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  4793. Manager->ActiveSession = ASession;
  4794. }
  4795. }
  4796. //---------------------------------------------------------------------------
  4797. void __fastcall TCustomScpExplorerForm::RenameSession()
  4798. {
  4799. UnicodeString Name = ManagedSession->SessionData->SessionName;
  4800. if (InputDialog(LoadStr(RENAME_SESSION_TITLE), LoadStr(RENAME_SESSION_PROMPT), Name, HELP_SESSION_RENAME) &&
  4801. // When submitting the default name, do not fix it
  4802. (Name != ManagedSession->SessionData->SessionName))
  4803. {
  4804. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  4805. TSessionData::ValidateName(Name);
  4806. // This is inconsistent with how color (for example) is handled.
  4807. ManagedSession->SessionData->Name = Name;
  4808. UpdateControls();
  4809. // Add/Remove distinguishing paths from sessions of the same name.
  4810. SessionListChanged();
  4811. }
  4812. }
  4813. //---------------------------------------------------------------------------
  4814. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  4815. {
  4816. DebugAssert(Queue != NULL);
  4817. bool Result = Queue->IsEmpty;
  4818. if (!Result)
  4819. {
  4820. SetFocus();
  4821. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  4822. }
  4823. return Result;
  4824. }
  4825. //---------------------------------------------------------------------------
  4826. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  4827. {
  4828. return CanCloseQueue(FQueue);
  4829. }
  4830. //---------------------------------------------------------------------------
  4831. void __fastcall TCustomScpExplorerForm::CloseSession()
  4832. {
  4833. if (CanCloseQueue())
  4834. {
  4835. TTerminalManager::Instance()->FreeActiveTerminal();
  4836. }
  4837. }
  4838. //---------------------------------------------------------------------------
  4839. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  4840. {
  4841. if (CanCloseQueue())
  4842. {
  4843. TTerminalManager::Instance()->DisconnectActiveTerminal();
  4844. }
  4845. }
  4846. //---------------------------------------------------------------------------
  4847. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  4848. {
  4849. DetachTerminal(Terminal);
  4850. RemoteDirView->Terminal = Terminal;
  4851. UpdateRemotePathComboBox(false);
  4852. InitStatusBar();
  4853. UpdateControls();
  4854. }
  4855. //---------------------------------------------------------------------------
  4856. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  4857. {
  4858. InitStatusBar();
  4859. }
  4860. //---------------------------------------------------------------------------
  4861. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  4862. {
  4863. if (DebugAlwaysTrue(!Terminal->Active))
  4864. {
  4865. TTerminalManager::Instance()->ReconnectActiveTerminal();
  4866. }
  4867. }
  4868. //---------------------------------------------------------------------------
  4869. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  4870. {
  4871. if (OpenInNewWindow())
  4872. {
  4873. // encode session name because of slashes in hierarchical sessions
  4874. ExecuteNewInstance(EncodeUrlString(Data->Name));
  4875. }
  4876. else
  4877. {
  4878. TTerminalManager * Manager = TTerminalManager::Instance();
  4879. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  4880. Manager->ActiveSession = Terminal;
  4881. }
  4882. }
  4883. //---------------------------------------------------------------------------
  4884. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  4885. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  4886. {
  4887. TTerminalManager * Manager = TTerminalManager::Instance();
  4888. std::unique_ptr<TObjectList> DataList(new TObjectList());
  4889. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  4890. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  4891. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  4892. {
  4893. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  4894. // FirstSession can be null, if some of the
  4895. if (!ConnectFirstTerminal && (FirstSession != NULL))
  4896. {
  4897. FirstSession->Disconnected = true;
  4898. FirstSession->DisconnectedTemporarily = true;
  4899. }
  4900. Manager->ActiveSession = FirstSession;
  4901. }
  4902. }
  4903. //---------------------------------------------------------------------------
  4904. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  4905. {
  4906. if (OpenInNewWindow())
  4907. {
  4908. ExecuteNewInstance(Name);
  4909. }
  4910. else
  4911. {
  4912. DoOpenFolderOrWorkspace(Name, true, false);
  4913. }
  4914. }
  4915. //---------------------------------------------------------------------------
  4916. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  4917. bool &CanClose)
  4918. {
  4919. // See the comment in CloseApp()
  4920. if (NonVisualDataModule->Busy)
  4921. {
  4922. CanClose = false;
  4923. }
  4924. else
  4925. {
  4926. TTerminalManager * Manager = TTerminalManager::Instance();
  4927. int ActiveSessions = 0;
  4928. for (int Index = 0; Index < Manager->Count; Index++)
  4929. {
  4930. if (Manager->Sessions[Index]->Active)
  4931. {
  4932. ActiveSessions++;
  4933. }
  4934. }
  4935. // Confirm, when there's at least one active remote session or
  4936. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  4937. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  4938. WinConfiguration->ConfirmClosingSession)
  4939. {
  4940. unsigned int Result;
  4941. TMessageParams Params(mpNeverAskAgainCheck);
  4942. UnicodeString Message;
  4943. int Answers = qaOK | qaCancel;
  4944. // The current session is the only active session
  4945. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  4946. {
  4947. if (!WinConfiguration->AutoSaveWorkspace)
  4948. {
  4949. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  4950. }
  4951. else
  4952. {
  4953. Message = LoadStr(CLOSE_SESSION);
  4954. }
  4955. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  4956. }
  4957. // Multiple active sessions or one active session, but it's not the current one
  4958. else if (ActiveSessions > 0)
  4959. {
  4960. if (!WinConfiguration->AutoSaveWorkspace)
  4961. {
  4962. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  4963. }
  4964. else
  4965. {
  4966. Message = LoadStr(CLOSE_SESSIONS);
  4967. }
  4968. }
  4969. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  4970. else
  4971. {
  4972. DebugAlwaysTrue(Manager->Count > 1);
  4973. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  4974. Message = LoadStr(CLOSE_WORKSPACE);
  4975. }
  4976. UnicodeString Note;
  4977. if (WinConfiguration->AutoSaveWorkspace)
  4978. {
  4979. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  4980. }
  4981. else
  4982. {
  4983. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  4984. Answers = qaYes | qaNo | qaCancel;
  4985. }
  4986. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  4987. SetFocus();
  4988. Result = MessageDialog(Message, qtConfirmation,
  4989. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  4990. if (Result == qaNeverAskAgain)
  4991. {
  4992. WinConfiguration->ConfirmClosingSession = false;
  4993. }
  4994. if (Result == qaNo)
  4995. {
  4996. CanClose = SaveWorkspace(true);
  4997. // note that the workspace will be saved redundatly again from FormClose
  4998. }
  4999. else
  5000. {
  5001. CanClose =
  5002. (Result == qaOK) ||
  5003. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5004. (Result == qaNeverAskAgain);
  5005. }
  5006. }
  5007. if (CanClose && HasActiveTerminal())
  5008. {
  5009. CanClose = CanCloseQueue();
  5010. }
  5011. }
  5012. if (CanClose)
  5013. {
  5014. CanClose =
  5015. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5016. FEditorManager->CloseExternalFilesWithoutProcess();
  5017. if (CanClose)
  5018. {
  5019. while (CanClose && (FLocalEditors->Count > 0))
  5020. {
  5021. int PrevCount = FLocalEditors->Count;
  5022. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5023. CanClose = (FLocalEditors->Count < PrevCount);
  5024. }
  5025. if (CanClose)
  5026. {
  5027. CanClose = FEditorManager->Empty(true);
  5028. if (!CanClose)
  5029. {
  5030. SetFocus();
  5031. CanClose =
  5032. (MessageDialog(
  5033. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5034. }
  5035. }
  5036. }
  5037. }
  5038. }
  5039. //---------------------------------------------------------------------------
  5040. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5041. {
  5042. TForm * Form = dynamic_cast<TForm *>(Sender);
  5043. DebugAssert(Form != NULL);
  5044. Form->Close();
  5045. }
  5046. //---------------------------------------------------------------------------
  5047. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5048. {
  5049. TForm * Form = dynamic_cast<TForm *>(Sender);
  5050. delete Form;
  5051. }
  5052. //---------------------------------------------------------------------------
  5053. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5054. {
  5055. while (FLocalEditors->Count > 0)
  5056. {
  5057. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5058. }
  5059. }
  5060. //---------------------------------------------------------------------------
  5061. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5062. TObject *Sender)
  5063. {
  5064. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5065. try
  5066. {
  5067. SetProperties(osRemote, FileList);
  5068. }
  5069. __finally
  5070. {
  5071. delete FileList;
  5072. }
  5073. }
  5074. //---------------------------------------------------------------------------
  5075. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5076. {
  5077. if (value)
  5078. {
  5079. if (Component == fcCustomCommandsBand)
  5080. {
  5081. UpdateCustomCommandsToolbar();
  5082. }
  5083. if (Component == fcQueueFileList)
  5084. {
  5085. DebugAssert(!QueueFileListSplitter->Visible);
  5086. AdjustQueueLayout();
  5087. UpdateQueueFileList();
  5088. }
  5089. }
  5090. }
  5091. //---------------------------------------------------------------------------
  5092. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5093. {
  5094. int MinHeightLimit =
  5095. GetStaticQueuePanelComponentsHeight() +
  5096. QueueFileListSplitter->Height +
  5097. QueueFileList->Height +
  5098. GetMinQueueViewHeight();
  5099. if (QueuePanel->ClientHeight < MinHeightLimit)
  5100. {
  5101. QueuePanel->ClientHeight = MinHeightLimit;
  5102. }
  5103. }
  5104. //---------------------------------------------------------------------------
  5105. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5106. {
  5107. TControl * Control = GetComponent(Component);
  5108. DebugAssert(Control);
  5109. bool Changed = (Control->Visible != value);
  5110. if (Changed)
  5111. {
  5112. ComponentShowing(Component, value);
  5113. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5114. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5115. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5116. if (value)
  5117. {
  5118. int RemainingHeight = Control->Parent->ClientHeight;
  5119. int RemainingWidth = Control->Parent->ClientWidth;
  5120. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5121. {
  5122. TControl * ChildControl = Control->Parent->Controls[i];
  5123. if (ChildControl->Visible)
  5124. {
  5125. switch (ChildControl->Align)
  5126. {
  5127. case alTop:
  5128. case alBottom:
  5129. RemainingHeight -= ChildControl->Height;
  5130. break;
  5131. case alLeft:
  5132. case alRight:
  5133. RemainingWidth -= ChildControl->Width;
  5134. break;
  5135. }
  5136. }
  5137. }
  5138. int Reserve = ScaleByTextHeight(this, 32);
  5139. // queue in explorer, trees in commander
  5140. if (Control->Height > RemainingHeight - Reserve)
  5141. {
  5142. Control->Height = RemainingHeight / 2;
  5143. }
  5144. if (Control->Width > RemainingWidth - Reserve)
  5145. {
  5146. Control->Width = RemainingWidth / 2;
  5147. }
  5148. }
  5149. Control->Visible = value;
  5150. if (WasFocused && Visible)
  5151. {
  5152. DirView(osCurrent)->SetFocus();
  5153. }
  5154. FixControlsPlacement();
  5155. }
  5156. }
  5157. //---------------------------------------------------------------------------
  5158. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5159. {
  5160. TControl * Control = GetComponent(Component);
  5161. if (Control == NULL)
  5162. {
  5163. return false;
  5164. }
  5165. else
  5166. {
  5167. return Control->Visible;
  5168. }
  5169. }
  5170. //---------------------------------------------------------------------------
  5171. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5172. {
  5173. bool Result;
  5174. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5175. {
  5176. Result = !IsUWP();
  5177. }
  5178. else
  5179. {
  5180. Result = true;
  5181. }
  5182. return Result;
  5183. }
  5184. //---------------------------------------------------------------------------
  5185. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5186. {
  5187. if (DirView->ItemFocused != NULL)
  5188. {
  5189. DirView->ItemFocused->MakeVisible(false);
  5190. }
  5191. }
  5192. //---------------------------------------------------------------------------
  5193. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5194. {
  5195. MakeFocusedItemVisible(RemoteDirView);
  5196. QueueSplitter->Visible = QueuePanel->Visible;
  5197. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5198. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5199. TControl * TopControlsOrder[] =
  5200. { TopDock, MessageDock, SessionsPageControl };
  5201. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5202. TControl * QueueControlsOrder[] =
  5203. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5204. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5205. }
  5206. //---------------------------------------------------------------------------
  5207. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5208. {
  5209. switch (Component) {
  5210. case fcStatusBar: return RemoteStatusBar;
  5211. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5212. case fcQueueView: return QueuePanel;
  5213. case fcQueueToolbar: return QueueDock;
  5214. case fcRemoteTree: return RemoteDrivePanel;
  5215. case fcSessionsTabs: return SessionsPageControl;
  5216. case fcQueueFileList: return QueueFileList;
  5217. default: return NULL;
  5218. }
  5219. }
  5220. //---------------------------------------------------------------------------
  5221. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5222. TObject *Sender, TListColumn *Column, TPoint &Point)
  5223. {
  5224. DebugAssert(NonVisualDataModule && Column && Sender);
  5225. NonVisualDataModule->ListColumn = Column;
  5226. TPopupMenu * DirViewColumnMenu;
  5227. if (Sender == DirView(osOther))
  5228. {
  5229. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5230. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible =
  5231. (Column->Index == uvName);
  5232. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible =
  5233. (Column->Index == uvSize);
  5234. }
  5235. else
  5236. {
  5237. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5238. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible =
  5239. (Column->Index == dvName);
  5240. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible =
  5241. (Column->Index == dvSize);
  5242. }
  5243. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5244. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5245. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5246. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5247. }
  5248. //---------------------------------------------------------------------------
  5249. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5250. TObject *Sender, TListItem *Item, bool &AllowExec)
  5251. {
  5252. DoDirViewExecFile(Sender, Item, AllowExec);
  5253. }
  5254. //---------------------------------------------------------------------------
  5255. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5256. TListItem * Item, bool & AllowExec)
  5257. {
  5258. DebugAssert(Sender && Item && Configuration);
  5259. DebugAssert(AllowExec);
  5260. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5261. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5262. bool Remote = !IsSideLocalBrowser(Side);
  5263. DebugAssert(Item == ADirView->ItemFocused);
  5264. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5265. TResolvedDoubleClickAction Action;
  5266. if (FForceExecution)
  5267. {
  5268. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5269. }
  5270. else
  5271. {
  5272. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5273. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5274. }
  5275. if (Action == rdcaCopy)
  5276. {
  5277. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5278. UnlockWindow();
  5279. try
  5280. {
  5281. if (IsLocalBrowserMode())
  5282. {
  5283. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5284. }
  5285. else
  5286. {
  5287. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5288. }
  5289. }
  5290. __finally
  5291. {
  5292. LockWindow();
  5293. }
  5294. AllowExec = false;
  5295. }
  5296. else if (Action == rdcaEdit)
  5297. {
  5298. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5299. {
  5300. ExecuteFile(Side, efDefaultEditor);
  5301. AllowExec = false;
  5302. }
  5303. }
  5304. else if (Action == rdcaOpen)
  5305. {
  5306. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5307. {
  5308. ExecuteFile(osRemote, efShell);
  5309. AllowExec = false;
  5310. }
  5311. }
  5312. }
  5313. //---------------------------------------------------------------------------
  5314. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5315. {
  5316. return ((Side == osRemote) || (Side == osCurrent));
  5317. }
  5318. //---------------------------------------------------------------------------
  5319. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5320. {
  5321. DebugFail();
  5322. }
  5323. //---------------------------------------------------------------------------
  5324. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5325. {
  5326. DebugFail();
  5327. }
  5328. //---------------------------------------------------------------------------
  5329. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5330. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5331. {
  5332. TSynchronizeParamType Params;
  5333. Params.LocalDirectory = LocalDirectory;
  5334. Params.RemoteDirectory = RemoteDirectory;
  5335. int UnusedParams =
  5336. (GUIConfiguration->SynchronizeParams &
  5337. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5338. TTerminal::spCaseSensitive));
  5339. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5340. Params.Options = GUIConfiguration->SynchronizeOptions;
  5341. bool SaveSettings = false;
  5342. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5343. &DoSynchronizeTooManyDirectories);
  5344. DebugAssert(FSynchronizeController == NULL);
  5345. FSynchronizeController = &Controller;
  5346. bool Result;
  5347. try
  5348. {
  5349. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5350. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5351. int Options =
  5352. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5353. DebugAssert(FOnFeedSynchronizeError == NULL);
  5354. DebugAssert(FOnSynchronizeAbort == NULL);
  5355. DebugAssert(FSynchronizeTerminal == NULL);
  5356. FSynchronizeTerminal = Terminal;
  5357. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5358. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5359. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5360. if (Result)
  5361. {
  5362. if (SaveSettings)
  5363. {
  5364. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5365. GUIConfiguration->SynchronizeOptions = Params.Options;
  5366. }
  5367. else
  5368. {
  5369. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5370. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5371. FLAGSET(Params.Options, soSynchronize))
  5372. {
  5373. GUIConfiguration->SynchronizeOptions =
  5374. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5375. soSynchronize;
  5376. }
  5377. }
  5378. LocalDirectory = Params.LocalDirectory;
  5379. RemoteDirectory = Params.RemoteDirectory;
  5380. }
  5381. }
  5382. __finally
  5383. {
  5384. FSynchronizeController = NULL;
  5385. DebugAssert(FOnFeedSynchronizeError == NULL);
  5386. FOnFeedSynchronizeError = NULL;
  5387. DebugAssert(FOnSynchronizeAbort == NULL);
  5388. FOnSynchronizeAbort = NULL;
  5389. FSynchronizeTerminal = NULL;
  5390. }
  5391. return Result;
  5392. }
  5393. //---------------------------------------------------------------------------
  5394. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5395. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5396. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5397. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5398. TSynchronizeOptions * Options, bool Full)
  5399. {
  5400. // Keep-up-to-date mode
  5401. if (Terminal->Status == ssOpened)
  5402. {
  5403. try
  5404. {
  5405. int PParams = Params.Params;
  5406. if (!Full)
  5407. {
  5408. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5409. if (FLAGSET(Params.Options, soRecurse))
  5410. {
  5411. PParams |= TTerminal::spSubDirs;
  5412. }
  5413. }
  5414. else
  5415. {
  5416. // if keepuptodate is non-recursive,
  5417. // full sync before has to be non-recursive as well
  5418. if (FLAGCLEAR(Params.Options, soRecurse))
  5419. {
  5420. PParams |= TTerminal::spNoRecurse;
  5421. }
  5422. }
  5423. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5424. PParams, Checklist, Options);
  5425. }
  5426. catch (Exception & E)
  5427. {
  5428. if (!Terminal->Active)
  5429. {
  5430. ShowExtendedExceptionEx(Terminal, &E);
  5431. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5432. if (!Terminal->Active)
  5433. {
  5434. throw;
  5435. }
  5436. }
  5437. else
  5438. {
  5439. if (FLAGSET(Params.Options, soContinueOnError) &&
  5440. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5441. {
  5442. // noop, already logged in MoreMessageDialog
  5443. }
  5444. else
  5445. {
  5446. // We get mostly EAbort here, so this is noop.
  5447. // Exception is an error when listing directories while looking for differences.
  5448. ShowExtendedExceptionEx(Terminal, &E);
  5449. throw;
  5450. }
  5451. }
  5452. }
  5453. }
  5454. }
  5455. //---------------------------------------------------------------------------
  5456. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5457. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5458. const UnicodeString ErrorStr)
  5459. {
  5460. if (!Directory.IsEmpty())
  5461. {
  5462. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5463. }
  5464. else
  5465. {
  5466. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5467. }
  5468. }
  5469. //---------------------------------------------------------------------------
  5470. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5471. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5472. {
  5473. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5474. {
  5475. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5476. }
  5477. else
  5478. {
  5479. TMessageParams Params(mpNeverAskAgainCheck);
  5480. unsigned int Result = MessageDialog(
  5481. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5482. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5483. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5484. {
  5485. MaxDirectories *= 2;
  5486. if (Result == qaNeverAskAgain)
  5487. {
  5488. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5489. }
  5490. }
  5491. else
  5492. {
  5493. Abort();
  5494. }
  5495. }
  5496. }
  5497. //---------------------------------------------------------------------------
  5498. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5499. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5500. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5501. TSynchronizeOptions * Options)
  5502. {
  5503. // Keep-up-to-date mode
  5504. DebugAssert(!FAutoOperation);
  5505. void * BatchStorage;
  5506. BatchStart(BatchStorage);
  5507. FAutoOperation = true;
  5508. bool AnyOperation = false;
  5509. TDateTime StartTime = Now();
  5510. TSynchronizeChecklist * AChecklist = NULL;
  5511. try
  5512. {
  5513. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5514. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5515. {
  5516. FSynchronizeProgressForm->Start();
  5517. }
  5518. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5519. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5520. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5521. Options);
  5522. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5523. SAFE_DESTROY(FSynchronizeProgressForm);
  5524. AnyOperation = (AChecklist->CheckedCount > 0);
  5525. if (AnyOperation)
  5526. {
  5527. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5528. CreateProgressForm(&SynchronizeProgress);
  5529. try
  5530. {
  5531. Terminal->SynchronizeApply(
  5532. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5533. SynchronizeProcessedItem, NULL, NULL, NULL);
  5534. }
  5535. __finally
  5536. {
  5537. DestroyProgressForm();
  5538. }
  5539. }
  5540. }
  5541. __finally
  5542. {
  5543. if (Checklist == NULL)
  5544. {
  5545. delete AChecklist;
  5546. }
  5547. else
  5548. {
  5549. *Checklist = AChecklist;
  5550. }
  5551. FAutoOperation = false;
  5552. SAFE_DESTROY(FSynchronizeProgressForm);
  5553. BatchEnd(BatchStorage);
  5554. ReloadLocalDirectory();
  5555. if (AnyOperation)
  5556. {
  5557. OperationComplete(StartTime);
  5558. }
  5559. }
  5560. }
  5561. //---------------------------------------------------------------------------
  5562. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5563. {
  5564. // can be called from command line
  5565. return Visible &&
  5566. ((DirView(osRemote)->SelCount > 0) ||
  5567. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5568. }
  5569. //---------------------------------------------------------------------------
  5570. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5571. {
  5572. LogSynchronizeEvent(Terminal, Message);
  5573. }
  5574. //---------------------------------------------------------------------------
  5575. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5576. int Params, TSynchronizeOptions & Options)
  5577. {
  5578. DebugAssert(!IsLocalBrowserMode());
  5579. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5580. {
  5581. Options.Filter = new TStringList();
  5582. Options.Filter->CaseSensitive = false;
  5583. Options.Filter->Duplicates = Types::dupAccept;
  5584. if (DirView(osRemote)->SelCount > 0)
  5585. {
  5586. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5587. }
  5588. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5589. {
  5590. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5591. }
  5592. Options.Filter->Sort();
  5593. }
  5594. }
  5595. //---------------------------------------------------------------------------
  5596. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5597. {
  5598. TCopyParamType Defaults;
  5599. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5600. ConfigStorage->AccessMode = smRead;
  5601. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5602. {
  5603. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5604. }
  5605. ConfigStorage.reset(NULL);
  5606. std::unique_ptr<TStringList> Options(new TStringList());
  5607. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5608. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5609. UnicodeString Result;
  5610. if (Options->Count > 0)
  5611. {
  5612. Result =
  5613. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5614. }
  5615. return Result;
  5616. }
  5617. //---------------------------------------------------------------------------
  5618. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5619. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5620. {
  5621. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5622. UnicodeString AdditionalParams =
  5623. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5624. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5625. SerializeCopyParamForCommandLine(CopyParams),
  5626. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5627. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5628. ExecuteNewInstance(SessionName, AdditionalParams);
  5629. }
  5630. //---------------------------------------------------------------------------
  5631. struct TSynchronizeParams
  5632. {
  5633. UnicodeString LocalDirectory;
  5634. UnicodeString RemoteDirectory;
  5635. TSynchronizeMode Mode;
  5636. TSynchronizeChecklist * Checklist;
  5637. int Params;
  5638. TCopyParamType * CopyParam;
  5639. TDateTime CollectElapsed;
  5640. TDateTime * StartTime;
  5641. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5642. };
  5643. //---------------------------------------------------------------------------
  5644. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5645. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5646. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5647. {
  5648. DebugAssert(!FAutoOperation);
  5649. void * BatchStorage;
  5650. BatchStart(BatchStorage);
  5651. FAutoOperation = true;
  5652. TFileOperationStatistics Statistics;
  5653. TDateTime Start = Now();
  5654. try
  5655. {
  5656. Params.OnProcessedItem = OnProcessedItem;
  5657. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5658. CreateProgressForm(&SynchronizeProgress);
  5659. Terminal->SynchronizeApply(
  5660. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5661. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5662. &Statistics);
  5663. }
  5664. __finally
  5665. {
  5666. Params.OnProcessedItem = NULL;
  5667. FAutoOperation = false;
  5668. DestroyProgressForm();
  5669. BatchEnd(BatchStorage);
  5670. ReloadLocalDirectory();
  5671. }
  5672. if (WinConfiguration->SynchronizeSummary)
  5673. {
  5674. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5675. // The statistics should be 0 anyway in this case
  5676. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5677. {
  5678. Message += L"\n";
  5679. if (Statistics.FilesUploaded > 0)
  5680. {
  5681. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5682. }
  5683. if (Statistics.FilesDownloaded > 0)
  5684. {
  5685. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5686. }
  5687. if (Statistics.FilesDeletedLocal > 0)
  5688. {
  5689. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5690. }
  5691. if (Statistics.FilesDeletedRemote > 0)
  5692. {
  5693. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5694. }
  5695. }
  5696. TDateTime Elapsed = (Now() - Start);
  5697. Message +=
  5698. L"\n" +
  5699. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Configuration->TimeFormat, Params.CollectElapsed))) + L"\n" +
  5700. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Configuration->TimeFormat, Elapsed)));
  5701. TMessageParams Params(mpNeverAskAgainCheck);
  5702. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5703. if (Result == qaNeverAskAgain)
  5704. {
  5705. WinConfiguration->SynchronizeSummary = false;
  5706. }
  5707. }
  5708. }
  5709. //---------------------------------------------------------------------------
  5710. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5711. {
  5712. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5713. {
  5714. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5715. }
  5716. // Not set in keep-up-to-date mode - Synchronize() method
  5717. if (Token != NULL)
  5718. {
  5719. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5720. if (Params.OnProcessedItem != NULL)
  5721. {
  5722. Params.OnProcessedItem(NULL, ChecklistItem);
  5723. }
  5724. }
  5725. }
  5726. //---------------------------------------------------------------------------
  5727. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5728. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5729. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5730. {
  5731. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5732. *Params.StartTime = Now();
  5733. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5734. }
  5735. //---------------------------------------------------------------------------
  5736. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5737. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5738. {
  5739. // terminal can be already closed (e.g. dropped connection)
  5740. if (Terminal != NULL)
  5741. {
  5742. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5743. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5744. }
  5745. }
  5746. //---------------------------------------------------------------------------
  5747. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5748. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5749. {
  5750. DebugAssert(!IsLocalBrowserMode());
  5751. TAutoBatch AutoBatch(this);
  5752. TAutoFlag AutoOperationFlag(FAutoOperation);
  5753. if (Side == osRemote)
  5754. {
  5755. std::unique_ptr<TStrings> FileList(new TStringList());
  5756. FileList->AddObject(FileName, RemoteFile);
  5757. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5758. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5759. RemoteDirView->SaveSelection();
  5760. RemoteDirView->SaveSelectedNames();
  5761. try
  5762. {
  5763. Terminal->MoveFiles(FileList.get(), Target, FileMask);
  5764. }
  5765. catch(...)
  5766. {
  5767. RemoteDirView->DiscardSavedSelection();
  5768. throw;
  5769. }
  5770. RemoteDirView->RestoreSelection();
  5771. }
  5772. else if (DebugAlwaysTrue(Side == osLocal))
  5773. {
  5774. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5775. {
  5776. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5777. }
  5778. UnicodeString Directory = ExtractFileDir(FileName);
  5779. ReloadLocalDirectory(Directory);
  5780. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5781. if (!SamePaths(Directory, NewDirectory))
  5782. {
  5783. ReloadLocalDirectory(NewDirectory);
  5784. }
  5785. }
  5786. }
  5787. //---------------------------------------------------------------------------
  5788. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  5789. {
  5790. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  5791. if (Side == osLocal)
  5792. {
  5793. if (Action == TSynchronizeChecklist::saDownloadNew)
  5794. {
  5795. OpenFolderInExplorer(LocalPath);
  5796. }
  5797. else
  5798. {
  5799. OpenFileInExplorer(TPath::Combine(LocalPath, Item->GetFileName()));
  5800. }
  5801. }
  5802. else if (DebugAlwaysTrue(Side == osRemote))
  5803. {
  5804. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  5805. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5806. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  5807. if (!LocalPath.IsEmpty())
  5808. {
  5809. SessionData->LocalDirectory = LocalPath;
  5810. }
  5811. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  5812. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  5813. }
  5814. }
  5815. //---------------------------------------------------------------------------
  5816. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  5817. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  5818. const TCopyParamType * CopyParams)
  5819. {
  5820. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5821. UnicodeString AdditionalParams =
  5822. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5823. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5824. SerializeCopyParamForCommandLine(CopyParams),
  5825. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  5826. LocalDirectory, RemoteDirectory, Mode, Params));
  5827. ExecuteNewInstance(SessionName, AdditionalParams);
  5828. }
  5829. //---------------------------------------------------------------------------
  5830. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  5831. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  5832. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  5833. {
  5834. int Result;
  5835. bool SaveSettings = false;
  5836. int Options =
  5837. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  5838. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  5839. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5840. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  5841. bool Continue =
  5842. (UseDefaults == 0) ||
  5843. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  5844. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults);
  5845. if (Continue)
  5846. {
  5847. Configuration->Usage->Inc(L"Synchronizations");
  5848. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  5849. UpdateCopyParamCounters(CopyParam);
  5850. TSynchronizeOptions SynchronizeOptions;
  5851. GetSynchronizeOptions(Params, SynchronizeOptions);
  5852. if (SaveSettings)
  5853. {
  5854. GUIConfiguration->SynchronizeParams = Params;
  5855. }
  5856. else
  5857. {
  5858. SaveMode = false;
  5859. }
  5860. TDateTime StartTime = Now();
  5861. TSynchronizeChecklist * Checklist = NULL;
  5862. try
  5863. {
  5864. DebugAssert(!FAutoOperation);
  5865. FAutoOperation = true;
  5866. try
  5867. {
  5868. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  5869. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  5870. int Files = -1;
  5871. if (DataList->Count >= 1)
  5872. {
  5873. Files = StrToIntDef(DataList->Strings[0], Files);
  5874. }
  5875. else
  5876. {
  5877. DataList->Add(UnicodeString());
  5878. }
  5879. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  5880. FSynchronizeProgressForm->Start();
  5881. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5882. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5883. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5884. &SynchronizeOptions);
  5885. if (Terminal->SessionData->CacheDirectories)
  5886. {
  5887. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  5888. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  5889. }
  5890. }
  5891. __finally
  5892. {
  5893. FAutoOperation = false;
  5894. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5895. SAFE_DESTROY(FSynchronizeProgressForm);
  5896. }
  5897. TSynchronizeParams SynchronizeParams;
  5898. SynchronizeParams.LocalDirectory = LocalDirectory;
  5899. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  5900. SynchronizeParams.Mode = Mode;
  5901. SynchronizeParams.CopyParam = &CopyParam;
  5902. SynchronizeParams.Params = Params;
  5903. SynchronizeParams.Checklist = Checklist;
  5904. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  5905. SynchronizeParams.StartTime = &StartTime;
  5906. SynchronizeParams.OnProcessedItem = NULL;
  5907. Result = Checklist->Count;
  5908. if (Checklist->Count > 0)
  5909. {
  5910. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  5911. {
  5912. if (!DoSynchronizeChecklistDialog(
  5913. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  5914. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  5915. {
  5916. Result = -1;
  5917. }
  5918. }
  5919. else
  5920. {
  5921. FullSynchronize(SynchronizeParams, NULL, NULL);
  5922. }
  5923. }
  5924. else
  5925. {
  5926. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  5927. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  5928. }
  5929. }
  5930. __finally
  5931. {
  5932. delete Checklist;
  5933. }
  5934. OperationComplete(StartTime);
  5935. }
  5936. else
  5937. {
  5938. Result = -1;
  5939. }
  5940. return Result;
  5941. }
  5942. //---------------------------------------------------------------------------
  5943. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  5944. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  5945. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  5946. {
  5947. if (Collect)
  5948. {
  5949. DebugAssert(FSynchronizeProgressForm != NULL);
  5950. if (!FSynchronizeProgressForm->Started)
  5951. {
  5952. FSynchronizeProgressForm->Start();
  5953. }
  5954. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  5955. SetTaskbarListProgressValue(CompareProgress);
  5956. }
  5957. else
  5958. {
  5959. DebugAssert(FSynchronizeProgressForm == NULL);
  5960. DebugAssert(FProgressForm != NULL);
  5961. }
  5962. }
  5963. //---------------------------------------------------------------------------
  5964. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  5965. {
  5966. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  5967. TRemoteFile * File = NULL;
  5968. Terminal->ReadFile(FullFileName, File);
  5969. if (File != NULL)
  5970. {
  5971. std::unique_ptr<TRemoteFile> FileOwner(File);
  5972. ExecuteRemoteFile(FullFileName, File, efInternalEditor);
  5973. Application->ShowMainForm = false;
  5974. Application->Run();
  5975. }
  5976. }
  5977. //---------------------------------------------------------------------------
  5978. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  5979. {
  5980. DebugFail();
  5981. }
  5982. //---------------------------------------------------------------------------
  5983. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  5984. {
  5985. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  5986. SessionData->Assign(ManagedSession->SessionData);
  5987. UpdateSessionData(SessionData.get());
  5988. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  5989. if (IsActiveTerminal(ManagedSession))
  5990. {
  5991. ManagedSession->UpdateSessionCredentials(SessionData.get());
  5992. }
  5993. if (!ManagedSession->SessionData->HasSessionName())
  5994. {
  5995. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  5996. // once IsWorkspace is cleared
  5997. SessionData->Name = UnicodeString();
  5998. }
  5999. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6000. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6001. SessionData->IsWorkspace = false;
  6002. return SessionData.release();
  6003. }
  6004. //---------------------------------------------------------------------------
  6005. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6006. {
  6007. TSessionData * SessionData = CloneCurrentSessionData();
  6008. try
  6009. {
  6010. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6011. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6012. }
  6013. __finally
  6014. {
  6015. delete SessionData;
  6016. }
  6017. }
  6018. //---------------------------------------------------------------------------
  6019. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6020. {
  6021. TTerminalManager * Manager = TTerminalManager::Instance();
  6022. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6023. if (DebugAlwaysTrue(ManagedSession != NULL))
  6024. {
  6025. // Update ManagedSession->StateData
  6026. UpdateSession(ManagedSession);
  6027. }
  6028. Manager->SaveWorkspace(DataList.get());
  6029. return DataList.release();
  6030. }
  6031. //---------------------------------------------------------------------------
  6032. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6033. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6034. {
  6035. WinConfiguration->LastWorkspace = Name;
  6036. if (!SavePasswords)
  6037. {
  6038. for (int Index = 0; Index < DataList->Count; Index++)
  6039. {
  6040. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6041. if (SessionData->Link.IsEmpty())
  6042. {
  6043. SessionData->ClearSessionPasswords();
  6044. }
  6045. }
  6046. }
  6047. StoredSessions->NewWorkspace(Name, DataList);
  6048. // modified only
  6049. StoredSessions->Save(false, Explicit);
  6050. }
  6051. //---------------------------------------------------------------------------
  6052. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6053. {
  6054. return
  6055. DefaultStr(WinConfiguration->LastWorkspace,
  6056. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6057. }
  6058. //---------------------------------------------------------------------------
  6059. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6060. {
  6061. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6062. bool AnyNonStoredSessionWithPassword = false;
  6063. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6064. bool AllNonStoredSessionsAnonymous = true;
  6065. TTerminalManager * Manager = TTerminalManager::Instance();
  6066. for (int Index = 0; Index < DataList->Count; Index++)
  6067. {
  6068. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6069. if (SessionData->Link.IsEmpty())
  6070. {
  6071. if (SessionData->HasAnySessionPassword())
  6072. {
  6073. AnyNonStoredSessionWithPassword = true;
  6074. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6075. {
  6076. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6077. }
  6078. }
  6079. if (!SameText(SessionData->UserName, AnonymousUserName))
  6080. {
  6081. AllNonStoredSessionsAnonymous = false;
  6082. }
  6083. }
  6084. }
  6085. bool SavePasswords;
  6086. bool * PSavePasswords;
  6087. bool NotRecommendedSavingPasswords =
  6088. !CustomWinConfiguration->UseMasterPassword &&
  6089. !AllNonStoredSessionsAnonymous;
  6090. if (Configuration->DisablePasswordStoring ||
  6091. !AnyNonStoredSessionWithPassword)
  6092. {
  6093. PSavePasswords = NULL;
  6094. SavePasswords = false;
  6095. }
  6096. else
  6097. {
  6098. PSavePasswords = &SavePasswords;
  6099. SavePasswords =
  6100. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6101. !NotRecommendedSavingPasswords;
  6102. }
  6103. UnicodeString Name = WorkspaceName();
  6104. bool CreateShortcut = false;
  6105. bool Result =
  6106. DoSaveWorkspaceDialog(
  6107. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6108. EnableAutoSave);
  6109. if (Result)
  6110. {
  6111. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6112. if (CreateShortcut)
  6113. {
  6114. TOperationVisualizer Visualizer;
  6115. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6116. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6117. }
  6118. if (EnableAutoSave)
  6119. {
  6120. WinConfiguration->AutoSaveWorkspace = true;
  6121. WinConfiguration->AutoWorkspace = Name;
  6122. if (PSavePasswords != NULL)
  6123. {
  6124. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6125. }
  6126. }
  6127. }
  6128. return Result;
  6129. }
  6130. //---------------------------------------------------------------------------
  6131. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6132. {
  6133. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6134. DebugAssert(Session == ManagedSession);
  6135. if (!IsLocalBrowserMode())
  6136. {
  6137. SAFE_DESTROY(Session->RemoteExplorerState);
  6138. if (WinConfiguration->PreservePanelState)
  6139. {
  6140. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6141. }
  6142. }
  6143. UpdateSessionData(Session->StateData);
  6144. }
  6145. //---------------------------------------------------------------------------
  6146. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6147. {
  6148. // Keep in sync with TSessionData::CopyStateData
  6149. DebugAssert(Data != NULL);
  6150. // This is inconsistent with how color (for example) is handled.
  6151. Data->Name = ManagedSession->SessionData->Name;
  6152. if (!IsLocalBrowserMode())
  6153. {
  6154. // cannot use RemoteDirView->Path, because it is empty if connection
  6155. // was already closed
  6156. // also only peek, we may not be connected at all atm
  6157. // so make sure we do not try retrieving current directory from the server
  6158. // (particularly with FTP)
  6159. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6160. if (!ACurrentDirectory.IsEmpty())
  6161. {
  6162. Data->RemoteDirectory = ACurrentDirectory;
  6163. }
  6164. }
  6165. Data->Color = SessionColor;
  6166. }
  6167. //---------------------------------------------------------------------------
  6168. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6169. {
  6170. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6171. DebugAssert(Toolbar != NULL);
  6172. for (int i = 0; i < Toolbar->Items->Count; i++)
  6173. {
  6174. TTBXCustomDropDownItem * DropDownItem;
  6175. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6176. if (DropDownItem != NULL)
  6177. {
  6178. ToolbarItemResize(DropDownItem,
  6179. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6180. Toolbar->NonClientWidth);
  6181. break;
  6182. }
  6183. }
  6184. }
  6185. //---------------------------------------------------------------------------
  6186. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6187. {
  6188. Item->EditWidth = Width;
  6189. }
  6190. //---------------------------------------------------------------------------
  6191. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6192. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6193. {
  6194. for (int i = 0; i < Toolbar->Items->Count; i++)
  6195. {
  6196. TTBXCustomDropDownItem * DropDownItem;
  6197. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6198. if (DropDownItem != NULL)
  6199. {
  6200. ASize.x -= DropDownItem->EditWidth;
  6201. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6202. }
  6203. }
  6204. }
  6205. //---------------------------------------------------------------------------
  6206. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6207. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6208. {
  6209. if (WinConfiguration->DDWarnLackOfTempSpace)
  6210. {
  6211. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6212. if (!ADrive.IsEmpty())
  6213. {
  6214. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6215. DebugAssert(RequiredSpace >= 0);
  6216. __int64 RequiredWithReserve;
  6217. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6218. if (FreeSpace < RequiredWithReserve)
  6219. {
  6220. unsigned int Result;
  6221. TMessageParams Params(mpNeverAskAgainCheck);
  6222. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6223. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6224. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6225. if (Result == qaNeverAskAgain)
  6226. {
  6227. WinConfiguration->DDWarnLackOfTempSpace = false;
  6228. }
  6229. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6230. }
  6231. }
  6232. }
  6233. }
  6234. //---------------------------------------------------------------------------
  6235. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6236. {
  6237. DoOpenDirectoryDialog(odAddBookmark, Side);
  6238. }
  6239. //---------------------------------------------------------------------------
  6240. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6241. {
  6242. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6243. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6244. try
  6245. {
  6246. TCustomDirView * DView = DirView(Side);
  6247. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6248. {
  6249. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6250. }
  6251. }
  6252. catch (...)
  6253. {
  6254. delete VisitedDirectories;
  6255. throw;
  6256. }
  6257. return VisitedDirectories;
  6258. }
  6259. //---------------------------------------------------------------------------
  6260. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6261. TOpenDirectoryMode Mode, TOperationSide Side)
  6262. {
  6263. bool Continue = true;
  6264. if (Mode == odAddBookmark)
  6265. {
  6266. TMessageParams Params(mpNeverAskAgainCheck);
  6267. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6268. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6269. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6270. unsigned int Answer =
  6271. MessageDialog(Message,
  6272. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6273. if (Answer == qaNeverAskAgain)
  6274. {
  6275. Continue = true;
  6276. WinConfiguration->UseSharedBookmarks = true;
  6277. }
  6278. else if (Answer == qaOK)
  6279. {
  6280. Continue = true;
  6281. WinConfiguration->UseSharedBookmarks = false;
  6282. }
  6283. else
  6284. {
  6285. Continue = false;
  6286. }
  6287. }
  6288. if (Continue)
  6289. {
  6290. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6291. try
  6292. {
  6293. UnicodeString Name = DirView(Side)->PathName;
  6294. bool Repeat;
  6295. do
  6296. {
  6297. Repeat = false;
  6298. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6299. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6300. // do not allow switching to location profiles,
  6301. // if we are not connected
  6302. HasDirView[osLocal] && (Terminal != NULL)))
  6303. {
  6304. TWindowLock Lock(this);
  6305. if (!TryOpenDirectory(Side, Name))
  6306. {
  6307. Repeat = true;
  6308. Mode = odBrowse;
  6309. }
  6310. }
  6311. }
  6312. while (Repeat);
  6313. }
  6314. __finally
  6315. {
  6316. delete VisitedDirectories;
  6317. }
  6318. }
  6319. }
  6320. //---------------------------------------------------------------------------
  6321. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6322. {
  6323. DebugAssert(!Terminal->CommandSessionOpened);
  6324. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6325. }
  6326. //---------------------------------------------------------------------------
  6327. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6328. {
  6329. bool Result = Terminal->IsCapable[Capability] ||
  6330. Terminal->CommandSessionOpened;
  6331. if (!Result)
  6332. {
  6333. DebugAssert(Terminal->IsCapable[fcSecondaryShell]);
  6334. if (!GUIConfiguration->ConfirmCommandSession)
  6335. {
  6336. Result = true;
  6337. }
  6338. else
  6339. {
  6340. TMessageParams Params(mpNeverAskAgainCheck);
  6341. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6342. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6343. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6344. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6345. if (Answer == qaNeverAskAgain)
  6346. {
  6347. GUIConfiguration->ConfirmCommandSession = false;
  6348. Result = true;
  6349. }
  6350. else if (Answer == qaOK)
  6351. {
  6352. Result = true;
  6353. }
  6354. }
  6355. if (Result)
  6356. {
  6357. Result = CommandSessionFallback();
  6358. }
  6359. }
  6360. return Result;
  6361. }
  6362. //---------------------------------------------------------------------------
  6363. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6364. {
  6365. if (EnsureCommandSessionFallback(fcAnyCommand))
  6366. {
  6367. DoConsoleDialog(Terminal, Command);
  6368. }
  6369. }
  6370. //---------------------------------------------------------------------------
  6371. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6372. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6373. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6374. {
  6375. if (!IsSideLocalBrowser(osRemote) &&
  6376. IsFileControl(DropSourceControl, osRemote) &&
  6377. (FDDExtMapFile != NULL))
  6378. {
  6379. Accept = true;
  6380. }
  6381. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6382. DebugAssert(FDDTargetControl != NULL);
  6383. }
  6384. //---------------------------------------------------------------------------
  6385. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6386. _di_IDataObject DataObj, int KeyState,
  6387. const TPoint & Point, int & Effect, bool & Accept)
  6388. {
  6389. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6390. }
  6391. //---------------------------------------------------------------------------
  6392. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6393. _di_IDataObject DataObj, int KeyState,
  6394. const TPoint & Point, int & Effect, bool & Accept)
  6395. {
  6396. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6397. }
  6398. //---------------------------------------------------------------------------
  6399. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6400. TObject * Sender)
  6401. {
  6402. DebugUsedParam(Sender);
  6403. DebugAssert(FDDTargetControl == Sender);
  6404. FDDTargetControl = NULL;
  6405. }
  6406. //---------------------------------------------------------------------------
  6407. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6408. {
  6409. FileControlDDDragLeave(SessionsPageControl);
  6410. }
  6411. //---------------------------------------------------------------------------
  6412. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6413. {
  6414. FileControlDDDragLeave(QueueView3);
  6415. }
  6416. //---------------------------------------------------------------------------
  6417. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6418. {
  6419. DebugAssert(!IsSideLocalBrowser(Side));
  6420. DebugUsedParam(Side);
  6421. bool Edit = false;
  6422. TRemoteFile * File = NULL;
  6423. UnicodeString FileName;
  6424. UnicodeString PointTo;
  6425. bool SymbolicLink = true;
  6426. if (RemoteDirView->ItemFocused)
  6427. {
  6428. DebugAssert(RemoteDirView->ItemFocused->Data);
  6429. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6430. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6431. if (Edit)
  6432. {
  6433. FileName = File->FileName;
  6434. PointTo = File->LinkTo;
  6435. }
  6436. else if (!File->IsParentDirectory)
  6437. {
  6438. PointTo = File->FileName;
  6439. }
  6440. }
  6441. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6442. Terminal->IsCapable[fcHardLink]))
  6443. {
  6444. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6445. if (Edit)
  6446. {
  6447. DebugAssert(File->FileName == FileName);
  6448. int Params = dfNoRecursive;
  6449. Terminal->ExceptionOnFail = true;
  6450. try
  6451. {
  6452. Terminal->DeleteFile(L"", File, &Params);
  6453. }
  6454. __finally
  6455. {
  6456. Terminal->ExceptionOnFail = false;
  6457. }
  6458. }
  6459. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6460. }
  6461. }
  6462. //---------------------------------------------------------------------------
  6463. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6464. {
  6465. return
  6466. (IsSideLocalBrowser(Side) ||
  6467. (HasActiveTerminal() &&
  6468. Terminal->ResolvingSymlinks &&
  6469. Terminal->IsCapable[fcSymbolicLink]));
  6470. }
  6471. //---------------------------------------------------------------------------
  6472. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6473. {
  6474. return
  6475. !IsSideLocalBrowser(FCurrentSide) &&
  6476. (RemoteDirView->ItemFocused != NULL) &&
  6477. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6478. Terminal->SessionData->ResolveSymlinks;
  6479. }
  6480. //---------------------------------------------------------------------------
  6481. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6482. {
  6483. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6484. FForceExecution = true;
  6485. try
  6486. {
  6487. DirView(osCurrent)->ExecuteCurrentFile();
  6488. }
  6489. __finally
  6490. {
  6491. FForceExecution = false;
  6492. }
  6493. }
  6494. //---------------------------------------------------------------------------
  6495. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6496. {
  6497. TEditorData ExternalEditor;
  6498. ExternalEditor.Editor = edExternal;
  6499. bool Remember = false;
  6500. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6501. {
  6502. if (Remember)
  6503. {
  6504. TEditorList * EditorList = new TEditorList;
  6505. try
  6506. {
  6507. *EditorList = *WinConfiguration->EditorList;
  6508. bool Found = false;
  6509. int i = 0;
  6510. while (!Found && (i < EditorList->Count))
  6511. {
  6512. const TEditorPreferences * Editor = EditorList->Editors[i];
  6513. if ((Editor->Data->Editor == edExternal) &&
  6514. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6515. {
  6516. Found = true;
  6517. }
  6518. i++;
  6519. }
  6520. if (!Found)
  6521. {
  6522. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6523. WinConfiguration->EditorList = EditorList;
  6524. }
  6525. }
  6526. __finally
  6527. {
  6528. delete EditorList;
  6529. }
  6530. }
  6531. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6532. }
  6533. }
  6534. //---------------------------------------------------------------------------
  6535. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6536. {
  6537. FEditorManager->ProcessFiles(FileTerminalRemoved, ATerminal);
  6538. if (FFileFindTerminal == ATerminal)
  6539. {
  6540. FFileFindTerminal = NULL;
  6541. HideFileFindDialog();
  6542. }
  6543. if (FClipboardTerminal == ATerminal)
  6544. {
  6545. ClipboardClear(); // implies ClipboardStop
  6546. }
  6547. if ((FOnSynchronizeAbort != NULL) &&
  6548. (ATerminal == FManagedSession))
  6549. {
  6550. FOnSynchronizeAbort(NULL);
  6551. }
  6552. }
  6553. //---------------------------------------------------------------------------
  6554. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6555. {
  6556. DetachTerminal(Sender);
  6557. }
  6558. //---------------------------------------------------------------------------
  6559. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6560. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6561. {
  6562. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6563. DebugAssert(Terminal != NULL);
  6564. if (Data->Terminal == Terminal)
  6565. {
  6566. Data->Terminal = NULL;
  6567. }
  6568. }
  6569. //---------------------------------------------------------------------------
  6570. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6571. {
  6572. return NULL;
  6573. }
  6574. //---------------------------------------------------------------------------
  6575. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6576. {
  6577. UpdateControls();
  6578. SessionColor = TColor(0);
  6579. UpdateRemotePathComboBox(false);
  6580. NeedSession(false);
  6581. }
  6582. //---------------------------------------------------------------------------
  6583. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6584. {
  6585. try
  6586. {
  6587. // Cache, as the login dialog can change its value.
  6588. // See also DoShow. Also see TTerminalManager::NewSession.
  6589. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6590. try
  6591. {
  6592. if (ShowLogin)
  6593. {
  6594. bool ReloadSessions = !Startup;
  6595. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6596. }
  6597. }
  6598. __finally
  6599. {
  6600. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6601. // (so there was no chance for the user to open any session yet)
  6602. if ((ShowLogin || !Startup) &&
  6603. !WinConfiguration->KeepOpenWhenNoSession &&
  6604. // this rules out the implicit Commander's local-local browser
  6605. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6606. {
  6607. TerminateApplication();
  6608. }
  6609. }
  6610. }
  6611. catch (EAbort &)
  6612. {
  6613. // swallow
  6614. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6615. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6616. }
  6617. }
  6618. //---------------------------------------------------------------------------
  6619. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6620. {
  6621. TTerminalManager * Manager = TTerminalManager::Instance();
  6622. DebugAssert(!Manager->Updating);
  6623. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6624. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6625. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6626. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6627. try
  6628. {
  6629. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6630. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6631. {
  6632. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6633. }
  6634. for (int Index = 0; Index <= Manager->Count; Index++)
  6635. {
  6636. TThemeTabSheet * TabSheet;
  6637. if (Index >= SessionsPageControl->PageCount)
  6638. {
  6639. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6640. TabSheet->PageControl = SessionsPageControl;
  6641. }
  6642. else
  6643. {
  6644. TabSheet = SessionsPageControl->Pages[Index];
  6645. }
  6646. bool IsSessionTab = (Index < Manager->Count);
  6647. if (IsSessionTab)
  6648. {
  6649. TTerminal * Terminal = Manager->Sessions[Index];
  6650. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6651. TabSheet->CaptionTruncation = tttEllipsis;
  6652. UpdateSessionTab(TabSheet);
  6653. }
  6654. else
  6655. {
  6656. TabSheet->Tag = 0; // not really needed
  6657. TabSheet->Shadowed = false;
  6658. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6659. TabSheet->CaptionTruncation = tttNoText;
  6660. // We know that we are at the last page, otherwise we could not call this (it assumes that new session tab is the last one)
  6661. UpdateNewTabTab();
  6662. }
  6663. }
  6664. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6665. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6666. {
  6667. SessionsPageControl->UpdateTabsCaptionTruncation();
  6668. }
  6669. }
  6670. __finally
  6671. {
  6672. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6673. }
  6674. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6675. }
  6676. //---------------------------------------------------------------------------
  6677. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6678. {
  6679. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6680. }
  6681. //---------------------------------------------------------------------------
  6682. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6683. {
  6684. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6685. UnicodeString TabCaption;
  6686. if (WinConfiguration->SelectiveToolbarText)
  6687. {
  6688. TabCaption = GetNewTabTabCaption();
  6689. }
  6690. TabSheet->BaseCaption = TabCaption;
  6691. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6692. }
  6693. //---------------------------------------------------------------------------
  6694. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6695. {
  6696. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6697. }
  6698. //---------------------------------------------------------------------------
  6699. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6700. {
  6701. DebugFail();
  6702. return UnicodeString();
  6703. }
  6704. //---------------------------------------------------------------------------
  6705. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6706. {
  6707. if (DebugAlwaysTrue(TabSheet != NULL))
  6708. {
  6709. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6710. if (DebugAlwaysTrue(ASession != NULL))
  6711. {
  6712. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6713. if (ASession->LocalBrowser)
  6714. {
  6715. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6716. }
  6717. else
  6718. {
  6719. TabSheet->ImageIndex = AddSessionColor(Color);
  6720. }
  6721. TTerminalManager * Manager = TTerminalManager::Instance();
  6722. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6723. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6724. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6725. }
  6726. }
  6727. }
  6728. //---------------------------------------------------------------------------
  6729. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6730. {
  6731. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6732. }
  6733. //---------------------------------------------------------------------------
  6734. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6735. {
  6736. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6737. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6738. bool Result = (Session != NULL);
  6739. if (Result)
  6740. {
  6741. TTerminalManager::Instance()->ActiveSession = Session;
  6742. }
  6743. else
  6744. {
  6745. try
  6746. {
  6747. NewTab();
  6748. }
  6749. __finally
  6750. {
  6751. SessionListChanged();
  6752. }
  6753. FSessionsPageControlNewTabTime = Now();
  6754. }
  6755. return Result;
  6756. }
  6757. //---------------------------------------------------------------------------
  6758. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6759. {
  6760. TWindowLock Lock(this);
  6761. SessionTabSwitched();
  6762. }
  6763. //---------------------------------------------------------------------------
  6764. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6765. {
  6766. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6767. DebugAssert(TransferList != NULL);
  6768. UnicodeString Name;
  6769. if (TransferList->ItemIndex <= 0)
  6770. {
  6771. Name = L"";
  6772. }
  6773. else
  6774. {
  6775. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  6776. }
  6777. if (FCopyParamAutoSelected.IsEmpty())
  6778. {
  6779. // if previous preset was not autoselected, make new preset the "default"
  6780. FCopyParamDefault = Name;
  6781. }
  6782. GUIConfiguration->CopyParamCurrent = Name;
  6783. }
  6784. //---------------------------------------------------------------------------
  6785. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  6786. {
  6787. // sanity check
  6788. bool ExistingPreset =
  6789. (FTransferListHoverIndex >= 0) &&
  6790. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  6791. DebugAssert(ExistingPreset);
  6792. if (ExistingPreset)
  6793. {
  6794. HDC DC = GetDC(0);
  6795. TCanvas * Canvas = new TCanvas();
  6796. try
  6797. {
  6798. Canvas->Handle = DC;
  6799. Canvas->Font = GetToolbarFont(this);
  6800. UnicodeString Name;
  6801. if (FTransferListHoverIndex == 0)
  6802. {
  6803. Name = L"";
  6804. }
  6805. else
  6806. {
  6807. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  6808. }
  6809. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  6810. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  6811. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  6812. static_cast<TObject*>(GetComponent(fcTransferList)));
  6813. UnicodeString InfoStr =
  6814. GUIConfiguration->CopyParamPreset[Name].
  6815. GetInfoStr(L"; ",
  6816. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  6817. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  6818. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  6819. {
  6820. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  6821. {
  6822. InfoStr.SetLength(InfoStr.Length() - 1);
  6823. }
  6824. InfoStr += Ellipsis;
  6825. }
  6826. // UpdateCaption does not cause invalidation of whole submenu, while
  6827. // setting Caption property does.
  6828. // also it probably does not resize the label, even if necessary
  6829. // (we do not want that anyway)
  6830. TransferLabel->UpdateCaption(InfoStr);
  6831. }
  6832. __finally
  6833. {
  6834. Canvas->Handle = NULL;
  6835. ReleaseDC(0, DC);
  6836. delete Canvas;
  6837. }
  6838. }
  6839. }
  6840. //---------------------------------------------------------------------------
  6841. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  6842. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  6843. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  6844. {
  6845. if (FTransferListHoverIndex != AHoverIndex)
  6846. {
  6847. FTransferListHoverIndex = AHoverIndex;
  6848. UpdateTransferLabel();
  6849. }
  6850. }
  6851. //---------------------------------------------------------------------------
  6852. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  6853. {
  6854. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  6855. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  6856. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  6857. {
  6858. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  6859. {
  6860. if (!NonVisualDataModule->Busy)
  6861. {
  6862. OpenDirectory(GetSide(osCurrent));
  6863. }
  6864. Message.Result = 1;
  6865. }
  6866. else
  6867. {
  6868. TForm::Dispatch(&Message);
  6869. }
  6870. }
  6871. else
  6872. {
  6873. TForm::Dispatch(&Message);
  6874. }
  6875. }
  6876. //---------------------------------------------------------------------------
  6877. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  6878. {
  6879. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  6880. if ((FIgnoreNextDialogChar != 0) &&
  6881. (toupper(Message.CharCode) == toupper(FIgnoreNextDialogChar)))
  6882. {
  6883. Message.Result = 1;
  6884. }
  6885. else
  6886. {
  6887. TForm::Dispatch(&Message);
  6888. }
  6889. FIgnoreNextDialogChar = 0;
  6890. }
  6891. //---------------------------------------------------------------------------
  6892. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  6893. {
  6894. // The four low-order bits are used internally by Windows
  6895. unsigned int Cmd = (Message.WParam & 0xFFF0);
  6896. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  6897. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  6898. // 61730 - restore thru double click - undocumented
  6899. // 61490 - maximize thru double click - undocumented
  6900. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  6901. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  6902. {
  6903. SysResizing(Cmd);
  6904. }
  6905. TForm::Dispatch(&Message);
  6906. }
  6907. //---------------------------------------------------------------------------
  6908. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  6909. {
  6910. // We were actually never able to make ENDSESSION_CRITICAL happen.
  6911. // Also there no point returning TRUE as we are not able to
  6912. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  6913. // Hence the process termination might be safer :)
  6914. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  6915. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  6916. {
  6917. Message.Result = FALSE;
  6918. }
  6919. else
  6920. {
  6921. Message.Result = TRUE;
  6922. }
  6923. // Do not call default handling as that triggers OnCloseQuery,
  6924. // where our implementation will popup confirmation dialogs, what we do not want,
  6925. // as per Vista guidelines:
  6926. // https://docs.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  6927. }
  6928. //---------------------------------------------------------------------------
  6929. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  6930. {
  6931. if (Message.EndSession && IsApplicationMinimized())
  6932. {
  6933. // WORKAROUND
  6934. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  6935. // when it receives WM_ENDSESSION,
  6936. // but that sometimes (particularly when application is minimized) cause crashes.
  6937. // Crash popups message that blocks log off.
  6938. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  6939. // so we call ExitProcess() immediately, not even trying to cleanup.
  6940. // It still causes beep, so there's likely some popup, but it does not block
  6941. // log off.
  6942. ExitProcess(0);
  6943. }
  6944. TForm::Dispatch(&Message);
  6945. }
  6946. #ifdef _DEBUG
  6947. //---------------------------------------------------------------------------
  6948. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  6949. {
  6950. TForm::Dispatch(&Message);
  6951. }
  6952. #endif
  6953. //---------------------------------------------------------------------------
  6954. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  6955. {
  6956. }
  6957. //---------------------------------------------------------------------------
  6958. void __fastcall TCustomScpExplorerForm::DoShow()
  6959. {
  6960. // Called from TCustomScpExplorerForm::CMShowingChanged
  6961. // only now are the controls resized finally, so the size constraints
  6962. // will not conflict with possibly very small window size
  6963. RestoreFormParams();
  6964. // This indicates that the form was rescaled after parameters were loaded and
  6965. // as most probably the parameters were actually saved with the current form scaling
  6966. // (windows was the last time likely closed on the same monitor, where it is starting now),
  6967. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  6968. // and no rounding problems will occur.
  6969. // See also RestoreForm.
  6970. // (we should be safe to call RestoreParams unconditionally)
  6971. if (PixelsPerInch != Screen->PixelsPerInch)
  6972. {
  6973. RestoreParams();
  6974. }
  6975. FixControlsPlacement();
  6976. if (Position == poDefaultPosOnly)
  6977. {
  6978. CutFormToDesktop(this);
  6979. }
  6980. TForm::DoShow();
  6981. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  6982. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  6983. // This was previously in NeedSession, where other related code is.
  6984. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  6985. // unpleasantly shows briefly.
  6986. if ((ManagedSession == NULL) &&
  6987. !WinConfiguration->ShowLoginWhenNoSession &&
  6988. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  6989. // This detects if workspace was saved the last time the main widow was closed
  6990. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  6991. {
  6992. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  6993. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  6994. }
  6995. // Before main window displays
  6996. if (ManagedSession == NULL)
  6997. {
  6998. StartingWithoutSession();
  6999. }
  7000. UpdatePixelsPerInchMainWindowCounter();
  7001. FShowing = true;
  7002. }
  7003. //---------------------------------------------------------------------------
  7004. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7005. {
  7006. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7007. }
  7008. //---------------------------------------------------------------------------
  7009. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7010. {
  7011. SessionListChanged();
  7012. InitStatusBar();
  7013. UpdateControls();
  7014. }
  7015. //---------------------------------------------------------------------------
  7016. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7017. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7018. TNotifyEvent OnBalloonClick, TObject * UserData)
  7019. {
  7020. bool Do;
  7021. UnicodeString Message;
  7022. if (E == NULL)
  7023. {
  7024. Message = Str;
  7025. Do = true;
  7026. }
  7027. else
  7028. {
  7029. Do = ExceptionMessage(E, Message);
  7030. }
  7031. if (Do && WinConfiguration->BalloonNotifications)
  7032. {
  7033. UnicodeString Title;
  7034. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7035. {
  7036. Message = TrimLeft(Message);
  7037. }
  7038. else
  7039. {
  7040. Message = UnformatMessage(Message);
  7041. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7042. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7043. Title = LoadResourceString(Captions[Type]);
  7044. if (Terminal != NULL)
  7045. {
  7046. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7047. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7048. }
  7049. }
  7050. if (Seconds == 0)
  7051. {
  7052. Seconds = WinConfiguration->NotificationsTimeout;
  7053. }
  7054. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7055. }
  7056. }
  7057. //---------------------------------------------------------------------------
  7058. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7059. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7060. UnicodeString HelpKeyword, const TMessageParams * Params,
  7061. TTerminal * Terminal)
  7062. {
  7063. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7064. (FOnFeedSynchronizeError != NULL)) &&
  7065. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7066. {
  7067. if (FOnFeedSynchronizeError != NULL)
  7068. {
  7069. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7070. }
  7071. else
  7072. {
  7073. DebugAssert(FErrorList != NULL);
  7074. TStringList * MoreMessagesCopy = NULL;
  7075. if (MoreMessages)
  7076. {
  7077. MoreMessagesCopy = new TStringList();
  7078. MoreMessagesCopy->Assign(MoreMessages);
  7079. }
  7080. FErrorList->AddObject(Message, MoreMessagesCopy);
  7081. }
  7082. PopupTrayBalloon(Terminal, Message, Type);
  7083. return ContinueAnswer(Answers);
  7084. }
  7085. else
  7086. {
  7087. bool UseBalloon = FTrayIcon->Visible;
  7088. if (UseBalloon)
  7089. {
  7090. PopupTrayBalloon(Terminal, Message, Type);
  7091. }
  7092. unsigned int Result;
  7093. try
  7094. {
  7095. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7096. }
  7097. __finally
  7098. {
  7099. // cancel only balloon we popped up, otherwise we may cancel notification
  7100. // balloon that was there before the message dialog
  7101. // (such as "dd confirmation opt in balloon)
  7102. if (UseBalloon)
  7103. {
  7104. FTrayIcon->CancelBalloon();
  7105. }
  7106. }
  7107. return Result;
  7108. }
  7109. }
  7110. //---------------------------------------------------------------------------
  7111. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7112. TTerminal * Terminal, Exception * E)
  7113. {
  7114. if (FTrayIcon->Visible)
  7115. {
  7116. PopupTrayBalloon(Terminal, L"", qtError, E);
  7117. }
  7118. // particularly prevent opening new session from jump list,
  7119. // while exception is shown
  7120. NonVisualDataModule->StartBusy();
  7121. try
  7122. {
  7123. ShowExtendedExceptionEx(Terminal, E);
  7124. }
  7125. __finally
  7126. {
  7127. NonVisualDataModule->EndBusy();
  7128. FTrayIcon->CancelBalloon();
  7129. }
  7130. }
  7131. //---------------------------------------------------------------------------
  7132. void __fastcall TCustomScpExplorerForm::SessionReady()
  7133. {
  7134. InitStatusBar();
  7135. // cannot rely on active page being page for active terminal,
  7136. // as it can happen that active page is the "new session" page
  7137. // (e.g. when reconnecting active terminal, while login dialog
  7138. // invoked from "new session" page is modal)
  7139. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7140. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7141. }
  7142. //---------------------------------------------------------------------------
  7143. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7144. TTerminal * Terminal, Exception * E)
  7145. {
  7146. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7147. if (!Terminal->Active)
  7148. {
  7149. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7150. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7151. {
  7152. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7153. }
  7154. }
  7155. }
  7156. //---------------------------------------------------------------------------
  7157. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7158. UnicodeString Message, TQueryType Type,
  7159. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7160. {
  7161. if ((E == NULL) ||
  7162. ExceptionMessage(E, Message))
  7163. {
  7164. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7165. if (Important)
  7166. {
  7167. Seconds *= 5;
  7168. }
  7169. UnicodeString NoteMessage(UnformatMessage(Message));
  7170. if (Terminal != NULL)
  7171. {
  7172. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7173. NoteMessage = FORMAT(L"%s: %s",
  7174. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7175. }
  7176. if (WinConfiguration->BalloonNotifications)
  7177. {
  7178. AddNote(NoteMessage);
  7179. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7180. }
  7181. else
  7182. {
  7183. FlashOnBackground();
  7184. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7185. }
  7186. }
  7187. }
  7188. //---------------------------------------------------------------------------
  7189. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7190. {
  7191. RestoreApp();
  7192. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7193. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7194. !NonVisualDataModule->Busy)
  7195. {
  7196. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7197. TTerminalManager::Instance()->ActiveSession = Terminal;
  7198. if (!ComponentVisible[fcQueueView])
  7199. {
  7200. ToggleQueueVisibility();
  7201. GoToQueue();
  7202. }
  7203. }
  7204. }
  7205. //---------------------------------------------------------------------------
  7206. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7207. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7208. {
  7209. UnicodeString Message;
  7210. TNotifyEvent OnClick = NULL;
  7211. TObject * UserData = NULL;
  7212. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7213. switch (Event)
  7214. {
  7215. case qeEmptyButMonitored:
  7216. if ((ATerminal != Terminal) || QueueInvisible)
  7217. {
  7218. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7219. OnClick = QueueEmptyNoteClicked;
  7220. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7221. TerminalNoteData->Terminal = ATerminal;
  7222. UserData = TerminalNoteData;
  7223. }
  7224. break;
  7225. case qeEmpty:
  7226. OperationComplete(ATerminal->QueueOperationStart);
  7227. break;
  7228. case qePendingUserAction:
  7229. if ((ATerminal != Terminal) ||
  7230. (QueueInvisible && !IsQueueAutoPopup()))
  7231. {
  7232. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7233. }
  7234. break;
  7235. default:
  7236. DebugFail();
  7237. }
  7238. if (!Message.IsEmpty())
  7239. {
  7240. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7241. }
  7242. }
  7243. //---------------------------------------------------------------------------
  7244. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7245. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7246. {
  7247. if (FDDExtMapFile != NULL)
  7248. {
  7249. CloseHandle(FDDExtMapFile);
  7250. FDDExtMapFile = NULL;
  7251. }
  7252. if (WinConfiguration->DDFakeFile)
  7253. {
  7254. DDFakeFileInitDrag(FileList, Created);
  7255. }
  7256. }
  7257. //---------------------------------------------------------------------------
  7258. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7259. {
  7260. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7261. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7262. {
  7263. FFakeFileDropTarget = FileName;
  7264. }
  7265. }
  7266. //---------------------------------------------------------------------------
  7267. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7268. {
  7269. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7270. if (!ForceDirectories(ApiPath(Result)))
  7271. {
  7272. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7273. }
  7274. FileSetAttr(ApiPath(Result), faHidden);
  7275. return Result;
  7276. }
  7277. //---------------------------------------------------------------------------
  7278. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7279. bool & Created)
  7280. {
  7281. FFakeFileDropTarget = UnicodeString();
  7282. FDragFakeDirectory = CreateFakeTransferDirectory();
  7283. FileList->AddItem(NULL, FDragFakeDirectory);
  7284. Created = true;
  7285. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7286. {
  7287. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7288. }
  7289. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7290. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7291. {
  7292. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7293. TDragExtCommStruct* CommStruct;
  7294. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7295. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7296. DebugAssert(CommStruct != NULL);
  7297. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7298. CommStruct->Dragging = true;
  7299. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7300. LENOF(CommStruct->DropDest));
  7301. NULL_TERMINATE(CommStruct->DropDest);
  7302. UnmapViewOfFile(CommStruct);
  7303. }
  7304. }
  7305. //---------------------------------------------------------------------------
  7306. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7307. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7308. {
  7309. bool Result;
  7310. DebugAssert(!IsLocalBrowserMode());
  7311. if (Sender == RemoteDirView)
  7312. {
  7313. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7314. }
  7315. else
  7316. {
  7317. DebugAssert(Sender == RemoteDriveView);
  7318. TStrings * FileList = RemoteDriveView->DragFileList();
  7319. try
  7320. {
  7321. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7322. }
  7323. __finally
  7324. {
  7325. delete FileList;
  7326. }
  7327. }
  7328. if (FDDTargetControl == RemoteDriveView)
  7329. {
  7330. RemoteDriveView->UpdateDropTarget();
  7331. }
  7332. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7333. // or from tree view to dir view.
  7334. // foMove happens when file/dir is dragged from remote tree view outside of
  7335. // application via dragex
  7336. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7337. (DropSourceControl == RemoteDriveView))
  7338. {
  7339. RemoteDriveView->UpdateDropSource();
  7340. }
  7341. return Result;
  7342. }
  7343. //---------------------------------------------------------------------------
  7344. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7345. {
  7346. DebugAssert(!IsLocalBrowserMode());
  7347. // This also handles drops of remote files to queue.
  7348. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7349. SAFE_DESTROY(FDDFileList);
  7350. if (!FFakeFileDropTarget.IsEmpty())
  7351. {
  7352. RemoveDir(ApiPath(FFakeFileDropTarget));
  7353. }
  7354. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7355. {
  7356. try
  7357. {
  7358. TDragResult DDResult = (Sender == RemoteDirView) ?
  7359. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7360. // Focus is moved to the target application,
  7361. // but as we are going to present the UI, we need to steal the focus back.
  7362. // This most likely won't work though (windows does not allow application
  7363. // to steal focus most of the time)
  7364. Application->BringToFront();
  7365. // On older version of Windows we never got drMove here, see also comment below.
  7366. // On Windows 10, we get the "move".
  7367. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7368. {
  7369. UnicodeString TargetDirectory;
  7370. TFileOperation Operation;
  7371. // drInvalid may mean drMove, see comment below
  7372. switch (DDResult)
  7373. {
  7374. case drCopy:
  7375. Operation = foCopy;
  7376. break;
  7377. case drMove:
  7378. Operation = foMove;
  7379. break;
  7380. default:
  7381. DebugFail();
  7382. case drInvalid:
  7383. // prefer "copy" for safety
  7384. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7385. break;
  7386. }
  7387. TTransferOperationParam Param;
  7388. UnicodeString CounterName;
  7389. bool ForceQueue;
  7390. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7391. {
  7392. // we get drInvalid both if d&d was intercepted by ddext,
  7393. // and when users drops on no-drop location.
  7394. // we tell the difference by existence of response from ddext,
  7395. // so we ignore absence of response in this case
  7396. if (DDResult != drInvalid)
  7397. {
  7398. // here we know that the extension is installed,
  7399. // as it is checked as soon as drag&drop starts from
  7400. // RemoteFileControlDDCreateDragFileList
  7401. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7402. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7403. {
  7404. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7405. }
  7406. else
  7407. {
  7408. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7409. }
  7410. }
  7411. }
  7412. else
  7413. {
  7414. // download using fake file
  7415. Param.Temp = false;
  7416. Param.DragDrop = true;
  7417. if (ForceQueue)
  7418. {
  7419. Param.Queue = asOn;
  7420. }
  7421. if (Sender == RemoteDirView)
  7422. {
  7423. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7424. }
  7425. if (RemoteFileControlFileOperation(Sender, Operation,
  7426. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7427. {
  7428. Configuration->Usage->Inc(CounterName);
  7429. }
  7430. }
  7431. }
  7432. }
  7433. __finally
  7434. {
  7435. CloseHandle(FDDExtMapFile);
  7436. FDDExtMapFile = NULL;
  7437. delete FDragFakeMonitors;
  7438. FDragFakeMonitors = NULL;
  7439. RemoveDir(ApiPath(FDragFakeDirectory));
  7440. FDragFakeDirectory = L"";
  7441. FFakeFileDropTarget = UnicodeString();
  7442. }
  7443. }
  7444. if (FDragDropSshTerminate.get() != NULL)
  7445. {
  7446. FDragDropSshTerminate->Rethrow();
  7447. }
  7448. }
  7449. //---------------------------------------------------------------------------
  7450. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7451. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7452. {
  7453. // Remember drop effect so we know (when user drops files), if we copy or move
  7454. FLastDropEffect = dwEffect;
  7455. }
  7456. //---------------------------------------------------------------------------
  7457. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7458. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7459. {
  7460. bool Result;
  7461. if (FDDTargetControl == QueueView3)
  7462. {
  7463. Directory = DefaultDownloadTargetDirectory();
  7464. Result = true;
  7465. CounterName = L"DownloadsDragDropQueue";
  7466. ForceQueue = true;
  7467. }
  7468. else if (!FFakeFileDropTarget.IsEmpty())
  7469. {
  7470. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7471. Result = true;
  7472. ForceQueue = false;
  7473. CounterName = L"DownloadsDragDropFakeFile";
  7474. }
  7475. else
  7476. {
  7477. ForceQueue = false;
  7478. Enabled = false;
  7479. try
  7480. {
  7481. int Timer = 0;
  7482. Result = false;
  7483. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7484. {
  7485. {
  7486. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7487. TDragExtCommStruct* CommStruct;
  7488. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7489. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7490. DebugAssert(CommStruct != NULL);
  7491. Result = !CommStruct->Dragging;
  7492. if (Result)
  7493. {
  7494. Directory = ExtractFilePath(CommStruct->DropDest);
  7495. CounterName = L"DownloadsDragDropExternalExt";
  7496. }
  7497. UnmapViewOfFile(CommStruct);
  7498. }
  7499. if (!Result)
  7500. {
  7501. Sleep(50);
  7502. Timer += 50;
  7503. Application->ProcessMessages();
  7504. }
  7505. }
  7506. }
  7507. __finally
  7508. {
  7509. Enabled = true;
  7510. }
  7511. }
  7512. return Result;
  7513. }
  7514. //---------------------------------------------------------------------------
  7515. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7516. const UnicodeString TempDir, int SecDelay)
  7517. {
  7518. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7519. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7520. if (FDelayedDeletionTimer == NULL)
  7521. {
  7522. DebugAssert(HandleAllocated());
  7523. FDelayedDeletionTimer = new TTimer(this);
  7524. FDelayedDeletionTimer->Interval = 10000;
  7525. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7526. }
  7527. else
  7528. {
  7529. FDelayedDeletionTimer->Enabled = true;
  7530. }
  7531. }
  7532. //---------------------------------------------------------------------------
  7533. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7534. {
  7535. DebugAssert(FDelayedDeletionList != NULL);
  7536. TDateTime N = Now();
  7537. TDateTime Alert;
  7538. UnicodeString Directory;
  7539. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7540. {
  7541. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7542. if ((N >= Alert) || (Sender == NULL))
  7543. {
  7544. Directory = FDelayedDeletionList->Strings[Index];
  7545. if (DeleteDirectory(ExcludeTrailingBackslash(Directory)))
  7546. {
  7547. FDelayedDeletionList->Delete(Index);
  7548. }
  7549. }
  7550. }
  7551. if (FDelayedDeletionList->Count == 0)
  7552. {
  7553. FDelayedDeletionTimer->Enabled = false;
  7554. }
  7555. }
  7556. //---------------------------------------------------------------------------
  7557. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7558. {
  7559. DebugAssert(!IsLocalBrowserMode());
  7560. if (IsFileControl(FDDTargetControl, osRemote) ||
  7561. (FDDTargetControl == SessionsPageControl))
  7562. {
  7563. TManagedTerminal * TargetTerminal = NULL;
  7564. TFileOperation Operation = foNone;
  7565. if (FDDTargetControl == SessionsPageControl)
  7566. {
  7567. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7568. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7569. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7570. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7571. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7572. {
  7573. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7574. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7575. {
  7576. Operation = foRemoteMove;
  7577. }
  7578. else
  7579. {
  7580. Operation = foRemoteCopy;
  7581. }
  7582. }
  7583. }
  7584. else
  7585. {
  7586. if (FLastDropEffect == DROPEFFECT_MOVE)
  7587. {
  7588. Operation = foRemoteMove;
  7589. }
  7590. else if (FLastDropEffect == DROPEFFECT_COPY)
  7591. {
  7592. Operation = foRemoteCopy;
  7593. }
  7594. }
  7595. if (Operation != foNone)
  7596. {
  7597. RemoteFileControlFileOperation(DropSourceControl,
  7598. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7599. }
  7600. // abort drag&drop
  7601. Abort();
  7602. }
  7603. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7604. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7605. (FDDTargetControl != QueueView3))
  7606. {
  7607. DebugAssert(!FDragTempDir.IsEmpty());
  7608. TTransferType Type;
  7609. UnicodeString TempDir = FDragTempDir;
  7610. // We clear FDragTempDir before calling
  7611. // just in case it fail (raises exception)
  7612. FDragTempDir = L"";
  7613. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7614. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7615. // empty directory parameter means temp directory -> don't display it!
  7616. UnicodeString TargetDir = L"";
  7617. int Options = 0;
  7618. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7619. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7620. {
  7621. Abort();
  7622. }
  7623. // TargetDir is set when dropped on local file control
  7624. // (this was workaround for legacy dirview event handling, now it should be
  7625. // made prettier)
  7626. if (TargetDir.IsEmpty())
  7627. {
  7628. TargetDir = TempDir;
  7629. if (ForceDirectories(ApiPath(TargetDir)))
  7630. {
  7631. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7632. FPendingTempSpaceWarn = true;
  7633. try
  7634. {
  7635. FDragDropOperation = true;
  7636. int Params = cpTemporary |
  7637. (Type == ttMove ? cpDelete : 0);
  7638. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7639. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7640. }
  7641. __finally
  7642. {
  7643. FDragDropOperation = false;
  7644. FPendingTempSpaceWarn = false;
  7645. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7646. }
  7647. }
  7648. else
  7649. {
  7650. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7651. }
  7652. }
  7653. }
  7654. }
  7655. //---------------------------------------------------------------------------
  7656. void __fastcall TCustomScpExplorerForm::DDDownload(
  7657. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7658. {
  7659. DebugAssert(!IsLocalBrowserMode());
  7660. TAutoBatch AutoBatch(this);
  7661. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7662. UpdateCopyParamCounters(*CopyParam);
  7663. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7664. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7665. {
  7666. RemoteDriveView->UpdateDropSource();
  7667. }
  7668. }
  7669. //---------------------------------------------------------------------------
  7670. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7671. {
  7672. public:
  7673. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7674. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7675. {
  7676. }
  7677. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7678. {
  7679. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7680. TDataObjectFilesEx::AllowData(FormatEtc);
  7681. }
  7682. };
  7683. //---------------------------------------------------------------------------
  7684. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7685. TObject * Sender, TDataObject *& DataObject)
  7686. {
  7687. if (FDDExtMapFile != NULL)
  7688. {
  7689. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7690. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7691. {
  7692. Abort();
  7693. }
  7694. if (FileList->Count > 0)
  7695. {
  7696. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7697. if (!FilesObject->IsValid(true, true))
  7698. {
  7699. FilesObject->_Release();
  7700. }
  7701. else
  7702. {
  7703. DataObject = FilesObject;
  7704. }
  7705. }
  7706. }
  7707. }
  7708. //---------------------------------------------------------------------------
  7709. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7710. {
  7711. DebugFail();
  7712. }
  7713. //---------------------------------------------------------------------------
  7714. void __fastcall TCustomScpExplorerForm::GoToTree()
  7715. {
  7716. ComponentVisible[fcRemoteTree] = true;
  7717. DriveView(osRemote)->SetFocus();
  7718. }
  7719. //---------------------------------------------------------------------------
  7720. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7721. TPanelExport Export)
  7722. {
  7723. TCustomDirView * DirView = this->DirView(Side);
  7724. std::unique_ptr<TStrings> ExportData(new TStringList());
  7725. switch (Export)
  7726. {
  7727. case pePath:
  7728. ExportData->Add(DirView->PathName);
  7729. break;
  7730. case peFileList:
  7731. case peFullFileList:
  7732. {
  7733. bool FullPath = (Export == peFullFileList);
  7734. DirView->CreateFileList(false, FullPath, ExportData.get());
  7735. for (int Index = 0; Index < ExportData->Count; Index++)
  7736. {
  7737. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7738. {
  7739. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7740. }
  7741. }
  7742. }
  7743. break;
  7744. default:
  7745. DebugFail();
  7746. }
  7747. return ExportData.release();
  7748. }
  7749. //---------------------------------------------------------------------------
  7750. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7751. TPanelExport Export, TPanelExportDestination Destination)
  7752. {
  7753. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7754. PanelExportStore(Side, Export, Destination, ExportData.get());
  7755. }
  7756. //---------------------------------------------------------------------------
  7757. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7758. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7759. TStrings * ExportData)
  7760. {
  7761. if (Destination == pedClipboard)
  7762. {
  7763. TInstantOperationVisualizer Visualizer;
  7764. CopyToClipboard(ExportData);
  7765. }
  7766. else
  7767. {
  7768. DebugFail();
  7769. }
  7770. }
  7771. //---------------------------------------------------------------------------
  7772. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  7773. {
  7774. TCustomDirView * DirView = this->DirView(Side);
  7775. UnicodeString Mask = DirView->Mask;
  7776. if (DoFilterMaskDialog(DirView, Mask))
  7777. {
  7778. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  7779. Configuration->Usage->Inc(L"Filters");
  7780. }
  7781. }
  7782. //---------------------------------------------------------------------------
  7783. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  7784. {
  7785. return FQueueController->DefaultOperation();
  7786. }
  7787. //---------------------------------------------------------------------------
  7788. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  7789. TQueueOperation Operation, void ** Param)
  7790. {
  7791. switch (Operation)
  7792. {
  7793. case qoPreferences:
  7794. return true;
  7795. case qoGoTo:
  7796. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  7797. case qoOnceEmpty:
  7798. return IsAnythingQueued();
  7799. default:
  7800. return FQueueController->AllowOperation(Operation, Param);
  7801. }
  7802. }
  7803. //---------------------------------------------------------------------------
  7804. void __fastcall TCustomScpExplorerForm::GoToQueue()
  7805. {
  7806. if (DebugAlwaysTrue(QueueView3->Visible))
  7807. {
  7808. QueueView3->SetFocus();
  7809. }
  7810. }
  7811. //---------------------------------------------------------------------------
  7812. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  7813. TQueueOperation Operation, void * Param)
  7814. {
  7815. if (Operation == qoGoTo)
  7816. {
  7817. GoToQueue();
  7818. }
  7819. else if (Operation == qoPreferences)
  7820. {
  7821. PreferencesDialog(pmQueue);
  7822. }
  7823. else
  7824. {
  7825. FQueueController->ExecuteOperation(Operation, Param);
  7826. }
  7827. }
  7828. //---------------------------------------------------------------------------
  7829. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  7830. {
  7831. return (Queue != NULL) && Queue->Enabled;
  7832. }
  7833. //---------------------------------------------------------------------------
  7834. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  7835. {
  7836. DebugAssert(Queue != NULL);
  7837. if (Queue != NULL)
  7838. {
  7839. Queue->Enabled = !Queue->Enabled;
  7840. }
  7841. }
  7842. //---------------------------------------------------------------------------
  7843. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  7844. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  7845. {
  7846. FQueueActedItem = QueueView3->ItemFocused;
  7847. }
  7848. //---------------------------------------------------------------------------
  7849. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  7850. {
  7851. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  7852. }
  7853. //---------------------------------------------------------------------------
  7854. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  7855. {
  7856. return
  7857. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  7858. (QueueDock->Visible ? QueueDock->Height : 0) +
  7859. (QueueLabel->Visible ? QueueLabel->Height : 0);
  7860. }
  7861. //---------------------------------------------------------------------------
  7862. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  7863. {
  7864. return ScaleByTextHeight(this, 48);
  7865. }
  7866. //---------------------------------------------------------------------------
  7867. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  7868. TObject * /*Sender*/, int & NewSize, bool & Accept)
  7869. {
  7870. // when queue is hidden by double-clicking splitter, stray attempt to
  7871. // resize the panel with strange value arrives, make sure it is ignored
  7872. if (ComponentVisible[fcQueueView])
  7873. {
  7874. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  7875. if (NewSize > MaxHeightLimit)
  7876. {
  7877. NewSize = MaxHeightLimit;
  7878. }
  7879. int MinHeightLimit =
  7880. GetStaticQueuePanelComponentsHeight() +
  7881. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  7882. GetMinQueueViewHeight();
  7883. if (NewSize < MinHeightLimit)
  7884. {
  7885. NewSize = MinHeightLimit;
  7886. }
  7887. }
  7888. else
  7889. {
  7890. Accept = false;
  7891. }
  7892. }
  7893. //---------------------------------------------------------------------------
  7894. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  7895. {
  7896. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  7897. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  7898. if (QueueViewHeight < GetMinQueueViewHeight())
  7899. {
  7900. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  7901. }
  7902. }
  7903. //---------------------------------------------------------------------------
  7904. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  7905. TDragObject *& /*DragObject*/)
  7906. {
  7907. FQueueActedItem = QueueView3->ItemFocused;
  7908. }
  7909. //---------------------------------------------------------------------------
  7910. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  7911. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  7912. {
  7913. Accept = true;
  7914. if (Source == QueueView3)
  7915. {
  7916. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  7917. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  7918. if (Accept)
  7919. {
  7920. TQueueItemProxy * QueueItem;
  7921. TQueueItemProxy * DestQueueItem;
  7922. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  7923. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  7924. Accept = (QueueItem != DestQueueItem) &&
  7925. (QueueItem->Status == TQueueItem::qsPending) &&
  7926. (DestQueueItem->Status == TQueueItem::qsPending);
  7927. }
  7928. }
  7929. }
  7930. //---------------------------------------------------------------------------
  7931. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  7932. TObject * /*Source*/, int /*X*/, int /*Y*/)
  7933. {
  7934. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  7935. {
  7936. TQueueItemProxy * QueueItem;
  7937. TQueueItemProxy * DestQueueItem;
  7938. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  7939. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  7940. QueueItem->Move(DestQueueItem);
  7941. }
  7942. }
  7943. //---------------------------------------------------------------------------
  7944. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  7945. {
  7946. if ((QueueView3->ItemFocused == NULL) &&
  7947. (QueueView3->Items->Count > 0))
  7948. {
  7949. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  7950. }
  7951. QueueLabelUpdateStatus();
  7952. }
  7953. //---------------------------------------------------------------------------
  7954. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  7955. {
  7956. QueueLabelUpdateStatus();
  7957. }
  7958. //---------------------------------------------------------------------------
  7959. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  7960. {
  7961. QueueLabel->UpdateStatus();
  7962. }
  7963. //---------------------------------------------------------------------------
  7964. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  7965. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  7966. {
  7967. if (Selected)
  7968. {
  7969. NonVisualDataModule->UpdateNonVisibleActions();
  7970. }
  7971. }
  7972. //---------------------------------------------------------------------------
  7973. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  7974. {
  7975. TDragDropFilesEx * Result = NULL;
  7976. if (Sender == SessionsPageControl)
  7977. {
  7978. Result = FSessionsDragDropFilesEx;
  7979. }
  7980. else if (Sender == QueueView3)
  7981. {
  7982. Result = FQueueDragDropFilesEx;
  7983. }
  7984. else
  7985. {
  7986. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  7987. if (DirView != NULL)
  7988. {
  7989. Result = DirView->DragDropFilesEx;
  7990. }
  7991. else
  7992. {
  7993. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  7994. if (DriveView != NULL)
  7995. {
  7996. Result = DriveView->DragDropFilesEx;
  7997. }
  7998. }
  7999. }
  8000. DebugAssert(Result != NULL);
  8001. return Result;
  8002. }
  8003. //---------------------------------------------------------------------------
  8004. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8005. {
  8006. return (DView->SelCount == DView->FilesCount);
  8007. }
  8008. //---------------------------------------------------------------------------
  8009. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8010. {
  8011. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8012. }
  8013. //---------------------------------------------------------------------------
  8014. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8015. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8016. {
  8017. DebugAssert(!IsLocalBrowserMode());
  8018. TFileOperation Operation;
  8019. switch (Effect)
  8020. {
  8021. case DROPEFFECT_MOVE:
  8022. Operation = foMove;
  8023. break;
  8024. case DROPEFFECT_COPY:
  8025. // occures on WinXP (reported by user)
  8026. default:
  8027. Operation = foCopy;
  8028. break;
  8029. };
  8030. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8031. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8032. if (DragDropFilesEx->FileList->Count > 0)
  8033. {
  8034. TStrings * FileList = new TStringList();
  8035. try
  8036. {
  8037. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8038. {
  8039. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8040. }
  8041. FDragDropOperation = true;
  8042. TTransferOperationParam Param;
  8043. Param.TargetDirectory = TargetPath;
  8044. // upload, no temp dirs
  8045. Param.Temp = false;
  8046. Param.DragDrop = DragDrop;
  8047. Param.Options =
  8048. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8049. if (ForceQueue)
  8050. {
  8051. Param.Queue = asOn;
  8052. }
  8053. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8054. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8055. {
  8056. if (IsFileControl(DropSourceControl, osLocal))
  8057. {
  8058. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8059. }
  8060. else
  8061. {
  8062. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8063. }
  8064. }
  8065. }
  8066. __finally
  8067. {
  8068. FDragDropOperation = false;
  8069. delete FileList;
  8070. }
  8071. }
  8072. }
  8073. //---------------------------------------------------------------------------
  8074. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8075. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8076. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8077. {
  8078. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8079. }
  8080. //---------------------------------------------------------------------------
  8081. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8082. TObject * Sender, int grfKeyState, int & dwEffect)
  8083. {
  8084. DebugAssert(!IsLocalBrowserMode());
  8085. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8086. if ((dwEffect != DROPEFFECT_NONE) &&
  8087. IsFileControl(DropSourceControl, osRemote))
  8088. {
  8089. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8090. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8091. (RemoteDirView->DropTarget == NULL))
  8092. {
  8093. dwEffect = DROPEFFECT_NONE;
  8094. }
  8095. else
  8096. {
  8097. if (dwEffect == DROPEFFECT_COPY)
  8098. {
  8099. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8100. // currently we support copying always (at least via temporary directory);
  8101. // remove associated checks once this all proves stable and working
  8102. bool CopyCapable = true;
  8103. // if we do not support neither of operations, there's no discussion
  8104. if (!MoveCapable && !CopyCapable)
  8105. {
  8106. dwEffect = DROPEFFECT_NONE;
  8107. }
  8108. else
  8109. {
  8110. // The default effect inside remote panel is move,
  8111. // unless we do not support it, but support copy
  8112. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8113. {
  8114. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8115. }
  8116. else
  8117. {
  8118. // with ctrl-down, we want copy unless it is not supported
  8119. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8120. }
  8121. }
  8122. }
  8123. }
  8124. }
  8125. }
  8126. //---------------------------------------------------------------------------
  8127. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8128. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8129. {
  8130. DebugAssert(!IsLocalBrowserMode());
  8131. if (FDDTotalSize >= 0)
  8132. {
  8133. if (File->IsDirectory)
  8134. {
  8135. FDDTotalSize = -1;
  8136. }
  8137. else
  8138. {
  8139. FDDTotalSize += File->Size;
  8140. }
  8141. }
  8142. DebugAssert(!FDragTempDir.IsEmpty());
  8143. // TODO: this is quite ineffective
  8144. // TODO: what if invalid character replacement is disabled?
  8145. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8146. UnicodeString TransferFileName;
  8147. if (Sender == RemoteDriveView)
  8148. {
  8149. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8150. }
  8151. else
  8152. {
  8153. TransferFileName = File->FileName;
  8154. }
  8155. FDDFileList->AddObject(TransferFileName, File);
  8156. }
  8157. //---------------------------------------------------------------------------
  8158. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8159. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8160. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8161. {
  8162. // sometimes we do not get DDEnd so the list is not released
  8163. SAFE_DESTROY(FDDFileList);
  8164. FDDFileList = new TStringList();
  8165. FDragTempDir = WinConfiguration->TemporaryDir();
  8166. FDDTotalSize = 0;
  8167. FDragDropSshTerminate.reset(NULL);
  8168. }
  8169. //---------------------------------------------------------------------------
  8170. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8171. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8172. HRESULT & Result)
  8173. {
  8174. if (Result == DRAGDROP_S_DROP)
  8175. {
  8176. try
  8177. {
  8178. GlobalDragImageList->HideDragImage();
  8179. try
  8180. {
  8181. RemoteFileControlDDTargetDrop();
  8182. }
  8183. catch(ESshTerminate & E)
  8184. {
  8185. FDragDropSshTerminate.reset(E.Clone());
  8186. }
  8187. }
  8188. catch (Exception &E)
  8189. {
  8190. // If downloading fails we need to cancel drag&drop, otherwise
  8191. // Explorer shows error
  8192. // But by the way exception probably never reach this point as
  8193. // it's catched on way.
  8194. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8195. Result = DRAGDROP_S_CANCEL;
  8196. ShowExtendedException(Terminal, &E);
  8197. }
  8198. }
  8199. }
  8200. //---------------------------------------------------------------------------
  8201. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8202. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8203. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8204. {
  8205. TFileMasks::TParams MaskParams;
  8206. MaskParams.Size = Size;
  8207. MaskParams.Modification = Modification;
  8208. // this does not re-parse the mask if it is the same as the last time
  8209. FDirViewMatchMask = Masks;
  8210. bool ImplicitMatch;
  8211. Matches =
  8212. // Local and RecurseInclude parameters have no effect as there's no path.
  8213. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8214. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8215. (AllowImplicitMatches || !ImplicitMatch);
  8216. }
  8217. //---------------------------------------------------------------------------
  8218. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8219. TObject * Sender, TListItem * Item, WORD & Indexes)
  8220. {
  8221. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8222. UnicodeString Ext;
  8223. if (dynamic_cast<TUnixDirView *>(DirView) != NULL)
  8224. {
  8225. Ext = UnixExtractFileExt(DirView->ItemFileName(Item));
  8226. }
  8227. else
  8228. {
  8229. Ext = ExtractFileExt(DirView->ItemFileName(Item));
  8230. }
  8231. if (SameText(Ext, Configuration->PartialExt))
  8232. {
  8233. Indexes |= oiPartial;
  8234. }
  8235. }
  8236. //---------------------------------------------------------------------------
  8237. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8238. {
  8239. return
  8240. DirViewEnabled(osCurrent) &&
  8241. DirView(osCurrent)->CanPasteFromClipBoard();
  8242. }
  8243. //---------------------------------------------------------------------------
  8244. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8245. {
  8246. bool Result = false;
  8247. if (CanPasteToDirViewFromClipBoard())
  8248. {
  8249. Result = true;
  8250. }
  8251. else
  8252. {
  8253. UnicodeString ClipboardText;
  8254. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8255. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8256. {
  8257. if (StoredSessions->IsUrl(ClipboardText))
  8258. {
  8259. Result = true;
  8260. }
  8261. else
  8262. {
  8263. Result = DirViewEnabled(osCurrent);
  8264. }
  8265. }
  8266. }
  8267. return Result;
  8268. }
  8269. //---------------------------------------------------------------------------
  8270. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8271. {
  8272. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8273. if (DoesClipboardContainOurFiles())
  8274. {
  8275. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8276. {
  8277. DebugAssert(!IsLocalBrowserMode());
  8278. TTerminalManager * Manager = TTerminalManager::Instance();
  8279. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8280. Manager->ActiveSession = FClipboardTerminal;
  8281. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8282. }
  8283. }
  8284. else if (CanPasteToDirViewFromClipBoard())
  8285. {
  8286. DirView(osCurrent)->PasteFromClipBoard();
  8287. }
  8288. else
  8289. {
  8290. UnicodeString ClipboardText;
  8291. if (NonEmptyTextFromClipboard(ClipboardText))
  8292. {
  8293. if (StoredSessions->IsUrl(ClipboardText))
  8294. {
  8295. NewSession(ClipboardText);
  8296. }
  8297. else
  8298. {
  8299. DirView(osCurrent)->Path = ClipboardText;
  8300. }
  8301. }
  8302. }
  8303. }
  8304. //---------------------------------------------------------------------------
  8305. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8306. {
  8307. // TBD
  8308. }
  8309. //---------------------------------------------------------------------------
  8310. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8311. {
  8312. TCustomDirView * ADirView = DirView(Side);
  8313. ADirView->SelectAll(Mode);
  8314. ADirView->SetFocus();
  8315. }
  8316. //---------------------------------------------------------------------------
  8317. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8318. {
  8319. TCustomDirView * ADirView = DirView(Side);
  8320. TFileFilter Filter;
  8321. DefaultFileFilter(Filter);
  8322. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8323. {
  8324. Configuration->Usage->Inc(L"MaskSelections");
  8325. ADirView->SelectFiles(Filter, Select);
  8326. ADirView->SetFocus();
  8327. }
  8328. }
  8329. //---------------------------------------------------------------------------
  8330. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8331. {
  8332. TCustomDirView * ADirView = DirView(Side);
  8333. ADirView->RestoreSelectedNames();
  8334. ADirView->SetFocus();
  8335. }
  8336. //---------------------------------------------------------------------------
  8337. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8338. {
  8339. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8340. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8341. {
  8342. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8343. UnicodeString Ext;
  8344. if (!IsSideLocalBrowser(osCurrent))
  8345. {
  8346. Ext = UnixExtractFileExt(FileName);
  8347. }
  8348. else
  8349. {
  8350. Ext = ExtractFileExt(FileName);
  8351. }
  8352. if (Ext.IsEmpty())
  8353. {
  8354. Ext = L".";
  8355. }
  8356. TFileFilter Filter;
  8357. Filter.Masks = FORMAT(L"*%s", (Ext));
  8358. Filter.Directories = false;
  8359. CurrentDirView->SelectFiles(Filter, Select);
  8360. }
  8361. }
  8362. //---------------------------------------------------------------------------
  8363. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8364. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8365. {
  8366. UnicodeString Result;
  8367. if (!FIncrementalSearch.IsEmpty() && (Side == GetSide(osCurrent)))
  8368. {
  8369. Result = FormatIncrementalSearchStatus(FIncrementalSearch, FIncrementalSearchHaveNext);
  8370. }
  8371. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8372. {
  8373. // noop
  8374. }
  8375. else
  8376. {
  8377. Result =
  8378. FMTLOAD(FILE_INFO_FORMAT,
  8379. (FormatBytes(FileInfo.SelectedSize),
  8380. FormatBytes(FileInfo.FilesSize),
  8381. FormatNumber(FileInfo.SelectedCount),
  8382. FormatNumber(FileInfo.FilesCount)));
  8383. }
  8384. return Result;
  8385. }
  8386. //---------------------------------------------------------------------------
  8387. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8388. TTBXStatusPanel * Panel, TOperationSide Side)
  8389. {
  8390. if (Panel->Index == 1)
  8391. {
  8392. ToggleShowHiddenFiles();
  8393. }
  8394. else if (Panel->Index == 2)
  8395. {
  8396. Filter(Side);
  8397. }
  8398. }
  8399. //---------------------------------------------------------------------------
  8400. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8401. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8402. {
  8403. DebugAssert(!StatusBar->SimplePanel);
  8404. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8405. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8406. }
  8407. //---------------------------------------------------------------------------
  8408. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8409. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8410. {
  8411. DebugAssert(StatusBar->Panels->Count >= 3);
  8412. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8413. if (FileInfo.HiddenCount > 0)
  8414. {
  8415. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8416. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8417. }
  8418. else
  8419. {
  8420. HiddenFilesPanel->ViewPriority = 0;
  8421. // not really necessary, just to cleanup no-longer-valid data
  8422. HiddenFilesPanel->Caption = L"";
  8423. }
  8424. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8425. if (FileInfo.FilteredCount > 0)
  8426. {
  8427. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8428. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8429. }
  8430. else
  8431. {
  8432. FilteredFilesPanel->ViewPriority = 0;
  8433. // not really necessary, just to cleanup no-longer-valid data
  8434. FilteredFilesPanel->Caption = L"";
  8435. }
  8436. }
  8437. //---------------------------------------------------------------------------
  8438. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8439. TObject * /*Sender*/)
  8440. {
  8441. if (DirView(osOther)->Enabled)
  8442. {
  8443. DirView(osOther)->SetFocus();
  8444. }
  8445. }
  8446. //---------------------------------------------------------------------------
  8447. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8448. {
  8449. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8450. switch (Config.Show)
  8451. {
  8452. case qvShow:
  8453. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8454. {
  8455. Config.Show = qvHide;
  8456. }
  8457. else
  8458. {
  8459. Config.Show = Config.LastHideShow;
  8460. }
  8461. break;
  8462. case qvHideWhenEmpty:
  8463. if (ComponentVisible[fcQueueView])
  8464. {
  8465. Config.Show = qvHide;
  8466. }
  8467. else
  8468. {
  8469. Config.LastHideShow = Config.Show;
  8470. Config.Show = qvShow;
  8471. }
  8472. break;
  8473. case qvHide:
  8474. Config.LastHideShow = Config.Show;
  8475. Config.Show = qvShow;
  8476. break;
  8477. }
  8478. WinConfiguration->QueueView = Config;
  8479. }
  8480. //---------------------------------------------------------------------------
  8481. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8482. {
  8483. UnicodeString Result;
  8484. if (Terminal != NULL)
  8485. {
  8486. switch (WinConfiguration->PathInCaption)
  8487. {
  8488. case picShort:
  8489. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8490. break;
  8491. case picFull:
  8492. Result = Terminal->CurrentDirectory;
  8493. break;
  8494. }
  8495. }
  8496. return Result;
  8497. }
  8498. //---------------------------------------------------------------------------
  8499. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8500. {
  8501. TColor Result = GetWindowColor(FSessionColor);
  8502. return Result;
  8503. }
  8504. //---------------------------------------------------------------------------
  8505. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8506. {
  8507. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8508. return Result;
  8509. }
  8510. //---------------------------------------------------------------------------
  8511. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8512. {
  8513. if (!FSessionChanging)
  8514. {
  8515. TTerminalManager::Instance()->UpdateAppTitle();
  8516. }
  8517. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8518. // background to gray on Windows 7 (works on Windows 10).
  8519. // See also EnableControl
  8520. if (Showing)
  8521. {
  8522. if (ManagedSession != NULL)
  8523. {
  8524. // Update path when it changes
  8525. if ((SessionsPageControl->ActivePage != NULL) &&
  8526. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8527. {
  8528. UpdateSessionTab(SessionsPageControl->ActivePage);
  8529. }
  8530. }
  8531. NonVisualDataModule->ReconnectSessionAction->Update();
  8532. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8533. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8534. CenterReconnectToolbar();
  8535. bool HasTerminal = HasActiveTerminal();
  8536. RemoteDirView->Enabled = HasTerminal;
  8537. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8538. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8539. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8540. RemoteDriveView->Color = RemoteDirView->Color;
  8541. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8542. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8543. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8544. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8545. QueueFileList->Enabled = QueueView3->Enabled;
  8546. QueueFileList->Color = QueueView3->Color;
  8547. QueueFileList->Font->Color = QueueView3->Font->Color;
  8548. QueueLabelUpdateStatus();
  8549. RemoteDirView->DarkMode = WinConfiguration->UseDarkTheme();
  8550. RemoteDriveView->DarkMode = RemoteDirView->DarkMode;
  8551. if (FImmersiveDarkMode != WinConfiguration->UseDarkTheme())
  8552. {
  8553. UpdateDarkMode();
  8554. }
  8555. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8556. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8557. }
  8558. }
  8559. //---------------------------------------------------------------------------
  8560. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8561. {
  8562. UpdateControls();
  8563. }
  8564. //---------------------------------------------------------------------------
  8565. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8566. TObject * Sender)
  8567. {
  8568. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8569. DebugAssert(DirView != NULL);
  8570. DoDirViewLoaded(DirView);
  8571. TransferPresetAutoSelect();
  8572. }
  8573. //---------------------------------------------------------------------------
  8574. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8575. {
  8576. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8577. // first run after installation
  8578. if (double(Updates.LastCheck) == 0)
  8579. {
  8580. AppLog(L"First run, scheduling updates check for the next run");
  8581. // make sure next time there will be an update (if enabled)
  8582. Updates.LastCheck = TDateTime(1);
  8583. WinConfiguration->Updates = Updates;
  8584. }
  8585. else
  8586. {
  8587. TDateTime Period;
  8588. if (IsUWP() && !IsOfficialPackage())
  8589. {
  8590. Period = DefaultUpdatesPeriod;
  8591. AppLog(L"Thirdparty UWP package, using default updates check period");
  8592. }
  8593. else
  8594. {
  8595. Period = Updates.Period;
  8596. }
  8597. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8598. if (double(Period) > 0)
  8599. {
  8600. TDateTime Interval = Now() - Updates.LastCheck;
  8601. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8602. if (Interval >= Period)
  8603. {
  8604. StartUpdateThread(UpdatesChecked);
  8605. }
  8606. }
  8607. }
  8608. }
  8609. //---------------------------------------------------------------------------
  8610. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8611. {
  8612. AppLog(L"Updates check done");
  8613. UnicodeString Message;
  8614. bool New;
  8615. TQueryType Type;
  8616. GetUpdatesMessage(Message, New, Type, false);
  8617. if (!Message.IsEmpty())
  8618. {
  8619. AppLogFmt(L"Updates check message: %s", (Message));
  8620. if (New)
  8621. {
  8622. AppLog(L"New version detected");
  8623. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8624. }
  8625. if (!New && (Type != qtWarning))
  8626. {
  8627. AppLog(L"Posting non-critical updates note");
  8628. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8629. }
  8630. else
  8631. {
  8632. AppLog(L"Posting new version or critical message notification");
  8633. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8634. }
  8635. if (New)
  8636. {
  8637. Configuration->Usage->Inc(L"UpdateNotifications");
  8638. }
  8639. }
  8640. }
  8641. //---------------------------------------------------------------------------
  8642. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8643. {
  8644. RestoreApp();
  8645. bool CanDisplay = !NonVisualDataModule->Busy;
  8646. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8647. {
  8648. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8649. }
  8650. if (CanDisplay)
  8651. {
  8652. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8653. CheckForUpdates(true);
  8654. }
  8655. else
  8656. {
  8657. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8658. }
  8659. }
  8660. //---------------------------------------------------------------------------
  8661. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8662. TCopyParamRuleData & Data)
  8663. {
  8664. DebugAssert(Terminal != NULL);
  8665. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8666. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8667. Data.RemoteDirectory = RemoteDirView->PathName;
  8668. }
  8669. //---------------------------------------------------------------------------
  8670. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8671. {
  8672. // Terminal can be null when we are changing local directory implicitly,
  8673. // because it has been deleted, while no session is connected
  8674. // (Login dialog is open)
  8675. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8676. {
  8677. DebugAssert(!IsLocalBrowserMode());
  8678. TCopyParamRuleData Data;
  8679. GetTransferPresetAutoSelectData(Data);
  8680. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8681. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8682. if (CopyParamIndex < 0)
  8683. {
  8684. // there is no preset that matches autoselection
  8685. // set preset that we consider "default"
  8686. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8687. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8688. }
  8689. else
  8690. {
  8691. // there is preset matching autoselection
  8692. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8693. if (CopyParamName == FCopyParamAutoSelected)
  8694. {
  8695. // autoselected the same preset as the last time
  8696. // make no change (i.e. preserve custom user preset, if any)
  8697. }
  8698. else
  8699. {
  8700. // autoselected the different preset then the last time (or there
  8701. // was default preset set)
  8702. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8703. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8704. }
  8705. }
  8706. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8707. {
  8708. if (CopyParamIndex >= 0)
  8709. {
  8710. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8711. }
  8712. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8713. try
  8714. {
  8715. int Fmt =
  8716. (CopyParamIndex < 0) ?
  8717. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8718. COPY_PARAM_AUTOSELECTED;
  8719. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8720. Data->Message = MainInstructions(Message);
  8721. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8722. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8723. CopyParamAttrs);
  8724. if (CopyParamIndex >= 0)
  8725. {
  8726. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8727. Info = FORMAT(L"%s\n \n%s", (Info,
  8728. FMTLOAD(COPY_PARAM_RULE,
  8729. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8730. }
  8731. Data->Message += L"\n\n" + Info;
  8732. if (WinConfiguration->CopyParamAutoSelectNotice)
  8733. {
  8734. TransferPresetNoteMessage(Data, true);
  8735. }
  8736. else
  8737. {
  8738. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  8739. Data = NULL; // ownership passed
  8740. }
  8741. }
  8742. __finally
  8743. {
  8744. delete Data;
  8745. }
  8746. }
  8747. }
  8748. }
  8749. //---------------------------------------------------------------------------
  8750. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  8751. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  8752. {
  8753. DebugAssert(NoteData != NULL);
  8754. DebugAssert(!IsLocalBrowserMode());
  8755. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  8756. TQueryButtonAlias Aliases[1];
  8757. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  8758. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  8759. Params.Aliases = Aliases;
  8760. Params.AliasesCount = LENOF(Aliases);
  8761. unsigned int Result =
  8762. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  8763. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  8764. switch (Result)
  8765. {
  8766. case qaNeverAskAgain:
  8767. DebugAssert(AllowNeverAskAgain);
  8768. WinConfiguration->CopyParamAutoSelectNotice = false;
  8769. break;
  8770. case qaIgnore:
  8771. PreferencesDialog(pmPresets);
  8772. break;
  8773. }
  8774. }
  8775. //---------------------------------------------------------------------------
  8776. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  8777. {
  8778. // as of now useless, as this is used for notes only, never for balloons, ...
  8779. RestoreApp();
  8780. // .. and we should never be busy here
  8781. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  8782. {
  8783. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  8784. }
  8785. }
  8786. //---------------------------------------------------------------------------
  8787. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  8788. TPreferencesMode APreferencesMode)
  8789. {
  8790. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  8791. TCopyParamRuleData Data;
  8792. if (Terminal != NULL)
  8793. {
  8794. PreferencesData.reset(new TPreferencesDialogData());
  8795. GetTransferPresetAutoSelectData(Data);
  8796. PreferencesData->CopyParamRuleData = &Data;
  8797. }
  8798. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  8799. }
  8800. //---------------------------------------------------------------------------
  8801. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  8802. const TCustomCommandType & Command)
  8803. {
  8804. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  8805. {
  8806. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  8807. }
  8808. }
  8809. //---------------------------------------------------------------------------
  8810. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  8811. {
  8812. bool RemoteAllowed = CustomCommandRemoteAllowed();
  8813. TCustomCommandType Command;
  8814. // make sure we use local custom command when remote are not supported
  8815. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  8816. {
  8817. Command = FLastCustomCommand;
  8818. }
  8819. else
  8820. {
  8821. Command.Params = Command.Params | ccLocal;
  8822. }
  8823. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  8824. FEditingFocusedAdHocCommand = OnFocused;
  8825. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  8826. int Options =
  8827. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  8828. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  8829. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  8830. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  8831. {
  8832. FLastCustomCommand = Command;
  8833. UpdateCustomCommandsToolbar();
  8834. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  8835. }
  8836. }
  8837. //---------------------------------------------------------------------------
  8838. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  8839. {
  8840. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  8841. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  8842. DebugAssert(State > 0);
  8843. if (State <= 0)
  8844. {
  8845. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  8846. }
  8847. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  8848. }
  8849. //---------------------------------------------------------------------------
  8850. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  8851. TCustomCommandType & Command, int & State)
  8852. {
  8853. bool Result = !FLastCustomCommand.Command.IsEmpty();
  8854. if (Result)
  8855. {
  8856. Command = FLastCustomCommand;
  8857. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  8858. }
  8859. return Result;
  8860. }
  8861. //---------------------------------------------------------------------------
  8862. void __fastcall TCustomScpExplorerForm::BeforeAction()
  8863. {
  8864. ResetIncrementalSearch();
  8865. }
  8866. //---------------------------------------------------------------------------
  8867. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  8868. {
  8869. DebugAssert(ComponentVisible[Component]);
  8870. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  8871. }
  8872. //---------------------------------------------------------------------------
  8873. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  8874. {
  8875. // when queue panel is resized here directly, the status bar is stretched
  8876. // over whole space the panel occupied
  8877. PostComponentHide(fcQueueView);
  8878. }
  8879. //---------------------------------------------------------------------------
  8880. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  8881. {
  8882. ComponentVisible[fcQueueFileList] = false;
  8883. }
  8884. //---------------------------------------------------------------------------
  8885. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  8886. {
  8887. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  8888. RefreshColorMode();
  8889. ResetSysDarkTheme();
  8890. ConfigurationChanged();
  8891. ConfigureInterface();
  8892. // Should be called for all controls
  8893. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  8894. }
  8895. //---------------------------------------------------------------------------
  8896. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  8897. {
  8898. // Do not handle, when shutting down anyway (maybe also when not setup completelly yet?)
  8899. if (!FInvalid &&
  8900. (Message.LParam != 0) &&
  8901. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  8902. {
  8903. ThemeChanged();
  8904. }
  8905. TForm::Dispatch(&Message);
  8906. }
  8907. //---------------------------------------------------------------------------
  8908. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  8909. {
  8910. TMessage * M = static_cast<TMessage*>(Message);
  8911. switch (M->Msg)
  8912. {
  8913. case CM_DIALOGCHAR:
  8914. CMDialogChar(*M);
  8915. break;
  8916. case WM_APPCOMMAND:
  8917. WMAppCommand(*M);
  8918. break;
  8919. case WM_SYSCOMMAND:
  8920. WMSysCommand(*M);
  8921. break;
  8922. case WM_QUERYENDSESSION:
  8923. WMQueryEndSession(*M);
  8924. break;
  8925. case WM_ENDSESSION:
  8926. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  8927. break;
  8928. #ifdef _DEBUG
  8929. case WM_WINDOWPOSCHANGED:
  8930. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  8931. break;
  8932. case CM_CUSTOMSTYLECHANGED:
  8933. TForm::Dispatch(Message);
  8934. break;
  8935. #endif
  8936. case WM_COMPONENT_HIDE:
  8937. {
  8938. Byte Component = static_cast<Byte>(M->WParam);
  8939. // sanity check
  8940. if (ComponentVisible[Component])
  8941. {
  8942. // special treatment
  8943. if (Component == fcQueueView)
  8944. {
  8945. ToggleQueueVisibility();
  8946. DebugAssert(!ComponentVisible[fcQueueView]);
  8947. }
  8948. else
  8949. {
  8950. ComponentVisible[Component] = false;
  8951. }
  8952. }
  8953. }
  8954. break;
  8955. case WM_COPYDATA:
  8956. WMCopyData(*M);
  8957. break;
  8958. case WM_MANAGES_CAPTION:
  8959. // caption managed in TTerminalManager::UpdateAppTitle()
  8960. M->Result = 1;
  8961. break;
  8962. case WM_WANTS_MOUSEWHEEL:
  8963. M->Result = 1;
  8964. break;
  8965. case CM_SHOWINGCHANGED:
  8966. CMShowingChanged(*M);
  8967. break;
  8968. case WM_CLOSE:
  8969. WMClose(*M);
  8970. break;
  8971. case WM_DPICHANGED:
  8972. WMDpiChanged(*M);
  8973. break;
  8974. case CM_DPICHANGED:
  8975. CMDpiChanged(*M);
  8976. break;
  8977. case WM_SETTINGCHANGE:
  8978. WMSettingChange(*M);
  8979. break;
  8980. case CM_DIALOGKEY:
  8981. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  8982. break;
  8983. default:
  8984. TForm::Dispatch(Message);
  8985. break;
  8986. }
  8987. }
  8988. //---------------------------------------------------------------------------
  8989. void __fastcall TCustomScpExplorerForm::UpdateImages()
  8990. {
  8991. // noop
  8992. }
  8993. //---------------------------------------------------------------------------
  8994. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  8995. {
  8996. TForm::Dispatch(&Message);
  8997. FSessionColors->Clear();
  8998. AddFixedSessionImages();
  8999. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9000. UpdateImages();
  9001. }
  9002. //---------------------------------------------------------------------------
  9003. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9004. {
  9005. TForm::Dispatch(&Message);
  9006. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9007. UpdatePixelsPerInchMainWindowCounter();
  9008. }
  9009. //---------------------------------------------------------------------------
  9010. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9011. {
  9012. // Cannot close window while we are busy.
  9013. // We cannot test this in FormCloseQuery as that is called also from
  9014. // Close(), which is called by CloseApplicationAction. So we can be busy
  9015. // there already even, when it is legitimate to close the application.
  9016. // Possibly a better place to handle this would be WMSysCommand.
  9017. if (NonVisualDataModule->Busy)
  9018. {
  9019. Message.Result = 1;
  9020. }
  9021. else
  9022. {
  9023. TForm::Dispatch(&Message);
  9024. }
  9025. }
  9026. //---------------------------------------------------------------------------
  9027. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9028. {
  9029. if (!FShowingChanged)
  9030. {
  9031. AddStartupSequence(L"D");
  9032. FShowingChanged = true;
  9033. }
  9034. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9035. bool NoSession = (ManagedSession == NULL);
  9036. // This calls TCustomScpExplorerForm::DoShow
  9037. TForm::Dispatch(&Message);
  9038. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9039. if (Showing && !FStarted)
  9040. {
  9041. FStarted = true;
  9042. InterfaceStarted();
  9043. }
  9044. if (Showing && NoSession)
  9045. {
  9046. // When we are starting minimized (i.e. from an installer),
  9047. // postpone showing Login dialog until we get restored.
  9048. // Otherwise the Login dialog (and Authentication window) show restored
  9049. // over invisible (minimized) main window.
  9050. if (WindowState == wsMinimized)
  9051. {
  9052. FNeedSession = true;
  9053. }
  9054. else
  9055. {
  9056. // This happens before application ever goes idle, so the toolbars would
  9057. // stay enabled (initial state) until the Login dialog is dismissed.
  9058. UpdateActions();
  9059. NonVisualDataModule->StartBusy();
  9060. try
  9061. {
  9062. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9063. // otherwise the dialog does not receive focus.
  9064. // With Commander interface the ProcessMessages is called already
  9065. // by TDriveView, but with Explorer interface, we need to call it explicily
  9066. Application->ProcessMessages();
  9067. // do not reload sessions, they have been loaded just now (optimization)
  9068. NeedSession(true);
  9069. }
  9070. __finally
  9071. {
  9072. NonVisualDataModule->EndBusy();
  9073. }
  9074. }
  9075. }
  9076. }
  9077. //---------------------------------------------------------------------------
  9078. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9079. {
  9080. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9081. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9082. }
  9083. //---------------------------------------------------------------------------
  9084. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9085. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9086. int & MaxHeight)
  9087. {
  9088. // workaround for bug in TWinControl.CalcConstraints
  9089. // Check for empty rect (restore from iconic state) is done there only after
  9090. // call to AdjustClientRect, which enlarges the rect (for forms).
  9091. TRect R = GetClientRect();
  9092. // when restoring from iconic state, place no restrictions
  9093. if (IsRectEmpty(R))
  9094. {
  9095. MinWidth = 0;
  9096. MinHeight = 0;
  9097. MaxWidth = 32000;
  9098. MaxHeight = 32000;
  9099. }
  9100. }
  9101. //---------------------------------------------------------------------------
  9102. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9103. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9104. {
  9105. // terminal can be already closed (e.g. dropped connection)
  9106. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9107. {
  9108. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9109. try
  9110. {
  9111. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9112. }
  9113. catch(...)
  9114. {
  9115. if (!Terminal->Active)
  9116. {
  9117. Close = true;
  9118. }
  9119. throw;
  9120. }
  9121. }
  9122. }
  9123. //---------------------------------------------------------------------------
  9124. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9125. {
  9126. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9127. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9128. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9129. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9130. {
  9131. OnGetSpaceAvailable = GetSpaceAvailable;
  9132. }
  9133. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9134. OnGetSpaceAvailable);
  9135. }
  9136. //---------------------------------------------------------------------------
  9137. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9138. {
  9139. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9140. Terminal->FillSessionDataForCode(Data.get());
  9141. return Data.release();
  9142. }
  9143. //---------------------------------------------------------------------------
  9144. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9145. {
  9146. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9147. DoGenerateUrlDialog(Data.get(), Paths);
  9148. }
  9149. //---------------------------------------------------------------------------
  9150. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9151. {
  9152. GenerateUrl(NULL);
  9153. }
  9154. //---------------------------------------------------------------------------
  9155. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9156. {
  9157. std::unique_ptr<TStrings> Paths(new TStringList());
  9158. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9159. GenerateUrl(Paths.get());
  9160. }
  9161. //---------------------------------------------------------------------------
  9162. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9163. {
  9164. FSessionColor = value;
  9165. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9166. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9167. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9168. DebugAssert(ColorItem != NULL);
  9169. ColorItem->Color = C;
  9170. NonVisualDataModule->ColorMenuItem->Color = C;
  9171. UpdateControls();
  9172. }
  9173. //---------------------------------------------------------------------------
  9174. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9175. {
  9176. if (value != FSessionColor)
  9177. {
  9178. UpdateSessionColor(value);
  9179. // Is null when called from LastTerminalClosed
  9180. if (Terminal != NULL)
  9181. {
  9182. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9183. }
  9184. }
  9185. }
  9186. //---------------------------------------------------------------------------
  9187. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9188. {
  9189. bool Result = FNoteTimer->Enabled;
  9190. if (Result)
  9191. {
  9192. // cannot cancel note too early
  9193. bool NotEarly =
  9194. (Now() - FNoteShown >
  9195. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9196. if (Force || NotEarly)
  9197. {
  9198. FNoteTimer->Enabled = false;
  9199. FNote = L"";
  9200. SAFE_DESTROY(FNoteData);
  9201. FOnNoteClick = NULL;
  9202. FNoteHints = FNotes->Text;
  9203. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9204. UpdateStatusBar();
  9205. }
  9206. }
  9207. return Result;
  9208. }
  9209. //---------------------------------------------------------------------------
  9210. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9211. {
  9212. DebugAssert(FNoteTimer->Enabled);
  9213. CancelNote(true);
  9214. }
  9215. //---------------------------------------------------------------------------
  9216. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9217. {
  9218. FNoteHints = FNotes->Text.TrimRight();
  9219. }
  9220. //---------------------------------------------------------------------------
  9221. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9222. {
  9223. int P = Note.Pos(L"\n");
  9224. if (P > 0)
  9225. {
  9226. Note.SetLength(P - 1);
  9227. }
  9228. FNotes->Add(FORMAT(L"[%s] %s",
  9229. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9230. while (FNotes->Count > 10)
  9231. {
  9232. FNotes->Delete(0);
  9233. }
  9234. if (UpdateNow)
  9235. {
  9236. UpdateNoteHints();
  9237. UpdateStatusBar();
  9238. }
  9239. }
  9240. //---------------------------------------------------------------------------
  9241. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9242. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9243. {
  9244. int P = Note.Pos(L"\n");
  9245. if (P > 0)
  9246. {
  9247. Note.SetLength(P - 1);
  9248. }
  9249. UpdateNoteHints();
  9250. FNote = Note;
  9251. SAFE_DESTROY(FNoteData);
  9252. FNoteData = NoteData;
  9253. FOnNoteClick = OnNoteClick;
  9254. AddNote(Note, false);
  9255. UpdateStatusBar();
  9256. FNoteShown = Now();
  9257. FNoteTimer->Enabled = false;
  9258. if (Seconds == 0)
  9259. {
  9260. Seconds = WinConfiguration->NotificationsTimeout;
  9261. }
  9262. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9263. FNoteTimer->Enabled = true;
  9264. }
  9265. //---------------------------------------------------------------------------
  9266. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9267. {
  9268. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9269. }
  9270. //---------------------------------------------------------------------------
  9271. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9272. {
  9273. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9274. {
  9275. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9276. }
  9277. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9278. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9279. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9280. 0, NULL, NULL);
  9281. }
  9282. //---------------------------------------------------------------------------
  9283. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9284. {
  9285. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9286. UnicodeString Note =
  9287. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9288. PostNote(Note, 0, NULL, NULL);
  9289. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9290. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9291. }
  9292. //---------------------------------------------------------------------------
  9293. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9294. {
  9295. WinConfiguration->FormatSizeBytes = Style;
  9296. }
  9297. //---------------------------------------------------------------------------
  9298. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9299. {
  9300. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9301. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9302. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9303. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9304. }
  9305. //---------------------------------------------------------------------------
  9306. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9307. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9308. {
  9309. if (Panel->Index == 0)
  9310. {
  9311. if (FOnNoteClick != NULL)
  9312. {
  9313. // prevent the user data from being freed by possible call
  9314. // to CancelNote or PostNote during call to OnNoteClick
  9315. std::unique_ptr<TObject> NoteData(FNoteData);
  9316. TNotifyEvent OnNoteClick = FOnNoteClick;
  9317. FNoteData = NULL;
  9318. // need to cancel the note as we are going to delete its user data
  9319. CancelNote(true);
  9320. OnNoteClick(NoteData.get());
  9321. }
  9322. }
  9323. if (HasActiveTerminal() &&
  9324. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9325. {
  9326. FileSystemInfo();
  9327. }
  9328. }
  9329. //---------------------------------------------------------------------------
  9330. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9331. {
  9332. // workaround:
  9333. // 1) for unknown reason, disabling window, while minimized,
  9334. // prevents it from restoring, even if it was enabled again meanwhile
  9335. // 2) when disabling the main window, while another has focus
  9336. // minimize is no longer possible
  9337. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9338. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9339. // Shouldn't we use IsApplicationMinimized() here?
  9340. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9341. {
  9342. Enabled = false;
  9343. }
  9344. FLockLevel++;
  9345. }
  9346. //---------------------------------------------------------------------------
  9347. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9348. {
  9349. DebugAssert(FLockLevel > 0);
  9350. FLockLevel--;
  9351. if (FLockLevel == 0)
  9352. {
  9353. DebugAssert(FLockSuspendLevel == 0);
  9354. Enabled = true;
  9355. }
  9356. }
  9357. //---------------------------------------------------------------------------
  9358. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9359. {
  9360. // We need to make sure that window is enabled when the last modal window closes
  9361. // otherwise focus is not restored correctly.
  9362. // So we re-enable the window when modal window opens and
  9363. // disable it back after is closes
  9364. if (FLockLevel > 0)
  9365. {
  9366. // while we have nesting counter, we know that we never be called
  9367. // recursivelly as Application->OnModalBegin is called only
  9368. // for the top-level modal window
  9369. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9370. {
  9371. // won't be disabled when conditions in LockWindow() were not satisfied
  9372. FDisabledOnLockSuspend = !Enabled;
  9373. // When minimized to tray (or actually when set to SW_HIDE),
  9374. // setting Enabled makes the window focusable even when there's
  9375. // modal window over it
  9376. if (!FTrayIcon->Visible)
  9377. {
  9378. Enabled = true;
  9379. }
  9380. }
  9381. FLockSuspendLevel++;
  9382. }
  9383. }
  9384. //---------------------------------------------------------------------------
  9385. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9386. {
  9387. if (FLockSuspendLevel > 0)
  9388. {
  9389. DebugAssert(FLockLevel > 0);
  9390. FLockSuspendLevel--;
  9391. // see comment in SuspendWindowLock
  9392. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9393. {
  9394. // Note that window can be enabled here, when we were minized to tray when
  9395. // was SuspendWindowLock() called.
  9396. // We should possibly do the same check as in LockWindow(),
  9397. // if it is ever possible that the consitions change between
  9398. // SuspendWindowLock() and ResumeWindowLock()
  9399. Enabled = !FDisabledOnLockSuspend;
  9400. }
  9401. }
  9402. }
  9403. //---------------------------------------------------------------------------
  9404. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9405. {
  9406. TTBXComboBoxItem * RemotePathComboBox =
  9407. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9408. if (!TextOnly)
  9409. {
  9410. TStrings * Items = RemotePathComboBox->Strings;
  9411. Items->BeginUpdate();
  9412. try
  9413. {
  9414. Items->Clear();
  9415. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9416. {
  9417. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9418. while (!IsUnixRootPath(APath))
  9419. {
  9420. int P = APath.LastDelimiter(L'/');
  9421. DebugAssert(P >= 0);
  9422. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9423. APath.SetLength(P - 1);
  9424. }
  9425. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9426. }
  9427. }
  9428. __finally
  9429. {
  9430. Items->EndUpdate();
  9431. }
  9432. }
  9433. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9434. // Setting ItemIndex to -1 does not reset its text
  9435. if (RemotePathComboBox->Strings->Count == 0)
  9436. {
  9437. RemotePathComboBox->Text = L"";
  9438. }
  9439. }
  9440. //---------------------------------------------------------------------------
  9441. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9442. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9443. {
  9444. if (AIndex < 0)
  9445. {
  9446. AIndex = Sender->ItemIndex;
  9447. }
  9448. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9449. }
  9450. //---------------------------------------------------------------------------
  9451. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9452. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9453. int & ImageIndex)
  9454. {
  9455. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9456. }
  9457. //---------------------------------------------------------------------------
  9458. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9459. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9460. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9461. {
  9462. if (!IsLocalBrowserMode())
  9463. {
  9464. ARect.Left += (10 * AIndex);
  9465. }
  9466. }
  9467. //---------------------------------------------------------------------------
  9468. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9469. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9470. {
  9471. AWidth += (10 * AIndex);
  9472. }
  9473. //---------------------------------------------------------------------------
  9474. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9475. {
  9476. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9477. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9478. int Index = RemotePathComboBox->ItemIndex;
  9479. while (Index < RemotePathComboBox->Strings->Count - 1)
  9480. {
  9481. APath = UnixExtractFileDir(APath);
  9482. Index++;
  9483. }
  9484. // VanDyke style paths
  9485. if (APath.IsEmpty())
  9486. {
  9487. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9488. APath = ROOTDIRECTORY;
  9489. }
  9490. if (RemoteDirView->Path != APath)
  9491. {
  9492. RemoteDirView->Path = APath;
  9493. }
  9494. }
  9495. //---------------------------------------------------------------------------
  9496. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9497. {
  9498. DoRemotePathComboBoxItemClick(Sender);
  9499. }
  9500. //---------------------------------------------------------------------------
  9501. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9502. {
  9503. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9504. DebugUsedParam(Sender);
  9505. UpdateRemotePathComboBox(true);
  9506. }
  9507. //---------------------------------------------------------------------------
  9508. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9509. {
  9510. DoRemotePathComboBoxCancel(Sender);
  9511. }
  9512. //---------------------------------------------------------------------------
  9513. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9514. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9515. {
  9516. ResetIncrementalSearch();
  9517. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9518. DebugAssert(DirView != NULL);
  9519. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9520. {
  9521. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9522. // OnEditing is called also from TCustomListView::CanEdit
  9523. if (Edit != NULL)
  9524. {
  9525. EditSelectBaseName(Edit);
  9526. }
  9527. }
  9528. }
  9529. //---------------------------------------------------------------------------
  9530. //---------------------------------------------------------------------------
  9531. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9532. {
  9533. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9534. Result->AutoDetectDnD = false;
  9535. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9536. Result->RenderDataOn = rdoEnterAndDropSync;
  9537. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9538. return Result;
  9539. }
  9540. //---------------------------------------------------------------------------
  9541. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9542. {
  9543. if (IsWin10Build(2004))
  9544. {
  9545. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9546. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9547. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9548. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9549. }
  9550. }
  9551. //---------------------------------------------------------------------------
  9552. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9553. {
  9554. TForm::CreateWnd();
  9555. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9556. UpdateDarkMode();
  9557. if (FSessionsDragDropFilesEx == NULL)
  9558. {
  9559. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9560. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9561. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9562. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9563. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9564. }
  9565. if (FQueueDragDropFilesEx == NULL)
  9566. {
  9567. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9568. // No need to set OnDragOver as we do not have any restrictions
  9569. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9570. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9571. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9572. }
  9573. }
  9574. //---------------------------------------------------------------------------
  9575. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9576. {
  9577. TForm::DestroyWnd();
  9578. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9579. FQueueDragDropFilesEx->DragDropControl = NULL;
  9580. }
  9581. //---------------------------------------------------------------------------
  9582. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9583. {
  9584. SideEnter(FCurrentSide);
  9585. FEverShown = true;
  9586. }
  9587. //---------------------------------------------------------------------------
  9588. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9589. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9590. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9591. {
  9592. if (!NonVisualDataModule->Busy)
  9593. {
  9594. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9595. Configuration->Usage->Inc(L"FileFinds");
  9596. LockWindow(true);
  9597. NonVisualDataModule->StartBusy();
  9598. WinConfiguration->LockedInterface = true;
  9599. try
  9600. {
  9601. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9602. }
  9603. __finally
  9604. {
  9605. WinConfiguration->LockedInterface = false;
  9606. NonVisualDataModule->EndBusy();
  9607. UnlockWindow();
  9608. }
  9609. }
  9610. }
  9611. //---------------------------------------------------------------------------
  9612. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9613. {
  9614. if (!NonVisualDataModule->Busy)
  9615. {
  9616. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9617. SetFocus();
  9618. RemoteDirView->Path = UnixExtractFilePath(Path);
  9619. UnicodeString FileName = UnixExtractFileName(Path);
  9620. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9621. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9622. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9623. if (Item == NULL)
  9624. {
  9625. ReloadDirectory(osRemote);
  9626. Item = RemoteDirView->FindFileItem(FileName);
  9627. }
  9628. if (Item != NULL)
  9629. {
  9630. RemoteDirView->ItemFocused = Item;
  9631. RemoteDirView->ItemFocused->MakeVisible(false);
  9632. RemoteDirView->SetFocus();
  9633. }
  9634. }
  9635. }
  9636. //---------------------------------------------------------------------------
  9637. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9638. {
  9639. bool Result = !NonVisualDataModule->Busy;
  9640. if (Result)
  9641. {
  9642. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9643. }
  9644. return Result;
  9645. }
  9646. //---------------------------------------------------------------------------
  9647. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9648. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9649. {
  9650. if (CanOperateOnFoundFiles(ATerminal))
  9651. {
  9652. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  9653. FOnFileOperationFinished = OnFileOperationFinished;
  9654. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9655. }
  9656. }
  9657. //---------------------------------------------------------------------------
  9658. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9659. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9660. {
  9661. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9662. }
  9663. //---------------------------------------------------------------------------
  9664. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9665. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9666. {
  9667. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9668. }
  9669. //---------------------------------------------------------------------------
  9670. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9671. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9672. {
  9673. if (CanOperateOnFoundFiles(ATerminal))
  9674. {
  9675. for (int Index = 0; Index < FileList->Count; Index++)
  9676. {
  9677. UnicodeString FileName = FileList->Strings[Index];
  9678. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9679. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9680. OnFileOperationFinished(osRemote, FileName, true);
  9681. }
  9682. }
  9683. }
  9684. //---------------------------------------------------------------------------
  9685. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9686. {
  9687. FFileFindTerminal = Terminal;
  9688. ShowFileFindDialog(
  9689. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  9690. DoDownloadFoundFiles, DoEditFoundFiles);
  9691. }
  9692. //---------------------------------------------------------------------------
  9693. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  9694. {
  9695. FTaskbarList = TaskbarList;
  9696. }
  9697. //---------------------------------------------------------------------------
  9698. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  9699. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  9700. {
  9701. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9702. if (Index >= 0)
  9703. {
  9704. if (Button == mbLeft)
  9705. {
  9706. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  9707. // If switching tab (switching session) takes long enough for user
  9708. // to actually release the button, "mouse down" is still raised,
  9709. // but we do not get "mouse up" event, so dragging is not cancelled,
  9710. // prevent that by not beginning dragging in the first place.
  9711. if (IsKeyPressed(VK_LBUTTON))
  9712. {
  9713. // when user clicks the "+", we get mouse down only after the session
  9714. // is closed, when new session tab is already on X:Y, so dragging
  9715. // starts, prevent that
  9716. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  9717. {
  9718. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9719. if (Terminal != NULL)
  9720. {
  9721. SessionsPageControl->BeginDrag(false);
  9722. }
  9723. }
  9724. }
  9725. }
  9726. else if (Button == mbMiddle)
  9727. {
  9728. // ignore middle-click for "New session tab" and the last local-local tab
  9729. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9730. if ((Session != NULL) && CanCloseSession(Session))
  9731. {
  9732. CloseSessionTab(Index);
  9733. }
  9734. }
  9735. }
  9736. }
  9737. //---------------------------------------------------------------------------
  9738. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  9739. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  9740. {
  9741. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9742. // do not allow dropping on the "+" tab
  9743. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9744. if ((TargetTerminal != NULL) &&
  9745. (SessionsPageControl->ActivePage->PageIndex != Index))
  9746. {
  9747. Configuration->Usage->Inc(L"SessionTabMoves");
  9748. // this is almost redundant as we would recreate tabs in SessionListChanged,
  9749. // but we want to actually prevent that to avoid flicker
  9750. SessionsPageControl->ActivePage->PageIndex = Index;
  9751. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  9752. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  9753. }
  9754. }
  9755. //---------------------------------------------------------------------------
  9756. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  9757. TObject * Sender, TObject * Source, int X, int Y,
  9758. TDragState /*State*/, bool & Accept)
  9759. {
  9760. Accept = (Sender == Source);
  9761. if (Accept)
  9762. {
  9763. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9764. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9765. // do not allow dragging to the "+" tab
  9766. Accept = (Terminal != NULL);
  9767. }
  9768. }
  9769. //---------------------------------------------------------------------------
  9770. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  9771. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  9772. {
  9773. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  9774. if (Index < 0)
  9775. {
  9776. Effect = DROPEFFECT_NONE;
  9777. }
  9778. else
  9779. {
  9780. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9781. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  9782. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  9783. {
  9784. Effect = DROPEFFECT_NONE;
  9785. }
  9786. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  9787. {
  9788. Effect = DROPEFFECT_COPY;
  9789. }
  9790. }
  9791. }
  9792. //---------------------------------------------------------------------------
  9793. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  9794. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  9795. {
  9796. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  9797. // do not allow dropping on local-local, disconnected and the "+" tab
  9798. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  9799. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9800. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  9801. {
  9802. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  9803. if (!IsFileControl(DropSourceControl, osRemote))
  9804. {
  9805. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  9806. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  9807. // Why don't we use Terminal->CurrentDirectory directly?
  9808. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  9809. // do not force queue, drag drop
  9810. false, true);
  9811. }
  9812. }
  9813. }
  9814. //---------------------------------------------------------------------------
  9815. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  9816. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  9817. {
  9818. // Downloads are handled in RemoteFileControlDDEnd
  9819. if (!IsFileControl(DropSourceControl, osRemote))
  9820. {
  9821. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  9822. Terminal->CurrentDirectory,
  9823. // force queue, drag drop
  9824. true, true);
  9825. }
  9826. }
  9827. //---------------------------------------------------------------------------
  9828. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  9829. {
  9830. FShowing = false;
  9831. // Do not save empty workspace
  9832. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  9833. {
  9834. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  9835. UnicodeString Name = WorkspaceName();
  9836. DoSaveWorkspace(
  9837. Name, DataList.get(),
  9838. !Configuration->DisablePasswordStoring &&
  9839. WinConfiguration->AutoSaveWorkspacePasswords, false);
  9840. WinConfiguration->LastStoredSession = Name;
  9841. }
  9842. }
  9843. //---------------------------------------------------------------------------
  9844. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  9845. {
  9846. TManagedTerminal * ManagedTerminal =
  9847. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  9848. if (ManagedTerminal != NULL)
  9849. {
  9850. ManagedTerminal->DirectoryLoaded = Now();
  9851. }
  9852. }
  9853. //---------------------------------------------------------------------------
  9854. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  9855. TListItem * /*Item*/, bool /*Selected*/)
  9856. {
  9857. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  9858. switch (DirView->LastSelectMethod)
  9859. {
  9860. case smKeyboard:
  9861. Configuration->Usage->Inc(L"KeyboardSelections");
  9862. break;
  9863. case smMouse:
  9864. Configuration->Usage->Inc(L"MouseSelections");
  9865. break;
  9866. }
  9867. }
  9868. //---------------------------------------------------------------------------
  9869. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  9870. {
  9871. if (Color != 0)
  9872. {
  9873. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  9874. }
  9875. else
  9876. {
  9877. return FSessionTabImageIndex;
  9878. }
  9879. }
  9880. //---------------------------------------------------------------------------
  9881. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  9882. {
  9883. TPngImageCollectionItem * Item =
  9884. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  9885. FSessionColors->AddPng(Item->PngImage);
  9886. return FSessionColors->Count - 1;
  9887. }
  9888. //---------------------------------------------------------------------------
  9889. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  9890. {
  9891. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  9892. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  9893. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  9894. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  9895. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  9896. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  9897. }
  9898. //---------------------------------------------------------------------------
  9899. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  9900. {
  9901. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  9902. }
  9903. //---------------------------------------------------------------------------
  9904. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  9905. {
  9906. switch (Side)
  9907. {
  9908. case osLocal:
  9909. return FNewLocalTabTabImageIndex;
  9910. case osRemote:
  9911. case osCurrent:
  9912. return FNewRemoteTabTabImageIndex;
  9913. default:
  9914. DebugFail();
  9915. return -1;
  9916. }
  9917. }
  9918. //---------------------------------------------------------------------------
  9919. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  9920. {
  9921. for (int Index = 0; Index < Control->ControlCount; Index++)
  9922. {
  9923. TControl * AControl = Control->Controls[Index];
  9924. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  9925. if (WinControl != NULL)
  9926. {
  9927. CollectItemsWithTextDisplayMode(WinControl);
  9928. }
  9929. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  9930. if (Toolbar != NULL)
  9931. {
  9932. // we care for top-level items only
  9933. TTBCustomItem * Items = Toolbar->Items;
  9934. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  9935. {
  9936. TTBCustomItem * Item = Items->Items[ItemIndex];
  9937. if (((Item->DisplayMode == nbdmImageAndText) ||
  9938. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  9939. EligibleForImageDisplayMode(Item))
  9940. {
  9941. FItemsWithTextDisplayMode.insert(Item);
  9942. }
  9943. }
  9944. }
  9945. }
  9946. }
  9947. //---------------------------------------------------------------------------
  9948. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  9949. {
  9950. return true;
  9951. }
  9952. //---------------------------------------------------------------------------
  9953. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  9954. {
  9955. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  9956. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  9957. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  9958. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  9959. bool Result = true;
  9960. while (Result && (i != FItemsWithTextDisplayMode.end()))
  9961. {
  9962. TTBCustomItem * Item = *i;
  9963. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  9964. if (Label != NULL)
  9965. {
  9966. // optimization
  9967. if (Label->Visible == SelectiveToolbarText)
  9968. {
  9969. Result = false;
  9970. }
  9971. else
  9972. {
  9973. Label->Visible = SelectiveToolbarText;
  9974. }
  9975. }
  9976. else
  9977. {
  9978. // optimization
  9979. if (Item->DisplayMode == DisplayMode)
  9980. {
  9981. Result = false;
  9982. }
  9983. else
  9984. {
  9985. Item->DisplayMode = DisplayMode;
  9986. }
  9987. }
  9988. ++i;
  9989. }
  9990. UpdateNewTabTab();
  9991. return Result;
  9992. }
  9993. //---------------------------------------------------------------------------
  9994. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  9995. {
  9996. DebugFail();
  9997. }
  9998. //---------------------------------------------------------------------------
  9999. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10000. {
  10001. // Among other, a lock level is non zero, while directory is being loaded,
  10002. // even when it happens as a result of dirview navigation,
  10003. // i.e. when TNonVisualDataModule is NOT FBusy.
  10004. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10005. // Among other this prevents a panel auto update to occur while
  10006. // directory is changing.
  10007. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10008. }
  10009. //---------------------------------------------------------------------------
  10010. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10011. {
  10012. // While the window is disabled, we still seem to process menu shortcuts at least,
  10013. // so stop it at least here.
  10014. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10015. bool Result;
  10016. if (Allowed == aaUpdate)
  10017. {
  10018. Result = true;
  10019. }
  10020. else
  10021. {
  10022. Result = !NonVisualDataModule->Busy;
  10023. if (Result && (Allowed == aaShortCut))
  10024. {
  10025. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10026. Action->Update();
  10027. Result = Action->Enabled;
  10028. }
  10029. }
  10030. return Result;
  10031. }
  10032. //---------------------------------------------------------------------------
  10033. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10034. {
  10035. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10036. }
  10037. //---------------------------------------------------------------------------
  10038. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10039. {
  10040. // This is somewhat redundant to LockWindow() call from
  10041. // TTerminalManager::TerminalReadDirectoryProgress.
  10042. // But disabling window is known not to block keyboard shorcuts
  10043. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10044. if (Busy > 0)
  10045. {
  10046. if (NonVisualDataModule->Busy)
  10047. {
  10048. State = false;
  10049. }
  10050. else
  10051. {
  10052. NonVisualDataModule->StartBusy();
  10053. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10054. LockWindow();
  10055. }
  10056. }
  10057. else if (Busy < 0)
  10058. {
  10059. UnlockWindow();
  10060. NonVisualDataModule->EndBusy();
  10061. }
  10062. else
  10063. {
  10064. State = NonVisualDataModule->Busy;
  10065. }
  10066. }
  10067. //---------------------------------------------------------------------------
  10068. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10069. {
  10070. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10071. if (Index >= 0)
  10072. {
  10073. TPopupMenu * PopupMenu = NULL;
  10074. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10075. if (Session != NULL)
  10076. {
  10077. SessionsPageControl->ActivePageIndex = Index;
  10078. if (DebugAlwaysTrue(SessionTabSwitched()))
  10079. {
  10080. // copied from TControl.WMContextMenu
  10081. SendCancelMode(SessionsPageControl);
  10082. // explicit popup instead of using PopupMenu property
  10083. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10084. // while connecting yet not-connected session and hence
  10085. // allowing an access to commands over not-completelly connected session
  10086. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10087. }
  10088. }
  10089. else
  10090. {
  10091. if (SupportsLocalBrowser())
  10092. {
  10093. PopupMenu = NonVisualDataModule->NewTabPopup;
  10094. }
  10095. }
  10096. if (PopupMenu != NULL)
  10097. {
  10098. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10099. PopupMenu->PopupComponent = SessionsPageControl;
  10100. PopupMenu->Popup(Point.x, Point.y);
  10101. }
  10102. }
  10103. Handled = true;
  10104. }
  10105. //---------------------------------------------------------------------------
  10106. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10107. {
  10108. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10109. }
  10110. //---------------------------------------------------------------------------
  10111. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10112. {
  10113. Configuration->Usage->Inc(L"PasswordChanges");
  10114. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10115. ChangePasswordData->DisableAuthentationsExceptPassword();
  10116. ChangePasswordData->ChangePassword = true;
  10117. std::unique_ptr<TTerminal> ChangePasswordSession(
  10118. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10119. ChangePasswordSession->AutoReadDirectory = false;
  10120. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10121. {
  10122. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10123. }
  10124. else
  10125. {
  10126. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10127. }
  10128. }
  10129. //---------------------------------------------------------------------------
  10130. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10131. {
  10132. // No nice way to assert SSH2
  10133. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10134. }
  10135. //---------------------------------------------------------------------------
  10136. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10137. {
  10138. TOperationVisualizer OperationVisualizer;
  10139. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10140. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10141. }
  10142. //---------------------------------------------------------------------------
  10143. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10144. {
  10145. TForm::ChangeScale(M, D);
  10146. int APixelsPerInch = GetControlPixelsPerInch(this);
  10147. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  10148. try
  10149. {
  10150. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  10151. }
  10152. __finally
  10153. {
  10154. GUIConfiguration->ChangeResourceModule(ResourceModule);
  10155. }
  10156. }
  10157. //---------------------------------------------------------------------------
  10158. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10159. {
  10160. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10161. }
  10162. //---------------------------------------------------------------------
  10163. class TPublicControl : public TControl
  10164. {
  10165. friend class TCustomScpExplorerForm;
  10166. };
  10167. //---------------------------------------------------------------------------
  10168. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10169. {
  10170. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10171. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10172. }
  10173. //---------------------------------------------------------------------------
  10174. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10175. {
  10176. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10177. OpenBookmark(Side, Bookmark);
  10178. }
  10179. //---------------------------------------------------------------------------
  10180. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10181. {
  10182. DoBookmarkClick(osLocal, Sender);
  10183. }
  10184. //---------------------------------------------------------------------------
  10185. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10186. {
  10187. DoBookmarkClick(osRemote, Sender);
  10188. }
  10189. //---------------------------------------------------------------------------
  10190. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10191. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10192. {
  10193. if (BookmarkList != NULL)
  10194. {
  10195. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10196. if (IsLocalBrowserMode())
  10197. {
  10198. Side = osLocal;
  10199. }
  10200. if (!WinConfiguration->UseLocationProfiles)
  10201. {
  10202. std::unique_ptr<TStringList> Directories(new TStringList());
  10203. Directories->CaseSensitive = (Side == osRemote);
  10204. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10205. {
  10206. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10207. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10208. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10209. {
  10210. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10211. Item->Caption = EscapeHotkey(Directory);
  10212. Item->ShortCut = Bookmark->ShortCut;
  10213. Item->OnClick = OnBookmarkClick;
  10214. Item->Tag = reinterpret_cast<int>(Bookmark);
  10215. Directories->Add(Directory);
  10216. Menu->Add(Item.release());
  10217. }
  10218. }
  10219. }
  10220. else
  10221. {
  10222. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10223. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10224. {
  10225. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10226. if (!Bookmark->Node.IsEmpty())
  10227. {
  10228. Folders->Add(Bookmark->Node);
  10229. }
  10230. }
  10231. for (int Index = 0; Index < Folders->Count; Index++)
  10232. {
  10233. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10234. Item->Caption = Folders->Strings[Index];
  10235. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10236. Folders->Objects[Index] = Item.get();
  10237. Menu->Add(Item.release());
  10238. }
  10239. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10240. {
  10241. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10242. TTBCustomItem * Parent;
  10243. if (!Bookmark->Node.IsEmpty())
  10244. {
  10245. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10246. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10247. }
  10248. else
  10249. {
  10250. Parent = Menu;
  10251. }
  10252. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10253. Item->Caption = Bookmark->Name;
  10254. Item->ShortCut = Bookmark->ShortCut;
  10255. Item->OnClick = OnBookmarkClick;
  10256. Item->Tag = reinterpret_cast<int>(Bookmark);
  10257. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10258. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10259. {
  10260. // No hint for location profiles that are actually mere "bookmarks"
  10261. }
  10262. else
  10263. {
  10264. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10265. UnicodeString LongHint;
  10266. if (!Bookmark->Local.IsEmpty())
  10267. {
  10268. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10269. }
  10270. if (!Bookmark->Remote.IsEmpty())
  10271. {
  10272. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10273. }
  10274. AddToList(Hint, LongHint, L"|");
  10275. Item->Hint = Hint;
  10276. }
  10277. Parent->Add(Item.release());
  10278. }
  10279. }
  10280. AddMenuSeparator(Menu);
  10281. }
  10282. }
  10283. //---------------------------------------------------------------------------
  10284. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10285. {
  10286. Menu->Clear();
  10287. std::unique_ptr<TTBCustomItem> Item;
  10288. Item.reset(new TTBXItem(Owner));
  10289. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10290. Item->Options = Item->Options << tboDefault;
  10291. Menu->Add(Item.release());
  10292. AddMenuSeparator(Menu);
  10293. if (Terminal != NULL)
  10294. {
  10295. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10296. }
  10297. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10298. Item.reset(new TTBXItem(Owner));
  10299. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10300. Menu->Add(Item.release());
  10301. }
  10302. //---------------------------------------------------------------------------
  10303. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10304. {
  10305. bool Result = true;
  10306. bool Remote = !IsSideLocalBrowser(Side);
  10307. try
  10308. {
  10309. UnicodeString APath = Path;
  10310. if (Remote)
  10311. {
  10312. Terminal->ExceptionOnFail = true;
  10313. }
  10314. else
  10315. {
  10316. APath = ExpandEnvironmentVariables(Path);
  10317. }
  10318. try
  10319. {
  10320. DirView(Side)->Path = APath;
  10321. }
  10322. __finally
  10323. {
  10324. if (Remote)
  10325. {
  10326. Terminal->ExceptionOnFail = false;
  10327. }
  10328. }
  10329. }
  10330. catch (Exception & E)
  10331. {
  10332. if (!Remote || Terminal->Active)
  10333. {
  10334. ShowExtendedExceptionEx(Terminal, &E);
  10335. Result = false;
  10336. }
  10337. else
  10338. {
  10339. throw;
  10340. }
  10341. }
  10342. return Result;
  10343. }
  10344. //---------------------------------------------------------------------------
  10345. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10346. {
  10347. // Make sure there some feedback even when loading tiny local folders
  10348. TInstantOperationVisualizer Visualizer;
  10349. DirView(Side)->ReloadDirectory();
  10350. }
  10351. //---------------------------------------------------------------------------
  10352. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10353. {
  10354. if (Index == SessionsPageControl->TabIndex)
  10355. {
  10356. CloseSession();
  10357. }
  10358. else
  10359. {
  10360. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10361. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10362. TTerminalManager * Manager = TTerminalManager::Instance();
  10363. if (!Terminal->Active)
  10364. {
  10365. Manager->FreeTerminal(Terminal);
  10366. }
  10367. else
  10368. {
  10369. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10370. if (CanCloseQueue(Queue))
  10371. {
  10372. Manager->FreeTerminal(Terminal);
  10373. }
  10374. }
  10375. }
  10376. }
  10377. //---------------------------------------------------------------------------
  10378. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10379. {
  10380. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10381. if (Session == NULL)
  10382. {
  10383. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10384. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10385. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10386. //P = SessionsPageControl->ClientToScreen(P);
  10387. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10388. }
  10389. else
  10390. {
  10391. CloseSessionTab(Index);
  10392. }
  10393. }
  10394. //---------------------------------------------------------------------------
  10395. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10396. {
  10397. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10398. {
  10399. TInstantOperationVisualizer Visualizer;
  10400. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10401. // before we create a new data object
  10402. ClipboardClear();
  10403. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10404. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10405. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10406. // Intermediate variable to WORKAROUND a crash in compiler
  10407. TObjectList * ClipboardFakeMonitors =
  10408. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10409. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10410. if (FClipboardDragDropFilesEx.get() == NULL)
  10411. {
  10412. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10413. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10414. }
  10415. FClipboardDragDropFilesEx->FileList->Clear();
  10416. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10417. FClipboardDragDropFilesEx->CopyToClipboard();
  10418. FClipboardTerminal = Terminal;
  10419. // Need full paths, as cwd can be different once files are pasted
  10420. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10421. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10422. {
  10423. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10424. }
  10425. }
  10426. }
  10427. //---------------------------------------------------------------------------
  10428. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10429. {
  10430. if (OpenClipboard(0))
  10431. {
  10432. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10433. CloseClipboard();
  10434. }
  10435. }
  10436. //---------------------------------------------------------------------------
  10437. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10438. {
  10439. return !FClipboardFakeDirectory.IsEmpty();
  10440. }
  10441. //---------------------------------------------------------------------------
  10442. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10443. {
  10444. RemoveDir(ApiPath(FClipboardFakeDirectory));
  10445. FClipboardFakeDirectory = UnicodeString();
  10446. FClipboardTerminal = NULL;
  10447. if (FDownloadingFromClipboard)
  10448. {
  10449. // We are called by the monitor, so attempt to release it would deadlock
  10450. FClipboardFakeMonitorsPendingReset = true;
  10451. }
  10452. else
  10453. {
  10454. FClipboardFakeMonitors.reset(NULL);
  10455. }
  10456. }
  10457. //---------------------------------------------------------------------------
  10458. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10459. {
  10460. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10461. {
  10462. ClipboardStop();
  10463. }
  10464. }
  10465. //---------------------------------------------------------------------------
  10466. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10467. {
  10468. TTerminalManager * Manager = TTerminalManager::Instance();
  10469. Manager->ActiveSession = FClipboardTerminal;
  10470. TTransferOperationParam Params;
  10471. Params.TargetDirectory = TargetDirectory;
  10472. Params.DragDrop = DragDrop;
  10473. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10474. }
  10475. //---------------------------------------------------------------------------
  10476. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10477. {
  10478. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10479. // (as it pumps a Windows message queue while being shutted down)
  10480. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10481. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10482. {
  10483. // Can fail as it can be e.g. locked by AV, so we retry that later
  10484. bool Removed = RemoveDir(ApiPath(FileName));
  10485. try
  10486. {
  10487. if (!NonVisualDataModule->Busy)
  10488. {
  10489. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10490. FClipboardFakeMonitorsPendingReset = false;
  10491. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10492. TAutoFlag Flag(FDownloadingFromClipboard);
  10493. ClipboardDownload(ExtractFilePath(FileName), NoConfirmation, true);
  10494. }
  10495. }
  10496. __finally
  10497. {
  10498. if (!Removed)
  10499. {
  10500. RemoveDir(ApiPath(FileName));
  10501. }
  10502. }
  10503. }
  10504. }
  10505. //---------------------------------------------------------------------------
  10506. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10507. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10508. {
  10509. TFileMasks::TParams MaskParams;
  10510. MaskParams.Size = Size;
  10511. MaskParams.Modification = Modification;
  10512. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10513. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10514. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10515. if (!Local && Directory)
  10516. {
  10517. FileName = UnixExcludeTrailingBackslash(FileName);
  10518. }
  10519. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10520. {
  10521. bool ImplicitMatch;
  10522. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10523. !ImplicitMatch)
  10524. {
  10525. Color = Iter->Color;
  10526. break;
  10527. }
  10528. }
  10529. }
  10530. //---------------------------------------------------------------------------
  10531. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10532. {
  10533. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10534. if (!DirView->IsEditing())
  10535. {
  10536. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10537. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10538. // while searching
  10539. if (Key == VK_BACK)
  10540. {
  10541. if (!FIncrementalSearch.IsEmpty())
  10542. {
  10543. if (FIncrementalSearch.Length() == 1)
  10544. {
  10545. ResetIncrementalSearch();
  10546. }
  10547. else
  10548. {
  10549. UnicodeString NewText = FIncrementalSearch.SubString(1, FIncrementalSearch.Length() - 1);
  10550. IncrementalSearch(NewText, false, false);
  10551. }
  10552. Key = 0;
  10553. }
  10554. }
  10555. }
  10556. }
  10557. //---------------------------------------------------------------------------
  10558. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10559. {
  10560. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10561. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10562. {
  10563. // Filter control sequences.
  10564. // When not searching yet, prefer use of the space for toggling file selection
  10565. // (so we cannot incrementally search for a string starting with a space).
  10566. if ((Key > VK_SPACE) ||
  10567. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearch.IsEmpty()))
  10568. {
  10569. IncrementalSearch(FIncrementalSearch + Key, false, false);
  10570. Key = 0;
  10571. }
  10572. }
  10573. }
  10574. //---------------------------------------------------------------------------
  10575. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10576. {
  10577. if (!FIncrementalSearch.IsEmpty())
  10578. {
  10579. FIncrementalSearch = L"";
  10580. DirView(osCurrent)->UpdateStatusBar();
  10581. }
  10582. }
  10583. //---------------------------------------------------------------------------
  10584. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10585. {
  10586. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10587. if (Item == NULL)
  10588. {
  10589. MessageBeep(MB_ICONHAND);
  10590. }
  10591. else
  10592. {
  10593. TCustomDirView * ADirView = DirView(osCurrent);
  10594. {
  10595. TAutoNestingCounter Guard(FIncrementalSearching);
  10596. ADirView->FocusItem(Item);
  10597. if (ADirView->NortonLike == nlOff)
  10598. {
  10599. if ((ADirView->Selected != Item) ||
  10600. (ADirView->SelCount > 1))
  10601. {
  10602. ADirView->ClearSelection();
  10603. ADirView->Selected = Item;
  10604. }
  10605. }
  10606. }
  10607. FIncrementalSearch = Text;
  10608. Item->MakeVisible(false);
  10609. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10610. FIncrementalSearchHaveNext = (NextItem != NULL) && (NextItem != Item);
  10611. ADirView->UpdateStatusBar();
  10612. }
  10613. }
  10614. //---------------------------------------------------------------------------
  10615. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  10616. {
  10617. int Index = Item->Index;
  10618. if (!Reverse)
  10619. {
  10620. Index++;
  10621. if (Index >= Item->Owner->Count)
  10622. {
  10623. Index = 0;
  10624. }
  10625. }
  10626. else
  10627. {
  10628. Index--;
  10629. if (Index < 0)
  10630. {
  10631. Index = Item->Owner->Count - 1;
  10632. }
  10633. }
  10634. return Item->Owner->Item[Index];
  10635. }
  10636. //---------------------------------------------------------------------------
  10637. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10638. {
  10639. TCustomDirView * ADirView = DirView(osCurrent);
  10640. if (ADirView->Items->Count == 0)
  10641. {
  10642. return NULL;
  10643. }
  10644. else
  10645. {
  10646. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  10647. TListItem * Item = CurrentItem;
  10648. if (SkipCurrent)
  10649. {
  10650. Item = DebugNotNull(GetNextFile(Item, Reverse));
  10651. }
  10652. while (true)
  10653. {
  10654. bool Matches = false;
  10655. switch (WinConfiguration->PanelSearch)
  10656. {
  10657. case isNameStartOnly:
  10658. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  10659. break;
  10660. case isName:
  10661. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  10662. break;
  10663. case isAll:
  10664. int ColCount = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Count : 1;
  10665. int Index = 0;
  10666. while ((Index < ColCount) && !Matches)
  10667. {
  10668. bool Visible = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Visible[Index] : true;
  10669. if (Visible)
  10670. {
  10671. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  10672. }
  10673. Index++;
  10674. }
  10675. break;
  10676. }
  10677. if (Matches)
  10678. {
  10679. return Item;
  10680. }
  10681. Item = GetNextFile(Item, Reverse);
  10682. if (Item == CurrentItem)
  10683. {
  10684. return NULL;
  10685. }
  10686. }
  10687. }
  10688. }
  10689. //---------------------------------------------------------------------------
  10690. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  10691. {
  10692. ResetIncrementalSearch();
  10693. }
  10694. //---------------------------------------------------------------------------
  10695. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  10696. {
  10697. if (Message.CharCode == VK_TAB)
  10698. {
  10699. if (!FIncrementalSearch.IsEmpty())
  10700. {
  10701. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  10702. bool Reverse = Shift.Contains(ssShift);
  10703. IncrementalSearch(FIncrementalSearch, true, Reverse);
  10704. Message.Result = 1;
  10705. return;
  10706. }
  10707. }
  10708. else if (Message.CharCode == VK_ESCAPE)
  10709. {
  10710. if (!FIncrementalSearch.IsEmpty())
  10711. {
  10712. ResetIncrementalSearch();
  10713. Message.Result = 1;
  10714. return;
  10715. }
  10716. }
  10717. TForm::Dispatch(&Message);
  10718. }
  10719. //---------------------------------------------------------------------------
  10720. void __fastcall TCustomScpExplorerForm::Deactivate()
  10721. {
  10722. TForm::Deactivate();
  10723. // E.g. when switching to an internal editor window
  10724. ResetIncrementalSearch();
  10725. }
  10726. //---------------------------------------------------------------------------
  10727. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  10728. {
  10729. // When switching to another application
  10730. ResetIncrementalSearch();
  10731. }
  10732. //---------------------------------------------------------------------------
  10733. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  10734. {
  10735. ResetIncrementalSearch();
  10736. }
  10737. //---------------------------------------------------------------------------
  10738. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  10739. {
  10740. if (FIncrementalSearching <= 0)
  10741. {
  10742. ResetIncrementalSearch();
  10743. }
  10744. }
  10745. //---------------------------------------------------------------------------
  10746. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  10747. {
  10748. CountClicksForWindowPrint(this);
  10749. }
  10750. //---------------------------------------------------------------------------
  10751. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  10752. {
  10753. CenterReconnectToolbar();
  10754. }
  10755. //---------------------------------------------------------------------------
  10756. void __fastcall TCustomScpExplorerForm::BrowseFile()
  10757. {
  10758. if (RemoteDirView->ItemFocused != NULL)
  10759. {
  10760. RemoteDirView->ItemFocused->Selected = true;
  10761. }
  10762. }
  10763. //---------------------------------------------------------------------------
  10764. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  10765. {
  10766. if (!FQueueStatusUpdating)
  10767. {
  10768. bool Refresh;
  10769. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  10770. {
  10771. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  10772. }
  10773. else
  10774. {
  10775. if (FQueueFileList->GetCount() > 0)
  10776. {
  10777. FQueueFileList->Clear();
  10778. Refresh = true;
  10779. }
  10780. }
  10781. int Count = FQueueFileList->GetCount();
  10782. if (QueueFileList->Items->Count != Count)
  10783. {
  10784. DebugAssert(Refresh);
  10785. QueueFileList->Items->Count = Count;
  10786. }
  10787. if (Refresh)
  10788. {
  10789. QueueFileList->Invalidate();
  10790. }
  10791. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  10792. }
  10793. }
  10794. //---------------------------------------------------------------------------
  10795. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  10796. {
  10797. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  10798. }
  10799. //---------------------------------------------------------------------------
  10800. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  10801. {
  10802. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  10803. // See TSynchronizeChecklistDialog::UpdateTimer
  10804. if (QueueFileList->Items->Count > 0)
  10805. {
  10806. QueueFileList->Items->Item[0]->MakeVisible(false);
  10807. }
  10808. UpdateQueueFileList();
  10809. }
  10810. //---------------------------------------------------------------------------
  10811. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  10812. {
  10813. Active = QueueView3->Focused() || QueueFileList->Focused();
  10814. }
  10815. //---------------------------------------------------------------------------
  10816. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  10817. {
  10818. QueueLabelUpdateStatus();
  10819. }
  10820. //---------------------------------------------------------------------------
  10821. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  10822. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  10823. {
  10824. int State = FQueueFileList->GetState(Item->Index);
  10825. if (State == qfsProcessed)
  10826. {
  10827. Sender->Canvas->Font->Color = clGrayText;
  10828. }
  10829. }
  10830. //---------------------------------------------------------------------------
  10831. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  10832. {
  10833. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  10834. QueueFileList->Column[0]->Width =
  10835. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  10836. }
  10837. //---------------------------------------------------------------------------
  10838. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  10839. {
  10840. QueueFileListColumnAutoSize();
  10841. }
  10842. //---------------------------------------------------------------------------
  10843. void __fastcall TCustomScpExplorerForm::CloseApp()
  10844. {
  10845. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  10846. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  10847. // So we clear the flag here.
  10848. DebugAssert(NonVisualDataModule->Busy);
  10849. NonVisualDataModule->EndBusy();
  10850. try
  10851. {
  10852. Close();
  10853. }
  10854. __finally
  10855. {
  10856. NonVisualDataModule->StartBusy();
  10857. }
  10858. }
  10859. //---------------------------------------------------------------------------
  10860. bool __fastcall TCustomScpExplorerForm::IsActiveTerminal(TTerminal * Terminal)
  10861. {
  10862. return (Terminal != NULL) && Terminal->Active;
  10863. }
  10864. //---------------------------------------------------------------------------
  10865. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  10866. {
  10867. return (ManagedSession != NULL);
  10868. }
  10869. //---------------------------------------------------------------------------
  10870. bool __fastcall TCustomScpExplorerForm::HasActiveTerminal()
  10871. {
  10872. return IsActiveTerminal(Terminal);
  10873. }
  10874. //---------------------------------------------------------------------------
  10875. void TCustomScpExplorerForm::LocalLocalCopy(
  10876. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  10877. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  10878. {
  10879. DebugFail();
  10880. }
  10881. //---------------------------------------------------------------------------
  10882. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  10883. {
  10884. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  10885. }
  10886. //---------------------------------------------------------------------------
  10887. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  10888. {
  10889. // Changing tab list triggers the OnResize.
  10890. if (!FUpdatingSessionTabs)
  10891. {
  10892. // UpdateTabsCaptionTruncation should be enough
  10893. SessionListChanged(true);
  10894. }
  10895. }
  10896. //---------------------------------------------------------------------------
  10897. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  10898. {
  10899. if (ASession == ManagedSession)
  10900. {
  10901. UpdateSession(ASession);
  10902. }
  10903. TSessionData * Data = ASession->StateData;
  10904. UnicodeString Result;
  10905. if (Side == osLocal)
  10906. {
  10907. Result = Data->LocalDirectory;
  10908. }
  10909. else if (DebugAlwaysTrue(Side == osOther))
  10910. {
  10911. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  10912. }
  10913. return Result;
  10914. }
  10915. //---------------------------------------------------------------------------
  10916. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  10917. {
  10918. UnicodeString Result;
  10919. if (!ASession->Active)
  10920. {
  10921. Result = LoadStr(STATUS_NOT_CONNECTED2);
  10922. }
  10923. else
  10924. {
  10925. Result = GetSessionPath(ASession, osRemote);
  10926. }
  10927. return Result;
  10928. }
  10929. //---------------------------------------------------------------------------
  10930. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  10931. {
  10932. return LoadStr(NEW_REMOTE_TAB_HINT);
  10933. }
  10934. //---------------------------------------------------------------------------
  10935. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  10936. {
  10937. if (Index >= 0)
  10938. {
  10939. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10940. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  10941. if (TabSession == NULL)
  10942. {
  10943. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  10944. if (NewTabTabCaption != TabSheet->Caption)
  10945. {
  10946. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  10947. }
  10948. }
  10949. else
  10950. {
  10951. TTerminalManager * Manager = TTerminalManager::Instance();
  10952. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  10953. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  10954. }
  10955. }
  10956. }
  10957. //---------------------------------------------------------------------------
  10958. typedef std::vector<TListItem *> TListItemsVector;
  10959. struct TCalculateSizeOperation
  10960. {
  10961. TCalculateSizeStats Stats;
  10962. TListItemsVector ListItems;
  10963. size_t Index;
  10964. };
  10965. //---------------------------------------------------------------------------
  10966. void TCustomScpExplorerForm::CalculateDirectorySizes()
  10967. {
  10968. TCalculateSizeOperation CalculateSizeOperation;
  10969. TOperationSide Side = GetSide(osCurrent);
  10970. TCustomDirView * ADirView = DirView(Side);
  10971. bool FullPath = IsSideLocalBrowser(Side);
  10972. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, FullPath, NULL, true));
  10973. std::unique_ptr<TStrings> FileList(new TStringList());
  10974. for (int Index = 0; Index < AllFileList->Count; Index++)
  10975. {
  10976. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  10977. if (ADirView->ItemIsDirectory(Item))
  10978. {
  10979. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  10980. CalculateSizeOperation.ListItems.push_back(Item);
  10981. }
  10982. }
  10983. CalculateSizeOperation.Index = 0;
  10984. __int64 Size = 0;
  10985. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation);
  10986. FCalculateSizeOperation = &CalculateSizeOperation;
  10987. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  10988. FOnFileOperationFinished = DirectorySizeCalculated;
  10989. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation);
  10990. FPrimaryOperation = foCalculateSize;
  10991. TCalculatedSizes CalculatedSizes;
  10992. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  10993. if (Side == osLocal)
  10994. {
  10995. Terminal->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  10996. }
  10997. else
  10998. {
  10999. TCalculateSizeParams Params;
  11000. Params.Stats = &CalculateSizeOperation.Stats;
  11001. Params.UseCache = true;
  11002. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11003. }
  11004. }
  11005. //---------------------------------------------------------------------------
  11006. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool)
  11007. {
  11008. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11009. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11010. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11011. // optimization
  11012. bool GotExpectedItem =
  11013. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11014. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11015. int Index = -1;
  11016. if (DebugAlwaysTrue(GotExpectedItem))
  11017. {
  11018. Index = FCalculateSizeOperation->Index;
  11019. FCalculateSizeOperation->Index++;
  11020. }
  11021. else
  11022. {
  11023. TListItemsVector::iterator I =
  11024. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11025. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11026. {
  11027. Index = I - FCalculateSizeOperation->ListItems.begin();
  11028. }
  11029. }
  11030. if (DebugAlwaysTrue(Index >= 0))
  11031. {
  11032. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11033. ADirView->SetItemCalculatedSize(Item, Size);
  11034. }
  11035. }
  11036. //---------------------------------------------------------------------------
  11037. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11038. {
  11039. Accept = false;
  11040. }
  11041. //---------------------------------------------------------------------------