CustomScpExplorer.cpp 412 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285
  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 "NonVisual.h"
  22. #include "Glyphs.h"
  23. #include "Tools.h"
  24. #include "WinConfiguration.h"
  25. #include "TerminalManager.h"
  26. #include "EditorManager.h"
  27. #include "ProgParams.h"
  28. #include "Setup.h"
  29. #include <Consts.hpp>
  30. #include <DateUtils.hpp>
  31. #include <TB2Common.hpp>
  32. #include <DirectoryMonitor.hpp>
  33. #include <System.IOUtils.hpp>
  34. #include <System.StrUtils.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. #define WM_PASTE_FILES (WM_WINSCP_USER + 14)
  55. static const int SessionPanelCount = 3;
  56. //---------------------------------------------------------------------------
  57. class TMutexGuard
  58. {
  59. public:
  60. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  61. int Timeout = 5000)
  62. {
  63. FMutex = NULL;
  64. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  65. if (WaitResult == WAIT_TIMEOUT)
  66. {
  67. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  68. }
  69. else
  70. {
  71. FMutex = AMutex;
  72. }
  73. }
  74. ~TMutexGuard()
  75. {
  76. if (FMutex != NULL)
  77. {
  78. ReleaseMutex(FMutex);
  79. }
  80. }
  81. private:
  82. HANDLE FMutex;
  83. };
  84. //---------------------------------------------------------------------------
  85. class TWindowLock
  86. {
  87. public:
  88. TWindowLock(TCustomScpExplorerForm * Form) :
  89. FForm(Form)
  90. {
  91. FForm->LockWindow();
  92. }
  93. ~TWindowLock()
  94. {
  95. FForm->UnlockWindow();
  96. }
  97. private:
  98. TCustomScpExplorerForm * FForm;
  99. };
  100. //---------------------------------------------------------------------------
  101. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  102. FForm(Form)
  103. {
  104. FForm->BatchStart(FBatchStorage);
  105. }
  106. //---------------------------------------------------------------------------
  107. TAutoBatch::~TAutoBatch()
  108. {
  109. FForm->BatchEnd(FBatchStorage);
  110. }
  111. //---------------------------------------------------------------------------
  112. struct TTransferOperationParam
  113. {
  114. TTransferOperationParam();
  115. UnicodeString TargetDirectory;
  116. bool Temp;
  117. bool DragDrop;
  118. int Options;
  119. TAutoSwitch Queue;
  120. };
  121. //---------------------------------------------------------------------------
  122. TTransferOperationParam::TTransferOperationParam()
  123. {
  124. Temp = false;
  125. DragDrop = false;
  126. Options = 0;
  127. Queue = asAuto;
  128. }
  129. //---------------------------------------------------------------------------
  130. class TTransferPresetNoteData : public TObject
  131. {
  132. public:
  133. UnicodeString Message;
  134. };
  135. //---------------------------------------------------------------------------
  136. class TTerminalNoteData : public TObject
  137. {
  138. public:
  139. TManagedTerminal * Terminal;
  140. };
  141. //---------------------------------------------------------------------------
  142. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  143. FFormRestored(false),
  144. TForm(Owner)
  145. {
  146. AddStartupSequence(L"F");
  147. FInvalid = false;
  148. FCurrentSide = osRemote;
  149. FEverShown = false;
  150. FDocks = new TList();
  151. InitControls();
  152. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  153. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  154. NonVisualDataModule->ScpExplorer = this;
  155. RestoreParams();
  156. ConfigurationChanged();
  157. RemoteDirView->Invalidate();
  158. FAutoOperation = false;
  159. FOnFileOperationFinished = NULL;
  160. FPrimaryOperation = foNone;
  161. FForceExecution = false;
  162. FIgnoreNextDialogChar = 0;
  163. FErrorList = NULL;
  164. FSynchronizeProgressForm = NULL;
  165. FProgressForm = NULL;
  166. FRefreshLocalDirectory = false;
  167. FRefreshRemoteDirectory = false;
  168. FDDExtMapFile = NULL;
  169. // CreateMutexW keeps failing with ERROR_NOACCESS
  170. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  171. DebugAssert(FDDExtMutex != NULL);
  172. FDDTargetControl = NULL;
  173. FDelayedDeletionTimer = NULL;
  174. FDelayedDeletionList = new TStringList();
  175. FDDFileList = NULL;
  176. FPendingTempSpaceWarn = false;
  177. FCapturedLog = NULL;
  178. FDragDropOperation = false;
  179. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  180. FAllowTransferPresetAutoSelect = true;
  181. FSessionChanging = false;
  182. FCopyParamDefault = L"";
  183. FSynchronizeController = NULL;
  184. FPendingQueueActionItem = NULL;
  185. FLockLevel = 0;
  186. FLockSuspendLevel = 0;
  187. FDisabledOnLockSuspend = false;
  188. FAlternativeDelete = false;
  189. FTrayIcon = new ::TTrayIcon(0);
  190. FTrayIcon->OnClick = TrayIconClick;
  191. FMaxQueueLength = 0;
  192. FLastContextPopupScreenPoint = TPoint(-1, -1);
  193. FTransferResumeList = NULL;
  194. FDeletedFiles = NULL;
  195. FMoveToQueue = false;
  196. StandaloneOperation = false;
  197. FOnFeedSynchronizeError = NULL;
  198. FOnSynchronizeAbort = NULL;
  199. FSynchronizeTerminal = NULL;
  200. FNeedSession = false;
  201. FDoNotIdleCurrentTerminal = 0;
  202. FIncrementalSearching = 0;
  203. FQueueFileList.reset(new TQueueFileList());
  204. FProgressSide = osCurrent;
  205. FCalculateSizeOperation = NULL;
  206. FDownloadingFromClipboard = false;
  207. FClipboardFakeMonitorsPendingReset = false;
  208. FHiContrastTheme = NULL;
  209. InitializeRemoteThumbnailMask();
  210. FEditorManager = new TEditorManager();
  211. FEditorManager->OnFileChange = ExecutedFileChanged;
  212. FEditorManager->OnFileReload = ExecutedFileReload;
  213. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  214. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  215. FLocalEditors = new TList();
  216. FQueueStatus = NULL;
  217. FQueueStatusSection = new TCriticalSection();
  218. FQueueStatusInvalidated = false;
  219. FQueueItemInvalidated = false;
  220. FQueueStatusUpdating = false;
  221. FQueueActedItem = NULL;
  222. FQueueController = new TQueueController(QueueView3);
  223. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  224. FUserActionTimer = new TTimer(this);
  225. FUserActionTimer->Enabled = false;
  226. FUserActionTimer->Interval = 10;
  227. FUserActionTimer->OnTimer = UserActionTimer;
  228. FNotes = new TStringList();
  229. FNoteTimer = new TTimer(this);
  230. FNoteTimer->Enabled = false;
  231. FNoteTimer->OnTimer = NoteTimer;
  232. FOnNoteClick = NULL;
  233. FOle32Library = LoadLibrary(L"Ole32.dll");
  234. FDragMoveCursor = FOle32Library != NULL ?
  235. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  236. UseSystemSettings(this);
  237. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  238. static_cast<TObject*>(GetComponent(fcTransferList)));
  239. DebugAssert(TransferList != NULL);
  240. FTransferListHoverIndex = -1;
  241. TransferList->OnChange = TransferListChange;
  242. TransferList->OnDrawItem = TransferListDrawItem;
  243. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  244. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  245. UseDesktopFont(SessionsPageControl);
  246. UseDesktopFont(RemoteDirView);
  247. UseDesktopFont(RemoteDriveView);
  248. UseDesktopFont(QueueView3);
  249. UseDesktopFont(QueueFileList);
  250. UseDesktopFont(QueueLabel);
  251. UseDesktopFont(RemoteStatusBar);
  252. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  253. QueueSplitter->ShowHint = true;
  254. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  255. QueueFileListSplitter->ShowHint = true;
  256. RemotePanelSplitter->ShowHint = true;
  257. UpdateImages();
  258. FCustomCommandMenu = CreateTBXPopupMenu(this);
  259. FCustomCommandLocalFileList = NULL;
  260. FCustomCommandRemoteFileList = NULL;
  261. FSessionColors = new TPngImageList(this);
  262. FSessionColors->ColorDepth = cd32Bit;
  263. AddFixedSessionImages();
  264. SessionsPageControl->Images = FSessionColors;
  265. // Needed for Explorer (Commander calls it implicitly on its own)
  266. UpdateSessionsPageControlHeight();
  267. UpdateQueueLabel();
  268. CheckStoreTransition();
  269. CreateHiddenWindow();
  270. StartUpdates();
  271. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  272. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  273. DriveInfo->NeedData();
  274. }
  275. //---------------------------------------------------------------------------
  276. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  277. {
  278. AppLog(L"Destroying main window");
  279. FInvalid = true;
  280. ReleaseHiContrastTheme();
  281. if (FClipboardTerminal != NULL)
  282. {
  283. ClipboardClear(); // implies ClipboardStop
  284. }
  285. // this has to be one of the very first things to do
  286. StopUpdateThread();
  287. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  288. TTerminalManager::Instance()->ScpExplorer = NULL;
  289. delete FCustomCommandLocalFileList;
  290. delete FCustomCommandRemoteFileList;
  291. delete FCustomCommandMenu;
  292. delete FTrayIcon;
  293. FTrayIcon = NULL;
  294. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  295. delete FEditorManager;
  296. ForceCloseLocalEditors();
  297. delete FLocalEditors;
  298. HideFileFindDialog();
  299. if (FDelayedDeletionTimer)
  300. {
  301. DoDelayedDeletion(NULL);
  302. SAFE_DESTROY(FDelayedDeletionTimer);
  303. }
  304. SAFE_DESTROY(FDelayedDeletionList);
  305. // sometimes we do not get DDEnd so the list is not released
  306. SAFE_DESTROY(FDDFileList);
  307. DebugAssert(FSynchronizeController == NULL);
  308. CloseHandle(FDDExtMutex);
  309. FDDExtMutex = NULL;
  310. FreeLibrary(FOle32Library);
  311. FOle32Library = NULL;
  312. FDragMoveCursor = NULL;
  313. DebugAssert(!FErrorList);
  314. if (FEverShown)
  315. {
  316. // when window is never shown (like when running command-line operation),
  317. // particularly window site is not restored correctly (BoundsRect value set
  318. // in RestoreForm gets lost during handle allocation), so we do not want
  319. // it to be stored
  320. AppLog(L"Storing main window configuration");
  321. StoreParams();
  322. }
  323. ManagedSession = NULL;
  324. Queue = NULL;
  325. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  326. NonVisualDataModule->ScpExplorer = NULL;
  327. delete FQueueScrollOnDragOver;
  328. FQueueScrollOnDragOver = NULL;
  329. delete FQueueController;
  330. FQueueController = NULL;
  331. delete FQueueStatusSection;
  332. FQueueStatusSection = NULL;
  333. delete FQueueStatus;
  334. FQueueStatus = NULL;
  335. delete FUserActionTimer;
  336. FUserActionTimer = NULL;
  337. delete FNoteTimer;
  338. delete FNotes;
  339. delete FNoteData;
  340. SAFE_DESTROY(FDocks);
  341. SessionsPageControl->Images = NULL;
  342. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  343. SAFE_DESTROY(FSessionColors);
  344. SAFE_DESTROY(FSessionsDragDropFilesEx);
  345. SAFE_DESTROY(FHistoryMenu[0][0]);
  346. SAFE_DESTROY(FHistoryMenu[0][1]);
  347. SAFE_DESTROY(FHistoryMenu[1][0]);
  348. SAFE_DESTROY(FHistoryMenu[1][1]);
  349. if (FHiddenWindow != NULL)
  350. {
  351. DestroyWindow(FHiddenWindow);
  352. FHiddenWindow = NULL;
  353. }
  354. AppLog(L"Main window destroyed");
  355. }
  356. //---------------------------------------------------------------------------
  357. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  358. {
  359. if (FHiContrastTheme != NULL)
  360. {
  361. ReleaseTBXTheme(FHiContrastTheme);
  362. FHiContrastTheme = NULL;
  363. }
  364. }
  365. //---------------------------------------------------------------------------
  366. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  367. {
  368. std::unique_ptr<TSessionData> Data;
  369. if (!Session.IsEmpty())
  370. {
  371. bool DefaultsOnly;
  372. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  373. }
  374. TTerminalManager * Manager = TTerminalManager::Instance();
  375. for (int Index = 0; Index < Manager->Count; Index++)
  376. {
  377. TTerminal * Terminal = Manager->Sessions[Index];
  378. if (Session.IsEmpty() ||
  379. Manager->IsActiveTerminalForSite(Terminal, Data.get()))
  380. {
  381. if (Path.IsEmpty())
  382. {
  383. Terminal->ClearCaches();
  384. }
  385. else
  386. {
  387. Terminal->DirectoryModified(Path, true);
  388. }
  389. }
  390. }
  391. // We should flag a pending refresh for the background terminals or busy foreground terminals
  392. if (HasActiveTerminal() &&
  393. CanCommandLineFromAnotherInstance() &&
  394. (Session.IsEmpty() || Manager->IsActiveTerminalForSite(Terminal, Data.get())) &&
  395. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  396. {
  397. Terminal->ReloadDirectory();
  398. }
  399. }
  400. //---------------------------------------------------------------------------
  401. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  402. {
  403. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  404. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  405. size_t MessageSize = sizeof(TCopyDataMessage);
  406. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  407. if (Result)
  408. {
  409. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  410. Result = (Message.Version == TCopyDataMessage::Version1);
  411. if (Result)
  412. {
  413. switch (Message.Command)
  414. {
  415. case TCopyDataMessage::CommandCanCommandLine:
  416. Result = CanCommandLineFromAnotherInstance();
  417. if (Result)
  418. {
  419. AppLog(L"Can process command-line from other instance");
  420. }
  421. else
  422. {
  423. AppLog(L"Cannot process command-line from other instance");
  424. }
  425. break;
  426. case TCopyDataMessage::CommandCommandLine:
  427. {
  428. UnicodeString CommandLine(Message.CommandLine);
  429. Result = CommandLineFromAnotherInstance(CommandLine);
  430. }
  431. break;
  432. case TCopyDataMessage::RefreshPanel:
  433. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  434. break;
  435. case TCopyDataMessage::MainWindowCheck:
  436. Result = true;
  437. break;
  438. default:
  439. Result = false;
  440. break;
  441. }
  442. }
  443. }
  444. Message.Result = Result ? 1 : 0;
  445. }
  446. //---------------------------------------------------------------------------
  447. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  448. {
  449. WNDCLASS WindowClass = {0};
  450. WindowClass.lpfnWndProc = DefWindowProc;
  451. WindowClass.hInstance = HInstance;
  452. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  453. FHiddenWindow = NULL;
  454. if (RegisterClass(&WindowClass))
  455. {
  456. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  457. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  458. }
  459. }
  460. //---------------------------------------------------------------------------
  461. bool __fastcall TCustomScpExplorerForm::CanConsole()
  462. {
  463. return
  464. HasActiveTerminal() &&
  465. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  466. }
  467. //---------------------------------------------------------------------------
  468. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  469. {
  470. bool Result = Visible && !NonVisualDataModule->Busy;
  471. return Result;
  472. }
  473. //---------------------------------------------------------------------------
  474. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  475. const UnicodeString & CommandLine)
  476. {
  477. TProgramParams Params(CommandLine);
  478. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  479. if (Result)
  480. {
  481. NonVisualDataModule->StartBusy();
  482. try
  483. {
  484. // this action is initiated from another process,
  485. // so it's likely that our window is not visible,
  486. // and user won't see what is going on
  487. Application->BringToFront();
  488. // reload sessions as we may be asked to open a session
  489. // just stored by another instance
  490. StoredSessions->Reload();
  491. UnicodeString SessionName = Params.Param[1];
  492. std::unique_ptr<TObjectList> DataList(new TObjectList());
  493. try
  494. {
  495. UnicodeString DownloadFile; // unused
  496. int Flags = GetCommandLineParseUrlFlags(&Params);
  497. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  498. }
  499. catch (EAbort &)
  500. {
  501. // Happens when opening session in PuTTY and in other situations,
  502. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  503. // to process the command-line on its own (or to pass it to yet another instance)
  504. }
  505. if (DataList->Count > 0)
  506. {
  507. TTerminalManager * Manager = TTerminalManager::Instance();
  508. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  509. }
  510. }
  511. __finally
  512. {
  513. NonVisualDataModule->EndBusy();
  514. }
  515. }
  516. return Result;
  517. }
  518. //---------------------------------------------------------------------------
  519. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  520. {
  521. TManagedTerminal * Result;
  522. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  523. {
  524. Result = FManagedSession;
  525. }
  526. else
  527. {
  528. Result = NULL;
  529. }
  530. return Result;
  531. }
  532. //---------------------------------------------------------------------------
  533. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  534. {
  535. if (FManagedSession != value)
  536. {
  537. TWindowLock Lock(this);
  538. SessionChanging();
  539. DoSetManagedSession(value, false);
  540. }
  541. }
  542. //---------------------------------------------------------------------------
  543. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  544. {
  545. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  546. FManagedSession = value;
  547. {
  548. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect, false);
  549. TAutoFlag SessionChangingFlag(FSessionChanging);
  550. SessionChanged(Replace);
  551. }
  552. if (Terminal != NULL)
  553. {
  554. TransferPresetAutoSelect();
  555. }
  556. // Update app and tab titles, prevented above by FSessionChanging.
  557. UpdateControls();
  558. }
  559. //---------------------------------------------------------------------------
  560. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  561. {
  562. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  563. DoSetManagedSession(value, true);
  564. }
  565. //---------------------------------------------------------------------------
  566. void __fastcall TCustomScpExplorerForm::SessionChanging()
  567. {
  568. if (ManagedSession != NULL)
  569. {
  570. UpdateSession(ManagedSession);
  571. }
  572. }
  573. //---------------------------------------------------------------------------
  574. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  575. {
  576. if (ManagedSession != NULL)
  577. {
  578. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  579. }
  580. if (!TTerminalManager::Instance()->Updating)
  581. {
  582. SessionListChanged();
  583. }
  584. if (Terminal != NULL)
  585. {
  586. TObject * State = NULL;
  587. if (WinConfiguration->PreservePanelState)
  588. {
  589. State = Terminal->RemoteExplorerState;
  590. DirView(osRemote)->AnnounceState(State);
  591. }
  592. try
  593. {
  594. if (Replaced)
  595. {
  596. RemoteDirView->ReplaceTerminal(Terminal);
  597. }
  598. else
  599. {
  600. RemoteDirView->Terminal = Terminal;
  601. }
  602. if (Terminal->Active)
  603. {
  604. Terminal->RefreshDirectory();
  605. }
  606. if (State != NULL)
  607. {
  608. DirView(osRemote)->RestoreState(State);
  609. }
  610. }
  611. __finally
  612. {
  613. DirView(osRemote)->AnnounceState(NULL);
  614. }
  615. }
  616. else
  617. {
  618. RemoteDirView->Terminal = NULL;
  619. }
  620. InitStatusBar();
  621. UpdateTransferList();
  622. // Update panels Enable state before refreshing the labels
  623. UpdateControls();
  624. }
  625. //---------------------------------------------------------------------------
  626. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  627. {
  628. if (Queue != value)
  629. {
  630. if (FQueue != NULL)
  631. {
  632. FQueue->OnListUpdate = NULL;
  633. FQueue->OnQueueItemUpdate = NULL;
  634. }
  635. FQueue = value;
  636. if (FQueue != NULL)
  637. {
  638. DebugAssert(FQueue->OnListUpdate == NULL);
  639. FQueue->OnListUpdate = QueueListUpdate;
  640. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  641. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  642. }
  643. QueueChanged();
  644. }
  645. }
  646. //---------------------------------------------------------------------------
  647. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  648. TListItem * Item)
  649. {
  650. if (FQueueActedItem == Item)
  651. {
  652. FQueueActedItem = NULL;
  653. if ((QueueView3->PopupMenu != NULL) &&
  654. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  655. {
  656. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  657. ReleaseCapture();
  658. }
  659. }
  660. if (Item->Data == FPendingQueueActionItem)
  661. {
  662. FPendingQueueActionItem = NULL;
  663. }
  664. }
  665. //---------------------------------------------------------------------------
  666. bool TCustomScpExplorerForm::IsAnythingQueued()
  667. {
  668. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  669. }
  670. //---------------------------------------------------------------------------
  671. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  672. {
  673. {
  674. TGuard Guard(FQueueStatusSection);
  675. FQueueStatusInvalidated = false;
  676. if (FQueue != NULL)
  677. {
  678. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  679. }
  680. }
  681. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  682. {
  683. FMaxQueueLength = FQueueStatus->Count;
  684. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  685. }
  686. {
  687. TAutoFlag Flag(FQueueStatusUpdating);
  688. FQueueController->UpdateQueueStatus(FQueueStatus);
  689. }
  690. UpdateQueueFileList();
  691. SetQueueProgress();
  692. UpdateQueueView();
  693. bool IsEmpty = !IsAnythingQueued();
  694. if (IsEmpty && (Terminal != NULL))
  695. {
  696. TOnceDoneOperation OnceDoneOperation =
  697. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  698. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  699. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  700. {
  701. FQueue->Enabled = false;
  702. }
  703. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  704. {
  705. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  706. }
  707. }
  708. }
  709. //---------------------------------------------------------------------------
  710. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  711. {
  712. UnicodeString Result;
  713. if (FQueueStatus != NULL)
  714. {
  715. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  716. {
  717. TFileOperationProgressType * ProgressData =
  718. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  719. if ((ProgressData != NULL) && ProgressData->InProgress)
  720. {
  721. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  722. }
  723. }
  724. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  725. {
  726. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  727. }
  728. }
  729. return Result;
  730. }
  731. //---------------------------------------------------------------------------
  732. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  733. {
  734. ComponentVisible[fcQueueView] =
  735. !IsLocalBrowserMode() &&
  736. ((WinConfiguration->QueueView.Show == qvShow) ||
  737. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  738. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  739. }
  740. //---------------------------------------------------------------------------
  741. void __fastcall TCustomScpExplorerForm::QueueChanged()
  742. {
  743. if (FQueueStatus != NULL)
  744. {
  745. // UpdateFileList implementation relies on the status being recreated when session changes
  746. delete FQueueStatus;
  747. FQueueStatus = NULL;
  748. }
  749. UpdateQueueStatus(true);
  750. }
  751. //---------------------------------------------------------------------------
  752. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  753. {
  754. if (FQueue == Queue)
  755. {
  756. FQueueStatusInvalidated = true;
  757. }
  758. }
  759. //---------------------------------------------------------------------------
  760. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  761. TQueueItem * Item)
  762. {
  763. if (FQueue == Queue)
  764. {
  765. TGuard Guard(FQueueStatusSection);
  766. // this may be running in parallel with QueueChanged
  767. if (FQueueStatus != NULL)
  768. {
  769. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  770. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  771. {
  772. FRefreshLocalDirectory = (QueueItem == NULL) ||
  773. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  774. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  775. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  776. }
  777. if (QueueItem != NULL)
  778. {
  779. QueueItem->UserData = (void*)true;
  780. FQueueItemInvalidated = true;
  781. }
  782. }
  783. }
  784. }
  785. //---------------------------------------------------------------------------
  786. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  787. {
  788. // during standalone editing, we have no way to see/control queue,
  789. // so we have to always popup prompts automatically
  790. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  791. }
  792. //---------------------------------------------------------------------------
  793. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  794. {
  795. if (FQueueStatus != NULL)
  796. {
  797. bool QueueAutoPopup = IsQueueAutoPopup();
  798. bool NeedRefresh = FQueueController->NeedRefresh();
  799. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  800. FQueueItemInvalidated = false;
  801. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  802. bool Updated = false;
  803. TQueueItemProxy * QueueItem;
  804. bool WasUserAction;
  805. for (int Index = 0; Index < Limit; Index++)
  806. {
  807. bool Update = false;
  808. QueueItem = FQueueStatus->Items[Index];
  809. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  810. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  811. (FPendingQueueActionItem == NULL))
  812. {
  813. FPendingQueueActionItem = QueueItem;
  814. FUserActionTimer->Enabled = true;
  815. }
  816. if ((bool)QueueItem->UserData)
  817. {
  818. QueueItem->UserData = (void*)false;
  819. QueueItem->Update();
  820. Updated = true;
  821. Update = true;
  822. }
  823. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  824. {
  825. Update = true;
  826. }
  827. if (Update)
  828. {
  829. FQueueController->RefreshQueueItem(QueueItem);
  830. }
  831. }
  832. if (Updated)
  833. {
  834. NonVisualDataModule->UpdateNonVisibleActions();
  835. SetQueueProgress();
  836. UpdateQueueFileList();
  837. }
  838. }
  839. }
  840. //---------------------------------------------------------------------------
  841. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  842. {
  843. if (FTaskbarList != NULL)
  844. {
  845. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  846. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  847. }
  848. }
  849. //---------------------------------------------------------------------------
  850. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  851. {
  852. if (Progress >= 0)
  853. {
  854. if (FTaskbarList != NULL)
  855. {
  856. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  857. }
  858. }
  859. else
  860. {
  861. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  862. }
  863. }
  864. //---------------------------------------------------------------------------
  865. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  866. {
  867. int OverallProgress;
  868. // FProgressForm is null when this is called from SetQueueProgress
  869. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  870. {
  871. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  872. }
  873. else if (!ProgressData->IsIndeterminate())
  874. {
  875. OverallProgress = ProgressData->OverallProgress();
  876. }
  877. else
  878. {
  879. OverallProgress = -1;
  880. }
  881. SetTaskbarListProgressValue(OverallProgress);
  882. }
  883. //---------------------------------------------------------------------------
  884. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  885. {
  886. TTerminalManager::Instance()->QueueStatusUpdated();
  887. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  888. {
  889. // Do not animate task bar button, when items are queued, but processing is disabled
  890. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  891. {
  892. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  893. {
  894. TFileOperationProgressType * ProgressData = NULL;
  895. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  896. {
  897. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  898. }
  899. if ((ProgressData != NULL) &&
  900. ProgressData->InProgress)
  901. {
  902. SetTaskbarListProgressValue(ProgressData);
  903. }
  904. else
  905. {
  906. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  907. }
  908. }
  909. else
  910. {
  911. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  912. }
  913. }
  914. else
  915. {
  916. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  917. }
  918. }
  919. UpdateQueueLabel();
  920. }
  921. //---------------------------------------------------------------------------
  922. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  923. {
  924. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  925. if (FQueueStatus != NULL)
  926. {
  927. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  928. if (ActiveAndPendingPrimaryCount > 0)
  929. {
  930. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  931. }
  932. }
  933. QueueLabel->Caption = Caption;
  934. }
  935. //---------------------------------------------------------------------------
  936. void TCustomScpExplorerForm::CheckStoreTransition()
  937. {
  938. if (WinConfiguration->StoreTransition == stInit)
  939. {
  940. if (IsUWP())
  941. {
  942. WinConfiguration->StoreTransition = stStoreFresh;
  943. AppLog(L"Fresh UWP/store installation");
  944. }
  945. else
  946. {
  947. WinConfiguration->StoreTransition = stStandard;
  948. AppLog(L"Fresh standard installation");
  949. }
  950. }
  951. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  952. {
  953. WinConfiguration->StoreTransition = stStoreMigrated;
  954. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  955. AppLog(L"Standard installation migrated to store installation");
  956. }
  957. if (WinConfiguration->StoreTransition == stStoreMigrated)
  958. {
  959. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  960. Toolbar->Parent = MessageDock;
  961. Toolbar->FullSize = true;
  962. Toolbar->Color = Application->HintColor;
  963. TTBXLabelItem * LabelItem;
  964. LabelItem = new TTBXLabelItem(Toolbar);
  965. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  966. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  967. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  968. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  969. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  970. Toolbar->Items->Add(LabelItem);
  971. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  972. LinkItem->FontSettings->Color = LinkColor;
  973. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  974. LinkItem->OnClick = StoreTransitionLinkClick;
  975. Toolbar->Items->Add(LinkItem);
  976. AddMenuSeparator(Toolbar->Items);
  977. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  978. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  979. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  980. CloseItem->OnClick = StoreTransitionCloseClick;
  981. Toolbar->Items->Add(CloseItem);
  982. GiveTBItemPriority(CloseItem);
  983. }
  984. }
  985. //---------------------------------------------------------------------------
  986. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  987. {
  988. ShowHelp(HELP_STORE_TRANSITION);
  989. }
  990. //---------------------------------------------------------------------------
  991. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  992. {
  993. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  994. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  995. delete Toolbar;
  996. WinConfiguration->StoreTransition = stStoreAcknowledged;
  997. UpdateControls();
  998. }
  999. //---------------------------------------------------------------------------
  1000. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  1001. {
  1002. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  1003. static_cast<TComponent*>(GetComponent(fcTransferList)));
  1004. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  1005. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  1006. TransferList->Strings->BeginUpdate();
  1007. try
  1008. {
  1009. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  1010. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  1011. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  1012. if (FTransferDropDownHint.IsEmpty())
  1013. {
  1014. FTransferDropDownHint = TransferDropDown->Hint;
  1015. }
  1016. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1017. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1018. TransferDropDown->Text = StripHotkey(Name);
  1019. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1020. (FTransferDropDownHint, StripHotkey(Name),
  1021. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1022. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1023. // update the label, otherwise when it is updated only on the first draw
  1024. // of the list, it is drawn "bold" for some reason
  1025. FTransferListHoverIndex = TransferList->ItemIndex;
  1026. UpdateTransferLabel();
  1027. }
  1028. __finally
  1029. {
  1030. TransferList->Strings->EndUpdate();
  1031. }
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1035. {
  1036. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1037. DebugAssert(Toolbar != NULL);
  1038. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1042. {
  1043. TForm::UpdateActions();
  1044. if (ComponentVisible[fcCustomCommandsBand])
  1045. {
  1046. UpdateCustomCommandsToolbar();
  1047. }
  1048. }
  1049. //---------------------------------------------------------------------------
  1050. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1051. {
  1052. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1053. }
  1054. //---------------------------------------------------------------------------
  1055. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1056. {
  1057. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1058. {
  1059. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1060. // Without this, the panel turns gray and unused part of header turns black
  1061. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1062. }
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1066. {
  1067. Color = GetBtnFaceColor();
  1068. DebugAssert(Configuration && RemoteDirView);
  1069. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1070. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1071. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1072. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1073. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1074. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1075. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1076. UpdateRowSelect(RemoteDirView);
  1077. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1078. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1079. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1080. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1081. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1082. UpdateSessionsPageControlHeight();
  1083. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1084. UpdateToolbarDisplayMode();
  1085. UpdateTransferList();
  1086. if (Terminal != NULL)
  1087. {
  1088. TransferPresetAutoSelect();
  1089. }
  1090. UpdateQueueView();
  1091. UpdateControls();
  1092. // this can be called even before constuctor finishes.
  1093. if (FEditorManager != NULL)
  1094. {
  1095. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1096. }
  1097. // this can be called even before constuctor finishes.
  1098. if (FLocalEditors != NULL)
  1099. {
  1100. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1101. {
  1102. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1103. }
  1104. }
  1105. if (ComponentVisible[fcCustomCommandsBand])
  1106. {
  1107. UpdateCustomCommandsToolbar();
  1108. }
  1109. // show only when keeping queue items forever,
  1110. // otherwise, it's enough to have it in the context menu
  1111. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1112. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1113. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1114. {
  1115. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1116. FFileColorsCurrent = WinConfiguration->FileColors;
  1117. FileColorsChanged();
  1118. }
  1119. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1120. (FSessionColors != NULL))
  1121. {
  1122. SessionListChanged();
  1123. }
  1124. if (GlyphsModule->LargerToolbar != WinConfiguration->LargerToolbar)
  1125. {
  1126. GlyphsModule->LargerToolbar = WinConfiguration->LargerToolbar;
  1127. if (FSessionColors != NULL)
  1128. {
  1129. RegenerateSessionColorsImageList();
  1130. UpdateSessionsPageControlHeight();
  1131. }
  1132. }
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1136. {
  1137. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1138. DirView->Invalidate();
  1139. }
  1140. //---------------------------------------------------------------------------
  1141. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1142. {
  1143. DoFileColorsChanged(RemoteDirView);
  1144. }
  1145. //---------------------------------------------------------------------------
  1146. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1147. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1148. void * /*Arg*/)
  1149. {
  1150. if (Token != NULL)
  1151. {
  1152. TForm * Editor = dynamic_cast<TForm*>(Token);
  1153. DebugAssert(Editor != NULL);
  1154. ReconfigureEditorForm(Editor);
  1155. }
  1156. }
  1157. //---------------------------------------------------------------------------
  1158. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1159. {
  1160. WinConfiguration->DDTransferConfirmation = asOn;
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1164. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1165. {
  1166. // noop
  1167. }
  1168. //---------------------------------------------------------------------------
  1169. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1170. {
  1171. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1175. {
  1176. if (DoNotShowAgain)
  1177. {
  1178. if (DragDrop)
  1179. {
  1180. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1181. {
  1182. PopupTrayBalloon(
  1183. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1184. }
  1185. WinConfiguration->DDTransferConfirmation = asOff;
  1186. }
  1187. else
  1188. {
  1189. WinConfiguration->ConfirmTransferring = false;
  1190. }
  1191. }
  1192. else
  1193. {
  1194. // User explicitly unchecked "do not show again",
  1195. // so show him the dialog the next time
  1196. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1197. {
  1198. WinConfiguration->DDTransferConfirmation = asOn;
  1199. }
  1200. }
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1204. TTransferDirection Direction, TTransferType Type, bool Temp,
  1205. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1206. bool Confirm, bool DragDrop, int Options)
  1207. {
  1208. bool Result = true;
  1209. DebugAssert(HasActiveTerminal());
  1210. // these parameters are known in advance
  1211. int Params =
  1212. FLAGMASK(Type == ttMove, cpDelete);
  1213. bool ToTemp = (Temp && (Direction == tdToLocal));
  1214. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1215. {
  1216. bool DisableNewerOnly =
  1217. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1218. ToTemp;
  1219. Options |=
  1220. FLAGMASK(ToTemp, coTemp) |
  1221. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1222. coDoNotShowAgain;
  1223. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1224. int CopyParamAttrs = (Direction == tdToRemote ?
  1225. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1226. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1227. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1228. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1229. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1230. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1231. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1232. if (Result)
  1233. {
  1234. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1235. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1236. }
  1237. }
  1238. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1239. {
  1240. Configuration->Usage->Inc(L"TransfersOnBackground");
  1241. // these parameter are known only after transfer dialog
  1242. Params |=
  1243. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1244. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1245. Result = false;
  1246. ClearTransferSourceSelection(Direction);
  1247. }
  1248. return Result;
  1249. }
  1250. //---------------------------------------------------------------------------
  1251. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1252. {
  1253. if (FOnFileOperationFinished != NULL)
  1254. {
  1255. FOnFileOperationFinished(Side, UnicodeString(), true);
  1256. }
  1257. else
  1258. {
  1259. if (HasDirView[Side])
  1260. {
  1261. DirView(Side)->SelectAll(smNone);
  1262. }
  1263. }
  1264. }
  1265. //---------------------------------------------------------------------------
  1266. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1267. {
  1268. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1269. ClearOperationSelection(Side);
  1270. }
  1271. //---------------------------------------------------------------------------
  1272. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1273. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1274. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1275. int Params)
  1276. {
  1277. DebugAssert(Queue != NULL);
  1278. bool SingleFile = false;
  1279. if (FileList->Count == 1)
  1280. {
  1281. if (Direction == tdToRemote)
  1282. {
  1283. UnicodeString FileName = FileList->Strings[0];
  1284. SingleFile = FileExists(ApiPath(FileName));
  1285. }
  1286. else
  1287. {
  1288. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1289. SingleFile = !File->IsDirectory;
  1290. }
  1291. }
  1292. TQueueItem * QueueItem;
  1293. if (Direction == tdToRemote)
  1294. {
  1295. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1296. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1297. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1298. }
  1299. else
  1300. {
  1301. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1302. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1303. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1304. }
  1305. AddQueueItem(Queue, QueueItem, Terminal);
  1306. }
  1307. //---------------------------------------------------------------------------
  1308. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1309. {
  1310. if (Queue->IsEmpty)
  1311. {
  1312. Terminal->QueueOperationStart = Now();
  1313. }
  1314. Queue->AddItem(QueueItem);
  1315. }
  1316. //---------------------------------------------------------------------------
  1317. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1318. {
  1319. }
  1320. //---------------------------------------------------------------------------
  1321. void __fastcall TCustomScpExplorerForm::InitControls()
  1322. {
  1323. DebugAssert(FDocks != NULL);
  1324. for (int Index = 0; Index < ComponentCount; Index++)
  1325. {
  1326. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1327. if ((Dock != NULL) && (Dock->Tag == 0))
  1328. {
  1329. FDocks->Add(Dock);
  1330. }
  1331. }
  1332. CollectItemsWithTextDisplayMode(this);
  1333. }
  1334. //---------------------------------------------------------------------------
  1335. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1336. {
  1337. ConfigurationChanged();
  1338. QueuePanel->Height =
  1339. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1340. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1341. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1342. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1343. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1344. QueueFileList->Height =
  1345. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1346. if (QueueFileList->Visible)
  1347. {
  1348. AdjustQueueLayout();
  1349. }
  1350. UpdateCustomCommandsToolbar();
  1351. }
  1352. //---------------------------------------------------------------------------
  1353. void __fastcall TCustomScpExplorerForm::StoreParams()
  1354. {
  1355. int APixelsPerInch = GetControlPixelsPerInch(this);
  1356. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1357. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1358. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1359. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1360. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1361. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1362. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1363. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1367. {
  1368. if (!FFormRestored)
  1369. {
  1370. FFormRestored = true;
  1371. RestoreFormParams();
  1372. }
  1373. TForm::CreateParams(Params);
  1374. }
  1375. //---------------------------------------------------------------------------
  1376. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1377. {
  1378. DebugAssert(FDocks != NULL);
  1379. for (int Index = 0; Index < FDocks->Count; Index++)
  1380. {
  1381. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1382. }
  1383. }
  1384. //---------------------------------------------------------------------------
  1385. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1386. {
  1387. SetDockAllowDrag(true);
  1388. while (!ButtonsStr.IsEmpty())
  1389. {
  1390. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1391. UnicodeString Name = CutToChar(S, L'=', true);
  1392. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1393. {
  1394. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1395. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1396. {
  1397. while (!S.IsEmpty())
  1398. {
  1399. UnicodeString S2 = CutToChar(S, L',', true);
  1400. UnicodeString Name = CutToChar(S2, L':', true);
  1401. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1402. {
  1403. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1404. if (SameText(GetToolbarItemName(Item), Name))
  1405. {
  1406. // forward compatibility
  1407. UnicodeString S3 = CutToChar(S2, L':', true);
  1408. bool Visible = StrToIntDef(S3, 0);
  1409. Item->Visible = Visible;
  1410. }
  1411. }
  1412. }
  1413. }
  1414. }
  1415. }
  1416. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1417. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1418. }
  1419. //---------------------------------------------------------------------------
  1420. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1421. {
  1422. UnicodeString Result;
  1423. SetDockAllowDrag(true);
  1424. Result = ::GetToolbarsLayoutStr(this);
  1425. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1426. return Result;
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1430. {
  1431. UnicodeString Result;
  1432. if (Item->Action != NULL)
  1433. {
  1434. Result = Item->Action->Name;
  1435. Result = RemoveSuffix(Result, L"Action", true);
  1436. }
  1437. else
  1438. {
  1439. Result = Item->Name;
  1440. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1441. Result = RemoveSuffix(Result, L"Item", true);
  1442. }
  1443. return Result;
  1444. }
  1445. //---------------------------------------------------------------------------
  1446. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1447. {
  1448. UnicodeString Result;
  1449. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1450. {
  1451. UnicodeString ToolbarStr;
  1452. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1453. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1454. {
  1455. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1456. {
  1457. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1458. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1459. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1460. // and save the changes here only.
  1461. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1462. {
  1463. UnicodeString Name = GetToolbarItemName(Item);
  1464. DebugAssert(Name.Pos(L"TBX") == 0);
  1465. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1466. }
  1467. }
  1468. }
  1469. if (!ToolbarStr.IsEmpty())
  1470. {
  1471. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1472. }
  1473. }
  1474. return Result;
  1475. }
  1476. //---------------------------------------------------------------------------
  1477. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1478. {
  1479. DebugAssert(FProgressForm == NULL);
  1480. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1481. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1482. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1483. FProgressForm->DeleteLocalToRecycleBin =
  1484. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1485. FProgressForm->DeleteRemoteToRecycleBin =
  1486. HasActiveTerminal() &&
  1487. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1488. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1489. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1490. LockWindow();
  1491. // Actually, do not know what hides the progress once the operation finishes
  1492. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1493. SetTaskbarListProgressState(TBPF_NORMAL);
  1494. }
  1495. //---------------------------------------------------------------------------
  1496. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1497. {
  1498. UnlockWindow();
  1499. SAFE_DESTROY(FProgressForm);
  1500. SetQueueProgress();
  1501. }
  1502. //---------------------------------------------------------------------------
  1503. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1504. TFileOperationProgressType & ProgressData)
  1505. {
  1506. // Download to temporary local directory
  1507. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1508. {
  1509. bool Continue = true;
  1510. FPendingTempSpaceWarn = false;
  1511. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1512. if (!Continue)
  1513. {
  1514. Abort();
  1515. }
  1516. }
  1517. // operation is being executed and we still didn't show up progress form
  1518. if (ProgressData.InProgress && !FProgressForm)
  1519. {
  1520. CreateProgressForm(NULL);
  1521. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1522. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1523. }
  1524. // operation is finished (or terminated), so we hide progress form
  1525. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1526. {
  1527. DestroyProgressForm();
  1528. if (ProgressData.Operation == foCalculateSize)
  1529. {
  1530. // When calculating size before transfer, the abort caused by
  1531. // cancel flag set due to "MoveToQueue" below,
  1532. // is not propagated back to us in ExecuteFileOperation,
  1533. // as it is silently swallowed.
  1534. // So we explicitly (re)throw it here.
  1535. if (FMoveToQueue)
  1536. {
  1537. Abort();
  1538. }
  1539. }
  1540. else
  1541. {
  1542. if ((ProgressData.Cancel == csContinue) &&
  1543. !FAutoOperation)
  1544. {
  1545. OperationComplete(ProgressData.StartTime);
  1546. }
  1547. }
  1548. }
  1549. if (FProgressForm &&
  1550. // Can happen only during synchronization, when ending one of the operations
  1551. ProgressData.InProgress)
  1552. {
  1553. FProgressForm->SetProgressData(ProgressData);
  1554. DebugAssert(ProgressData.InProgress);
  1555. SetTaskbarListProgressValue(&ProgressData);
  1556. if (FProgressForm->Cancel > csContinue)
  1557. {
  1558. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1559. if (FProgressForm->Cancel == csCancelFile)
  1560. {
  1561. FProgressForm->ClearCancel();
  1562. }
  1563. // cancel cancels even the move
  1564. FMoveToQueue = false;
  1565. }
  1566. else if (FProgressForm->MoveToQueue)
  1567. {
  1568. FMoveToQueue = true;
  1569. ProgressData.SetCancelAtLeast(csCancel);
  1570. }
  1571. if ((FTransferResumeList != NULL) &&
  1572. ProgressData.InProgress &&
  1573. ProgressData.IsTransfer() &&
  1574. !ProgressData.FullFileName.IsEmpty())
  1575. {
  1576. if ((FTransferResumeList->Count == 0) ||
  1577. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1578. {
  1579. // note that we do not recognize directories from files here
  1580. FTransferResumeList->Add(ProgressData.FullFileName);
  1581. }
  1582. }
  1583. }
  1584. }
  1585. //---------------------------------------------------------------------------
  1586. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1587. const TDateTime & StartTime)
  1588. {
  1589. if (GUIConfiguration->BeepOnFinish &&
  1590. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1591. {
  1592. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1593. DWORD Sound;
  1594. if (!ExtractFileExt(BeepSound).IsEmpty())
  1595. {
  1596. Sound = SND_FILENAME;
  1597. }
  1598. else
  1599. {
  1600. Sound = SND_ALIAS;
  1601. }
  1602. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1603. }
  1604. }
  1605. //---------------------------------------------------------------------------
  1606. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1607. TFileOperationProgressType & ProgressData)
  1608. {
  1609. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1610. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1611. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1612. FileOperationProgress(ProgressData);
  1613. }
  1614. //---------------------------------------------------------------------------
  1615. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1616. {
  1617. UnicodeString Result;
  1618. if (FProgressForm != NULL)
  1619. {
  1620. Result = FProgressForm->ProgressStr();
  1621. }
  1622. return Result;
  1623. }
  1624. //---------------------------------------------------------------------------
  1625. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1626. bool DragDrop)
  1627. {
  1628. return (!DragDrop && (DropSourceControl == NULL)) ||
  1629. (DropSourceControl == DirView(osOther));
  1630. }
  1631. //---------------------------------------------------------------------------
  1632. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1633. {
  1634. TCustomDirView * ADirView = DirView(Side);
  1635. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1636. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1637. // this can happen when local drive is unplugged in the middle of the operation
  1638. if (Item != NULL)
  1639. {
  1640. if (Unselect)
  1641. {
  1642. Item->Selected = false;
  1643. }
  1644. ADirView->MakeProgressVisible(Item);
  1645. }
  1646. return Item;
  1647. }
  1648. //---------------------------------------------------------------------------
  1649. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1650. TFileOperation Operation, TOperationSide Side,
  1651. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1652. TOnceDoneOperation & OnceDoneOperation)
  1653. {
  1654. if (!FAutoOperation)
  1655. {
  1656. // no selection on "/upload", form serves only as event handler
  1657. // (it is not displayed)
  1658. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1659. ((Operation == FPrimaryOperation) ||
  1660. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1661. {
  1662. TOperationSide DViewSide;
  1663. if ((FProgressSide != osCurrent) &&
  1664. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1665. {
  1666. // assume the operation is over the focused panel
  1667. DViewSide = FProgressSide;
  1668. }
  1669. else
  1670. {
  1671. DViewSide = Side;
  1672. }
  1673. if (FOnFileOperationFinished != NULL)
  1674. {
  1675. FOnFileOperationFinished(DViewSide, FileName, Success);
  1676. }
  1677. else
  1678. {
  1679. VisualiseOperationFinished(DViewSide, FileName, Success);
  1680. }
  1681. }
  1682. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1683. {
  1684. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1685. {
  1686. if (Side == osLocal)
  1687. {
  1688. Configuration->Usage->Inc(L"UploadedFiles");
  1689. }
  1690. else
  1691. {
  1692. Configuration->Usage->Inc(L"DownloadedFiles");
  1693. }
  1694. }
  1695. }
  1696. }
  1697. if (Success && (FSynchronizeController != NULL))
  1698. {
  1699. DebugAssert(!IsSideLocalBrowser(osRemote));
  1700. if (Operation == foCopy)
  1701. {
  1702. DebugAssert(Side == osLocal);
  1703. FSynchronizeController->LogOperation(soUpload, FileName);
  1704. }
  1705. else if (Operation == foDelete)
  1706. {
  1707. DebugAssert(Side == osRemote);
  1708. FSynchronizeController->LogOperation(soDelete, FileName);
  1709. }
  1710. }
  1711. if (FProgressForm)
  1712. {
  1713. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1714. }
  1715. }
  1716. //---------------------------------------------------------------------------
  1717. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1718. TFileOperation Operation, TOperationSide Side,
  1719. bool Temp, const UnicodeString & FileName, Boolean Success,
  1720. TOnceDoneOperation & OnceDoneOperation)
  1721. {
  1722. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1723. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1724. OnceDoneOperation);
  1725. }
  1726. //---------------------------------------------------------------------------
  1727. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1728. {
  1729. return false;
  1730. }
  1731. //---------------------------------------------------------------------------
  1732. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1733. {
  1734. return false;
  1735. }
  1736. //---------------------------------------------------------------------------
  1737. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1738. {
  1739. return false;
  1740. }
  1741. //---------------------------------------------------------------------------
  1742. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1743. {
  1744. return NULL;
  1745. }
  1746. //---------------------------------------------------------------------------
  1747. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1748. {
  1749. DebugAssert(GetSide(Side) == osRemote);
  1750. DebugUsedParam(Side);
  1751. return RemoteDirView;
  1752. }
  1753. //---------------------------------------------------------------------------
  1754. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1755. {
  1756. DebugAssert(GetSide(Side) == osRemote);
  1757. DebugUsedParam(Side);
  1758. return RemoteDriveView;
  1759. }
  1760. //---------------------------------------------------------------------------
  1761. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1762. {
  1763. DebugAssert(GetSide(Side) == osRemote);
  1764. DebugUsedParam(Side);
  1765. return HasActiveTerminal();
  1766. }
  1767. //---------------------------------------------------------------------------
  1768. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1769. TOperationSide Side, int FilesOnly)
  1770. {
  1771. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1772. }
  1773. //---------------------------------------------------------------------------
  1774. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1775. TOperationSide Side, int FilesOnly)
  1776. {
  1777. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. struct THistoryItemData
  1781. {
  1782. short int Side;
  1783. short int Index;
  1784. };
  1785. //---------------------------------------------------------------------------
  1786. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1787. {
  1788. DirView(Side)->HistoryGo(Index);
  1789. }
  1790. //---------------------------------------------------------------------------
  1791. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1792. {
  1793. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1794. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1795. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1796. }
  1797. //---------------------------------------------------------------------------
  1798. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1799. bool Back)
  1800. {
  1801. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1802. {
  1803. TCustomDirView * DView = DirView(Side);
  1804. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1805. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1806. if (ICount > 10)
  1807. {
  1808. ICount = 10;
  1809. }
  1810. Menu->Items->Clear();
  1811. THistoryItemData Data;
  1812. Data.Side = Side;
  1813. for (short int i = 1; i <= ICount; i++)
  1814. {
  1815. TTBCustomItem * Item = new TTBXItem(Menu);
  1816. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1817. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1818. Item->Hint = DView->HistoryPath[Data.Index];
  1819. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1820. Item->Tag = *reinterpret_cast<int*>(&Data);
  1821. Item->OnClick = HistoryItemClick;
  1822. Menu->Items->Add(Item);
  1823. }
  1824. }
  1825. }
  1826. //---------------------------------------------------------------------------
  1827. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1828. TOperationSide Side, bool Back)
  1829. {
  1830. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1831. {
  1832. // workaround
  1833. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1834. // operator new allocates memory in Pascal code, but calls inline
  1835. // constructor in C++, leading in problems, the function does
  1836. // both in Pascal code
  1837. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1838. UpdateHistoryMenu(Side, Back);
  1839. }
  1840. return FHistoryMenu[Side == osLocal][Back];
  1841. }
  1842. //---------------------------------------------------------------------------
  1843. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1844. TCustomDirView *Sender)
  1845. {
  1846. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1847. UpdateHistoryMenu(Side, true);
  1848. UpdateHistoryMenu(Side, false);
  1849. }
  1850. //---------------------------------------------------------------------------
  1851. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1852. {
  1853. // remote custom commands can be executed only if the server supports shell commands
  1854. // or have secondary shell
  1855. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1856. }
  1857. //---------------------------------------------------------------------------
  1858. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1859. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1860. {
  1861. // -1 = hidden, 0 = disabled, 1 = enabled
  1862. int Result;
  1863. TFileCustomCommand RemoteCustomCommand;
  1864. TLocalCustomCommand LocalCustomCommand;
  1865. TFileCustomCommand * NonInteractiveCustomCommand =
  1866. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1867. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1868. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1869. if (FLAGCLEAR(Command.Params, ccLocal))
  1870. {
  1871. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1872. // custom command that does not operate with files can be executed anytime ...
  1873. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1874. {
  1875. // ... but do not show such command in remote file menu
  1876. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1877. {
  1878. Result = AllowedState;
  1879. }
  1880. else
  1881. {
  1882. Result = -1;
  1883. }
  1884. }
  1885. else
  1886. {
  1887. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1888. {
  1889. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1890. }
  1891. else
  1892. {
  1893. Result = -1;
  1894. }
  1895. }
  1896. }
  1897. else
  1898. {
  1899. // custom command that does not operate with files can be executed anytime
  1900. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1901. {
  1902. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1903. }
  1904. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1905. {
  1906. if ((ListType == ccltAll) || (ListType == ccltFile))
  1907. {
  1908. // special case is "diff"-style command that can be executed over any side,
  1909. // if we have both sides
  1910. Result =
  1911. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1912. // directly (instead of EnableSelectedOperation) to pass
  1913. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1914. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1915. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1916. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1917. }
  1918. else if (ListType == ccltBoth)
  1919. {
  1920. DebugAssert(!IsLocalBrowserMode());
  1921. Result = 1;
  1922. }
  1923. else
  1924. {
  1925. Result = -1;
  1926. }
  1927. }
  1928. else
  1929. {
  1930. if ((ListType == ccltAll) ||
  1931. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1932. {
  1933. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1934. }
  1935. else
  1936. {
  1937. Result = -1;
  1938. }
  1939. }
  1940. if ((Result > 0) &&
  1941. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1942. !HasActiveTerminal())
  1943. {
  1944. Result = 0;
  1945. }
  1946. }
  1947. return Result;
  1948. }
  1949. //---------------------------------------------------------------------------
  1950. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1951. TStrings * FileList, const TCustomCommandType & ACommand,
  1952. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1953. {
  1954. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1955. {
  1956. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1957. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1958. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1959. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1960. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1961. bool Capture =
  1962. FLAGSET(ACommand.Params, ccShowResults) ||
  1963. FLAGSET(ACommand.Params, ccCopyResults) ||
  1964. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1965. TCaptureOutputEvent OutputEvent = NULL;
  1966. DebugAssert(FCapturedLog == NULL);
  1967. if (Capture)
  1968. {
  1969. FCapturedLog = new TStringList();
  1970. OutputEvent = TerminalCaptureLog;
  1971. }
  1972. try
  1973. {
  1974. if (!RemoteCustomCommand.IsFileCommand(Command))
  1975. {
  1976. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1977. OutputEvent);
  1978. }
  1979. else
  1980. {
  1981. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1982. }
  1983. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1984. {
  1985. if (FLAGSET(ACommand.Params, ccCopyResults))
  1986. {
  1987. CopyToClipboard(FCapturedLog);
  1988. }
  1989. if (FLAGSET(ACommand.Params, ccShowResults))
  1990. {
  1991. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1992. }
  1993. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1994. {
  1995. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1996. }
  1997. }
  1998. }
  1999. __finally
  2000. {
  2001. SAFE_DESTROY(FCapturedLog);
  2002. }
  2003. }
  2004. }
  2005. //---------------------------------------------------------------------------
  2006. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  2007. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  2008. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  2009. {
  2010. DebugAssert(!IsLocalBrowserMode());
  2011. TStrings * LocalFileList = NULL;
  2012. TStrings * RemoteFileList = NULL;
  2013. TStrings * RemoteFileListFull = NULL;
  2014. try
  2015. {
  2016. if (LocalFileCommand)
  2017. {
  2018. if (ALocalFileList == NULL)
  2019. {
  2020. DebugAssert(HasDirView[osLocal]);
  2021. // Cannot have focus on both panels, so we have to call AnyFileSelected
  2022. // directly (instead of EnableSelectedOperation) to pass
  2023. // false to FocusedFileOnlyWhenFocused
  2024. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  2025. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  2026. }
  2027. else
  2028. {
  2029. LocalFileList = ALocalFileList;
  2030. }
  2031. if (FileListCommand)
  2032. {
  2033. if (LocalFileList->Count != 1)
  2034. {
  2035. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2036. }
  2037. }
  2038. else
  2039. {
  2040. if ((LocalFileList->Count != 1) &&
  2041. (FileList->Count != 1) &&
  2042. (LocalFileList->Count != FileList->Count))
  2043. {
  2044. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2045. }
  2046. }
  2047. }
  2048. UnicodeString RootTempDir;
  2049. UnicodeString TempDir;
  2050. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2051. if (!RemoteFiles)
  2052. {
  2053. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true, true);
  2054. }
  2055. try
  2056. {
  2057. TDateTimes RemoteFileTimes;
  2058. if (RemoteFiles)
  2059. {
  2060. RemoteFileList = FileList;
  2061. }
  2062. else
  2063. {
  2064. RemoteFileList = new TStringList();
  2065. TMakeLocalFileListParams MakeFileListParam;
  2066. MakeFileListParam.FileList = RemoteFileList;
  2067. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2068. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2069. MakeFileListParam.Recursive =
  2070. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2071. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2072. if (!MakeFileListParam.Recursive)
  2073. {
  2074. RemoteFileTimes.clear();
  2075. RemoteFileListFull = new TStringList();
  2076. MakeFileListParam.FileList = RemoteFileListFull;
  2077. MakeFileListParam.Recursive = true;
  2078. MakeFileListParam.IncludeDirs = false;
  2079. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2080. }
  2081. else
  2082. {
  2083. RemoteFileListFull = RemoteFileList;
  2084. }
  2085. }
  2086. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2087. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2088. if (!NonBlocking)
  2089. {
  2090. int Count;
  2091. if (FileListCommand)
  2092. {
  2093. Count = 1;
  2094. }
  2095. else if (LocalFileCommand)
  2096. {
  2097. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2098. }
  2099. else
  2100. {
  2101. Count = RemoteFileList->Count;
  2102. }
  2103. Progress.Start(foCustomCommand, osRemote, Count);
  2104. DebugAssert(FProgressForm != NULL);
  2105. FProgressForm->ReadOnly = true;
  2106. }
  2107. try
  2108. {
  2109. if (FileListCommand)
  2110. {
  2111. UnicodeString LocalFile;
  2112. // MakeFileList does not delimit filenames
  2113. UnicodeString FileList = MakeFileList(RemoteFileList);
  2114. if (LocalFileCommand)
  2115. {
  2116. DebugAssert(LocalFileList->Count == 1);
  2117. LocalFile = LocalFileList->Strings[0];
  2118. }
  2119. TLocalCustomCommand CustomCommand(Data,
  2120. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2121. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2122. if (NonBlocking)
  2123. {
  2124. DebugAssert(!POutput);
  2125. ExecuteShellChecked(ShellCommand);
  2126. }
  2127. else
  2128. {
  2129. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2130. }
  2131. }
  2132. else if (LocalFileCommand)
  2133. {
  2134. if (LocalFileList->Count == 1)
  2135. {
  2136. UnicodeString LocalFile = LocalFileList->Strings[0];
  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(), FileName, LocalFile, L"");
  2144. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2145. TOnceDoneOperation OnceDoneOperation;
  2146. // Do not unselect anything, as it won't work with two panels anyway
  2147. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2148. }
  2149. }
  2150. else if (RemoteFileList->Count == 1)
  2151. {
  2152. UnicodeString FileName = RemoteFileList->Strings[0];
  2153. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2154. {
  2155. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2156. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2157. Progress.SetFile(LocalFileNameOnly);
  2158. TLocalCustomCommand CustomCommand(
  2159. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2160. FileName, LocalFileName, L"");
  2161. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2162. TOnceDoneOperation OnceDoneOperation;
  2163. // Do not unselect anything, as it won't work with two panels anyway
  2164. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2165. }
  2166. }
  2167. else
  2168. {
  2169. if (LocalFileList->Count != RemoteFileList->Count)
  2170. {
  2171. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2172. }
  2173. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2174. {
  2175. UnicodeString FileName = RemoteFileList->Strings[Index];
  2176. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2177. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2178. Progress.SetFile(LocalFileNameOnly); // sic
  2179. TLocalCustomCommand CustomCommand(
  2180. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2181. FileName, LocalFileName, L"");
  2182. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2183. TOnceDoneOperation OnceDoneOperation;
  2184. // Do not unselect anything, as it won't work with two panels anyway
  2185. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2186. }
  2187. }
  2188. }
  2189. else
  2190. {
  2191. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2192. {
  2193. UnicodeString FileName = RemoteFileList->Strings[Index];
  2194. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2195. Progress.SetFile(FileNameForProgress);
  2196. TLocalCustomCommand CustomCommand(Data,
  2197. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2198. FileName, L"", L"");
  2199. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2200. TOnceDoneOperation OnceDoneOperation;
  2201. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2202. }
  2203. }
  2204. }
  2205. __finally
  2206. {
  2207. if (!NonBlocking)
  2208. {
  2209. Progress.Stop();
  2210. }
  2211. }
  2212. DebugAssert(!FAutoOperation);
  2213. if (!RemoteFiles)
  2214. {
  2215. TempDir = IncludeTrailingBackslash(TempDir);
  2216. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2217. {
  2218. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2219. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2220. // Skip directories, process only nested files.
  2221. // The check is redundant as FileAge fails for directories anyway.
  2222. !DirectoryExists(FileName))
  2223. {
  2224. UnicodeString RemoteDir =
  2225. UnixExtractFileDir(
  2226. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2227. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2228. TDateTime NewTime;
  2229. if (FileAge(FileName, NewTime) &&
  2230. (NewTime != RemoteFileTimes[Index]))
  2231. {
  2232. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2233. TemporaryFileCopyParam(CopyParam);
  2234. CopyParam.FileMask = L"";
  2235. FAutoOperation = true;
  2236. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2237. TemporaryFilesList->Add(FileName);
  2238. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2239. }
  2240. }
  2241. }
  2242. }
  2243. }
  2244. __finally
  2245. {
  2246. FAutoOperation = false;
  2247. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2248. {
  2249. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2250. }
  2251. }
  2252. }
  2253. __finally
  2254. {
  2255. if (RemoteFileList != FileList)
  2256. {
  2257. delete RemoteFileList;
  2258. }
  2259. if (LocalFileList != ALocalFileList)
  2260. {
  2261. delete LocalFileList;
  2262. }
  2263. if (RemoteFileListFull != RemoteFileList)
  2264. {
  2265. delete RemoteFileListFull;
  2266. }
  2267. }
  2268. }
  2269. //---------------------------------------------------------------------------
  2270. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2271. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2272. bool FileListCommand, UnicodeString * POutput)
  2273. {
  2274. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2275. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2276. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2277. {
  2278. UnicodeString FileName = SelectedFileList->Strings[Index];
  2279. if (DirectoryExists(FileName))
  2280. {
  2281. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2282. {
  2283. LocalFileList->Add(FileName);
  2284. }
  2285. if (FLAGSET(ACommand.Params, ccRecursive))
  2286. {
  2287. TMakeLocalFileListParams MakeFileListParam;
  2288. MakeFileListParam.FileList = LocalFileList.get();
  2289. MakeFileListParam.FileTimes = NULL;
  2290. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2291. MakeFileListParam.Recursive = true;
  2292. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2293. }
  2294. }
  2295. else
  2296. {
  2297. LocalFileList->Add(FileName);
  2298. }
  2299. }
  2300. UnicodeString RemotePath;
  2301. if (Terminal != NULL)
  2302. {
  2303. RemotePath = Terminal->CurrentDirectory;
  2304. }
  2305. if (FileListCommand)
  2306. {
  2307. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2308. TLocalCustomCommand CustomCommand(
  2309. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2310. L"", L"", FileList);
  2311. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2312. }
  2313. else
  2314. {
  2315. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2316. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2317. DebugAssert(FProgressForm != NULL);
  2318. FProgressForm->ReadOnly = true;
  2319. try
  2320. {
  2321. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2322. {
  2323. UnicodeString FileName = LocalFileList->Strings[Index];
  2324. Progress.SetFile(FileName);
  2325. TLocalCustomCommand CustomCommand(
  2326. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2327. FileName, L"", L"");
  2328. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2329. TOnceDoneOperation OnceDoneOperation;
  2330. Progress.Finish(FileName, true, OnceDoneOperation);
  2331. }
  2332. }
  2333. __finally
  2334. {
  2335. Progress.Stop();
  2336. }
  2337. }
  2338. }
  2339. //---------------------------------------------------------------------------
  2340. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2341. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2342. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2343. {
  2344. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2345. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2346. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2347. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2348. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2349. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2350. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2351. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2352. std::unique_ptr<UnicodeString> POutput;
  2353. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2354. FLAGSET(ACommand.Params, ccCopyResults))
  2355. {
  2356. POutput.reset(new UnicodeString());
  2357. }
  2358. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  2359. if (!LocalCustomCommand.IsFileCommand(Command))
  2360. {
  2361. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2362. }
  2363. // remote files?
  2364. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2365. {
  2366. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2367. }
  2368. // local files
  2369. else
  2370. {
  2371. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2372. }
  2373. if (POutput.get() != NULL)
  2374. {
  2375. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2376. int P = POutput->Pos(sLineBreak);
  2377. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2378. {
  2379. POutput->SetLength(P - 1);
  2380. }
  2381. // Copy even empty output to clipboard
  2382. if (FLAGSET(ACommand.Params, ccCopyResults))
  2383. {
  2384. CopyToClipboard(*POutput);
  2385. }
  2386. // But do not show an empty message box.
  2387. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2388. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2389. !POutput->IsEmpty())
  2390. {
  2391. TClipboardHandler ClipboardHandler;
  2392. ClipboardHandler.Text = *POutput;
  2393. TMessageParams Params;
  2394. TQueryButtonAlias Aliases[1];
  2395. Aliases[0].Button = qaRetry;
  2396. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2397. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2398. Params.Aliases = Aliases;
  2399. Params.AliasesCount = LENOF(Aliases);
  2400. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2401. }
  2402. }
  2403. }
  2404. //---------------------------------------------------------------------------
  2405. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2406. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2407. {
  2408. TCustomCommandData Data;
  2409. UnicodeString Site;
  2410. UnicodeString RemotePath;
  2411. if (HasActiveTerminal())
  2412. {
  2413. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2414. Data = TCustomCommandData(SessionData.get());
  2415. Site = Terminal->SessionData->SessionKey;
  2416. RemotePath = Terminal->CurrentDirectory;
  2417. }
  2418. UnicodeString HelpKeyword = ACommand.HomePage;
  2419. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2420. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2421. {
  2422. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2423. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2424. {
  2425. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2426. }
  2427. else
  2428. {
  2429. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2430. }
  2431. if (!DoCustomCommandOptionsDialog(
  2432. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2433. {
  2434. Abort();
  2435. }
  2436. }
  2437. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2438. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2439. {
  2440. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2441. }
  2442. else
  2443. {
  2444. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2445. }
  2446. }
  2447. //---------------------------------------------------------------------------
  2448. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2449. const TCustomCommandType & Command)
  2450. {
  2451. DebugAssert(FCustomCommandLocalFileList != NULL);
  2452. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2453. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2454. TStrings * LocalFileList = new TStringList();
  2455. TStrings * RemoteFileList = new TStringList();
  2456. try
  2457. {
  2458. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2459. {
  2460. LocalFileList->Clear();
  2461. LocalFileList->AddObject(
  2462. FCustomCommandLocalFileList->Strings[Index],
  2463. FCustomCommandLocalFileList->Objects[Index]);
  2464. RemoteFileList->Clear();
  2465. RemoteFileList->AddObject(
  2466. FCustomCommandRemoteFileList->Strings[Index],
  2467. FCustomCommandRemoteFileList->Objects[Index]);
  2468. CustomCommand(RemoteFileList, Command, LocalFileList);
  2469. }
  2470. }
  2471. __finally
  2472. {
  2473. delete LocalFileList;
  2474. delete RemoteFileList;
  2475. }
  2476. }
  2477. //---------------------------------------------------------------------------
  2478. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2479. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2480. {
  2481. delete FCustomCommandLocalFileList;
  2482. delete FCustomCommandRemoteFileList;
  2483. // takeover ownership,
  2484. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2485. FCustomCommandLocalFileList = LocalFileList;
  2486. FCustomCommandRemoteFileList = RemoteFileList;
  2487. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2488. if (Button != NULL)
  2489. {
  2490. FCustomCommandMenu->Items->Clear();
  2491. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2492. MenuPopup(FCustomCommandMenu, Button);
  2493. }
  2494. else
  2495. {
  2496. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2497. }
  2498. }
  2499. //---------------------------------------------------------------------------
  2500. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2501. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2502. {
  2503. DebugAssert(FCapturedLog != NULL);
  2504. if ((OutputType == cotOutput) || (OutputType == cotError))
  2505. {
  2506. FCapturedLog->Add(AddedLine);
  2507. }
  2508. }
  2509. //---------------------------------------------------------------------------
  2510. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2511. TOperationSide Side)
  2512. {
  2513. return
  2514. (Side == osOther) &&
  2515. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2516. }
  2517. //---------------------------------------------------------------------------
  2518. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2519. TOperationSide Side, TTBXCustomItem * Item,
  2520. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2521. {
  2522. TCustomDirView * DView = DirView(Side);
  2523. bool IsDefault = false;
  2524. if (DView->ItemFocused != NULL)
  2525. {
  2526. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2527. TResolvedDoubleClickAction DefaultAction =
  2528. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2529. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2530. }
  2531. TTBItemOptions O = Item->Options;
  2532. if (IsDefault)
  2533. {
  2534. Item->Options = O << tboDefault;
  2535. }
  2536. else
  2537. {
  2538. Item->Options = O >> tboDefault;
  2539. }
  2540. }
  2541. //---------------------------------------------------------------------------
  2542. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2543. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2544. {
  2545. TCustomDirView * DView = DirView(Side);
  2546. TListItem * Item = DView->ItemFocused;
  2547. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2548. EnableFocusedOperation[Side])
  2549. {
  2550. TPoint ClientPoint;
  2551. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2552. TPoint(0, 0) : MousePos;
  2553. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2554. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2555. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2556. }
  2557. }
  2558. //---------------------------------------------------------------------------
  2559. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2560. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2561. {
  2562. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2563. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2564. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2565. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2566. Handled = true;
  2567. }
  2568. //---------------------------------------------------------------------------
  2569. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2570. {
  2571. }
  2572. //---------------------------------------------------------------------------
  2573. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2574. {
  2575. DebugAssert(FErrorList == NULL);
  2576. if (WinConfiguration->ContinueOnError)
  2577. {
  2578. FErrorList = new TStringList();
  2579. Configuration->Usage->Inc(L"ContinuationsOnError");
  2580. }
  2581. NonVisualDataModule->StartBusy();
  2582. }
  2583. //---------------------------------------------------------------------------
  2584. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2585. {
  2586. NonVisualDataModule->EndBusy();
  2587. if (FErrorList)
  2588. {
  2589. HandleErrorList(FErrorList);
  2590. }
  2591. }
  2592. //---------------------------------------------------------------------------
  2593. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2594. const TCopyParamType & CopyParam)
  2595. {
  2596. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2597. {
  2598. Configuration->Usage->Inc(L"FileMaskUses");
  2599. }
  2600. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2601. {
  2602. Configuration->Usage->Inc(L"OperationMaskUses");
  2603. }
  2604. }
  2605. //---------------------------------------------------------------------------
  2606. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2607. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2608. {
  2609. DebugAssert(!IsLocalBrowserMode());
  2610. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2611. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2612. TTransferOperationParam DefaultParam;
  2613. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2614. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2615. switch (Param.Queue)
  2616. {
  2617. case asOn:
  2618. CopyParam.Queue = true;
  2619. break;
  2620. case asOff:
  2621. CopyParam.Queue = false;
  2622. break;
  2623. case asAuto:
  2624. default:
  2625. // keep default
  2626. break;
  2627. }
  2628. bool Result =
  2629. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2630. if (Result)
  2631. {
  2632. DebugAssert(Terminal);
  2633. bool SelectionRestored = false;
  2634. TCustomDirView * DView = NULL;
  2635. if (HasDirView[Side])
  2636. {
  2637. DView = DirView(Side);
  2638. DView->SaveSelection();
  2639. DView->SaveSelectedNames();
  2640. }
  2641. UpdateCopyParamCounters(CopyParam);
  2642. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2643. DebugAssert(FTransferResumeList == NULL);
  2644. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2645. FMoveToQueue = false;
  2646. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2647. try
  2648. {
  2649. TStrings * PermanentFileList;
  2650. std::unique_ptr<TStrings> PermanentFileListOwner;
  2651. try
  2652. {
  2653. if (Side == osLocal)
  2654. {
  2655. PermanentFileList = FileList;
  2656. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2657. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2658. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2659. if (Operation == foMove)
  2660. {
  2661. ReloadLocalDirectory();
  2662. if (DView != NULL)
  2663. {
  2664. DView->RestoreSelection();
  2665. }
  2666. SelectionRestored = true;
  2667. }
  2668. }
  2669. else
  2670. {
  2671. // Clone the file list as it may refer to current directory files,
  2672. // which get destroyed, when the source directory is reloaded after foMove operation.
  2673. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2674. // But for a hotfix, we are not going to do such a big change.
  2675. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2676. PermanentFileList = PermanentFileListOwner.get();
  2677. try
  2678. {
  2679. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2680. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2681. }
  2682. __finally
  2683. {
  2684. if (Operation == foMove)
  2685. {
  2686. if (DView != NULL)
  2687. {
  2688. DView->RestoreSelection();
  2689. }
  2690. SelectionRestored = true;
  2691. }
  2692. ReloadLocalDirectory(Param.TargetDirectory);
  2693. }
  2694. }
  2695. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2696. if (FMoveToQueue)
  2697. {
  2698. Abort();
  2699. }
  2700. }
  2701. catch (EAbort &)
  2702. {
  2703. if (FMoveToQueue)
  2704. {
  2705. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2706. DebugAssert(CopyParam.TransferSkipList == NULL);
  2707. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2708. if (TransferResumeList->Count > 0)
  2709. {
  2710. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2711. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2712. }
  2713. CopyParam.TransferSkipList = TransferResumeList.release();
  2714. // not really needed, just to keep it consistent with TransferResumeList
  2715. FTransferResumeList = NULL;
  2716. FMoveToQueue = false;
  2717. Configuration->Usage->Inc("MovesToBackground");
  2718. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2719. ClearTransferSourceSelection(Direction);
  2720. }
  2721. throw;
  2722. }
  2723. }
  2724. __finally
  2725. {
  2726. if (!SelectionRestored && (DView != NULL))
  2727. {
  2728. DView->DiscardSavedSelection();
  2729. }
  2730. FTransferResumeList = NULL;
  2731. }
  2732. }
  2733. return Result;
  2734. }
  2735. //---------------------------------------------------------------------------
  2736. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2737. TOperationSide Side, TStrings * FileList, void * Param)
  2738. {
  2739. DebugAssert(FileList->Count);
  2740. // We deliberately do not toggle alternative flag (Param), but use OR,
  2741. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2742. // shortcut of CurrentDeleteAlternativeAction
  2743. bool Alternative =
  2744. bool(Param) || UseAlternativeFunction();
  2745. bool Recycle;
  2746. if (IsSideLocalBrowser(Side))
  2747. {
  2748. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2749. }
  2750. else
  2751. {
  2752. Recycle =
  2753. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2754. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2755. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2756. }
  2757. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2758. if (!Result)
  2759. {
  2760. UnicodeString Query;
  2761. if (FileList->Count == 1)
  2762. {
  2763. if (IsSideLocalBrowser(Side))
  2764. {
  2765. Query = ExtractFileName(FileList->Strings[0]);
  2766. }
  2767. else
  2768. {
  2769. Query = UnixExtractFileName(FileList->Strings[0]);
  2770. }
  2771. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2772. }
  2773. else
  2774. {
  2775. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2776. }
  2777. TMessageParams Params(mpNeverAskAgainCheck);
  2778. Params.ImageName = L"Delete file";
  2779. unsigned int Answer =
  2780. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2781. if (Answer == qaNeverAskAgain)
  2782. {
  2783. Result = true;
  2784. if (Recycle)
  2785. {
  2786. WinConfiguration->ConfirmRecycling = false;
  2787. }
  2788. else
  2789. {
  2790. WinConfiguration->ConfirmDeleting = false;
  2791. }
  2792. }
  2793. else
  2794. {
  2795. Result = (Answer == qaOK);
  2796. }
  2797. }
  2798. if (Result)
  2799. {
  2800. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2801. }
  2802. return Result;
  2803. }
  2804. //---------------------------------------------------------------------------
  2805. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2806. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2807. {
  2808. TAutoBatch AutoBatch(this);
  2809. bool Result;
  2810. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2811. {
  2812. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2813. }
  2814. else if (Operation == foRename)
  2815. {
  2816. DebugAssert(DirView(Side)->ItemFocused);
  2817. DirView(Side)->ItemFocused->EditCaption();
  2818. Result = true;
  2819. }
  2820. else if (Operation == foDelete)
  2821. {
  2822. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2823. }
  2824. else if (Operation == foSetProperties)
  2825. {
  2826. DirView(osRemote)->SaveSelectedNames();
  2827. Result = SetProperties(Side, FileList);
  2828. }
  2829. else if (Operation == foCustomCommand)
  2830. {
  2831. DebugAssert(Param);
  2832. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2833. DirView(osRemote)->SaveSelectedNames();
  2834. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2835. CustomCommand(FileList, *Command, NULL);
  2836. Result = true;
  2837. }
  2838. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2839. {
  2840. DebugAssert(!IsSideLocalBrowser(Side));
  2841. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2842. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2843. }
  2844. else if (Operation == foLock)
  2845. {
  2846. DebugAssert(!IsSideLocalBrowser(Side));
  2847. LockFiles(FileList, true);
  2848. Result = true;
  2849. }
  2850. else if (Operation == foUnlock)
  2851. {
  2852. DebugAssert(!IsSideLocalBrowser(Side));
  2853. LockFiles(FileList, false);
  2854. Result = true;
  2855. }
  2856. else
  2857. {
  2858. DebugFail();
  2859. }
  2860. return Result;
  2861. }
  2862. //---------------------------------------------------------------------------
  2863. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2864. {
  2865. if (Side == osCurrent)
  2866. {
  2867. Side = FCurrentSide;
  2868. }
  2869. return Side;
  2870. }
  2871. //---------------------------------------------------------------------------
  2872. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2873. {
  2874. TOperationSide Result;
  2875. switch (GetSide(Side))
  2876. {
  2877. case osLocal:
  2878. Result = osOther;
  2879. break;
  2880. case osOther:
  2881. Result = osLocal;
  2882. break;
  2883. default:
  2884. DebugFail();
  2885. Abort();
  2886. }
  2887. return Result;
  2888. }
  2889. //---------------------------------------------------------------------------
  2890. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2891. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2892. {
  2893. Side = GetSide(Side);
  2894. bool FullPath = IsSideLocalBrowser(Side);
  2895. TCustomDirView * ADirView = DirView(Side);
  2896. std::unique_ptr<TStringList> FileList(new TStringList());
  2897. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2898. bool ReloadProperties =
  2899. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2900. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2901. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2902. if (Result && ReloadProperties)
  2903. {
  2904. std::unique_ptr<TStringList> FileList2(new TStringList());
  2905. FileList->CaseSensitive = true;
  2906. FileList->Sort();
  2907. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2908. {
  2909. TListItem * Item = ADirView->Items->Item[Index];
  2910. UnicodeString FileName = ADirView->ItemFileName(Item);
  2911. int Index2;
  2912. if (FileList->Find(FileName, Index2))
  2913. {
  2914. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2915. }
  2916. }
  2917. LoadFilesProperties(FileList2.get());
  2918. }
  2919. return Result;
  2920. }
  2921. //---------------------------------------------------------------------------
  2922. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2923. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2924. bool NoConfirmation, void * Param)
  2925. {
  2926. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2927. {
  2928. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2929. {
  2930. DebugAssert(!IsLocalBrowserMode());
  2931. if (GetSide(Side) == osLocal)
  2932. {
  2933. Configuration->Usage->Inc(L"UploadsCommand");
  2934. }
  2935. else
  2936. {
  2937. Configuration->Usage->Inc(L"DownloadsCommand");
  2938. }
  2939. }
  2940. }
  2941. }
  2942. //---------------------------------------------------------------------------
  2943. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2944. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2945. {
  2946. TTransferOperationParam Param;
  2947. if ((WinConfiguration->Interface != ifCommander) ||
  2948. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2949. {
  2950. Flags &= ~cocShortCutHint;
  2951. }
  2952. TCustomDirView * DView = DirView(Side);
  2953. Param.Options =
  2954. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2955. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2956. if (FLAGSET(Flags, cocQueue))
  2957. {
  2958. Param.Queue = asOn;
  2959. }
  2960. else if (FLAGSET(Flags, cocNonQueue))
  2961. {
  2962. Param.Queue = asOff;
  2963. }
  2964. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2965. }
  2966. //---------------------------------------------------------------------------
  2967. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2968. {
  2969. int Count = ErrorList->Count;
  2970. try
  2971. {
  2972. if (ErrorList->Count)
  2973. {
  2974. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2975. if (MessageDialog(Message, qtError,
  2976. qaOK | qaCancel, HELP_NONE) == qaOK)
  2977. {
  2978. unsigned int Answer;
  2979. int Index = 0;
  2980. do
  2981. {
  2982. DebugAssert(Index >= 0 && Index < Count);
  2983. TQueryButtonAlias Aliases[2];
  2984. Aliases[0].Button = qaYes;
  2985. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2986. Aliases[1].Button = qaNo;
  2987. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2988. TMessageParams Params;
  2989. Params.Aliases = Aliases;
  2990. Params.AliasesCount = LENOF(Aliases);
  2991. int No = Index + 1;
  2992. UnicodeString Message = ErrorList->Strings[Index];
  2993. UnicodeString AMainInstructions;
  2994. UnicodeString Details;
  2995. if (ExtractMainInstructions(Message, AMainInstructions))
  2996. {
  2997. Details = Message;
  2998. Message = AMainInstructions;
  2999. }
  3000. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  3001. Answer = MoreMessageDialog(
  3002. Message,
  3003. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  3004. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  3005. qaOK, HELP_NONE, &Params);
  3006. if (Answer == qaNo)
  3007. {
  3008. Index++;
  3009. }
  3010. if (Answer == qaYes)
  3011. {
  3012. Index--;
  3013. }
  3014. }
  3015. while (Answer != qaOK);
  3016. }
  3017. }
  3018. }
  3019. __finally
  3020. {
  3021. TStrings * List = ErrorList;
  3022. ErrorList = NULL;
  3023. for (int i = 0; i < Count; i++)
  3024. {
  3025. delete List->Objects[i];
  3026. }
  3027. delete List;
  3028. }
  3029. }
  3030. //---------------------------------------------------------------------------
  3031. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3032. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3033. {
  3034. // needed for checking filemasks, as there's no directory object
  3035. // associated with the file object
  3036. File->FullFileName = FullFileName;
  3037. TFileMasks::TParams MaskParams;
  3038. MaskParams.Size = File->Size;
  3039. MaskParams.Modification = File->Modification;
  3040. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3041. }
  3042. //---------------------------------------------------------------------------
  3043. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3044. {
  3045. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3046. Side = GetSide(Side);
  3047. TCustomDirView * DView = DirView(Side);
  3048. TListItem * FocusedItem = DView->ItemFocused;
  3049. UnicodeString Name;
  3050. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3051. {
  3052. Name = DView->ItemFileName(FocusedItem);
  3053. }
  3054. else
  3055. {
  3056. Name = LoadStr(NEW_FILE);
  3057. }
  3058. UnicodeString Names = Name;
  3059. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3060. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3061. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  3062. {
  3063. while (!Names.IsEmpty())
  3064. {
  3065. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3066. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3067. UnicodeString TargetFileName;
  3068. UnicodeString LocalFileName;
  3069. UnicodeString RootTempDir;
  3070. UnicodeString TempDir;
  3071. UnicodeString RemoteDirectory;
  3072. bool ExistingFile = false;
  3073. if (!IsSideLocalBrowser(Side))
  3074. {
  3075. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3076. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3077. if ((File.get() != NULL) &&
  3078. !File->IsDirectory)
  3079. {
  3080. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3081. ExistingFile = true;
  3082. }
  3083. File.reset(NULL);
  3084. if (!ExistingFile)
  3085. {
  3086. RemoteDirectory = UnixExtractFilePath(Name);
  3087. TemporaryDirectoryForRemoteFiles(
  3088. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3089. TargetFileName = UnixExtractFileName(Name);
  3090. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3091. LocalFileName = TempDir +
  3092. // We probably do not want to trim the VMS version here
  3093. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3094. }
  3095. }
  3096. else
  3097. {
  3098. if (ExtractFilePath(Name).IsEmpty())
  3099. {
  3100. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3101. }
  3102. else
  3103. {
  3104. LocalFileName = ExpandFileName(Name);
  3105. }
  3106. TargetFileName = ExtractFileName(Name);
  3107. }
  3108. if (!ExistingFile)
  3109. {
  3110. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3111. if (NewFile)
  3112. {
  3113. int File = FileCreate(ApiPath(LocalFileName));
  3114. if (File < 0)
  3115. {
  3116. if (!RootTempDir.IsEmpty())
  3117. {
  3118. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3119. }
  3120. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3121. }
  3122. else
  3123. {
  3124. FileClose(File);
  3125. }
  3126. }
  3127. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3128. const TEditorData * ExternalEditor = NULL;
  3129. TFileMasks::TParams MaskParams; // size not known
  3130. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3131. false, MaskParams);
  3132. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3133. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3134. }
  3135. }
  3136. }
  3137. }
  3138. //---------------------------------------------------------------------------
  3139. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3140. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3141. {
  3142. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3143. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3144. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3145. return
  3146. ((ExecuteFileBy == efInternalEditor)) ||
  3147. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3148. }
  3149. //---------------------------------------------------------------------------
  3150. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3151. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3152. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3153. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3154. {
  3155. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3156. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3157. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3158. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3159. Side = GetSide(Side);
  3160. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3161. if (!IsSideLocalBrowser(Side))
  3162. {
  3163. Data->Terminal = Terminal;
  3164. Data->SessionData = CloneCurrentSessionData();
  3165. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3166. Data->RemoteDirectory = RemoteDirectory;
  3167. Data->SessionName = Terminal->SessionData->SessionName;
  3168. Data->LocalRootDirectory = LocalRootDirectory;
  3169. Data->OriginalFileName = OriginalFileName;
  3170. Data->Command = L""; // will be changed later for external editor
  3171. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3172. if (WinConfiguration->EditorCheckNotModified)
  3173. {
  3174. Data->SourceTimestamp = SourceTimestamp;
  3175. }
  3176. }
  3177. if (ExecuteFileBy == efInternalEditor)
  3178. {
  3179. if (!IsSideLocalBrowser(Side))
  3180. {
  3181. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3182. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3183. TForm * Editor;
  3184. try
  3185. {
  3186. Editor =
  3187. ShowEditorForm(
  3188. FileName, this,
  3189. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3190. SaveAllInternalEditors, AnyInternalEditorModified,
  3191. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3192. }
  3193. catch(...)
  3194. {
  3195. if (!LocalRootDirectory.IsEmpty())
  3196. {
  3197. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3198. }
  3199. throw;
  3200. }
  3201. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3202. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3203. }
  3204. else
  3205. {
  3206. DebugAssert(!StandaloneOperation);
  3207. TForm * Editor =
  3208. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3209. SaveAllInternalEditors, AnyInternalEditorModified,
  3210. L"", false, SessionColor, -1, NewFile);
  3211. FLocalEditors->Add(Editor);
  3212. }
  3213. }
  3214. else
  3215. {
  3216. HANDLE Process;
  3217. if (ExecuteFileBy == efExternalEditor)
  3218. {
  3219. UnicodeString Program, Params, Dir;
  3220. Data->Command = ExternalEditor->ExternalEditor;
  3221. ReformatFileNameCommand(Data->Command);
  3222. SplitCommand(Data->Command, Program, Params, Dir);
  3223. Params = ExpandFileNameCommand(Params, FileName);
  3224. Program = ExpandEnvironmentVariables(Program);
  3225. if (!ExecuteShell(Program, Params, Process))
  3226. {
  3227. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3228. }
  3229. }
  3230. else
  3231. {
  3232. DebugAssert(!IsSideLocalBrowser(Side));
  3233. if (!ExecuteShell(FileName, L"", Process))
  3234. {
  3235. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3236. }
  3237. }
  3238. if (IsSideLocalBrowser(Side) ||
  3239. ((ExecuteFileBy == efShell) &&
  3240. !WinConfiguration->Editor.SDIShellEditor) ||
  3241. ((ExecuteFileBy == efExternalEditor) &&
  3242. !ExternalEditor->SDIExternalEditor))
  3243. {
  3244. // no need for handle
  3245. if (Process != NULL)
  3246. {
  3247. DebugCheck(CloseHandle(Process));
  3248. }
  3249. Process = INVALID_HANDLE_VALUE;
  3250. }
  3251. else
  3252. {
  3253. if (Process == NULL)
  3254. {
  3255. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3256. }
  3257. }
  3258. if (!IsSideLocalBrowser(Side))
  3259. {
  3260. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3261. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3262. }
  3263. }
  3264. }
  3265. //---------------------------------------------------------------------------
  3266. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3267. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3268. void * /*Arg*/)
  3269. {
  3270. if (Token != NULL)
  3271. {
  3272. EditorFormFileSave(static_cast<TForm *>(Token));
  3273. }
  3274. }
  3275. //---------------------------------------------------------------------------
  3276. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3277. {
  3278. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3279. {
  3280. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3281. }
  3282. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3283. }
  3284. //---------------------------------------------------------------------------
  3285. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3286. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3287. void * Arg)
  3288. {
  3289. if ((Token != NULL) &&
  3290. IsEditorFormModified(static_cast<TForm *>(Token)))
  3291. {
  3292. *static_cast<bool *>(Arg) = true;
  3293. }
  3294. }
  3295. //---------------------------------------------------------------------------
  3296. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3297. TObject * /*Sender*/, bool & Modified)
  3298. {
  3299. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3300. {
  3301. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3302. {
  3303. Modified = true;
  3304. }
  3305. }
  3306. if (!Modified)
  3307. {
  3308. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3309. }
  3310. }
  3311. //---------------------------------------------------------------------------
  3312. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3313. {
  3314. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3315. }
  3316. //---------------------------------------------------------------------------
  3317. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3318. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3319. UnicodeString & Result, UnicodeString & RootDirectory)
  3320. {
  3321. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3322. {
  3323. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3324. Result = RootDirectory;
  3325. }
  3326. else
  3327. {
  3328. RootDirectory = L"";
  3329. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3330. Result = IncludeTrailingBackslash(Result);
  3331. }
  3332. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3333. {
  3334. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3335. }
  3336. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3337. {
  3338. UnicodeString ARemoteDirectory = RemoteDirectory;
  3339. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3340. {
  3341. ARemoteDirectory.Delete(1, 1);
  3342. }
  3343. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3344. }
  3345. if (!ForceDirectories(ApiPath(Result)))
  3346. {
  3347. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3348. }
  3349. }
  3350. //---------------------------------------------------------------------------
  3351. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3352. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3353. bool GetTargetNames, bool AutoOperation, bool SimpleTempDir)
  3354. {
  3355. DebugAssert(!IsLocalBrowserMode());
  3356. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3357. if (ForceText)
  3358. {
  3359. CopyParam.TransferMode = tmAscii;
  3360. }
  3361. TemporaryFileCopyParam(CopyParam);
  3362. if (TempDir.IsEmpty())
  3363. {
  3364. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3365. }
  3366. DebugAssert(!FAutoOperation);
  3367. FAutoOperation = AutoOperation;
  3368. Terminal->ExceptionOnFail = true;
  3369. try
  3370. {
  3371. try
  3372. {
  3373. // turn off confirmations, as for MDI editors we may possibly download
  3374. // the same file over
  3375. Terminal->CopyToLocal(
  3376. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3377. if (GetTargetNames)
  3378. {
  3379. for (int i = 0; i < FileList->Count; i++)
  3380. {
  3381. FileList->Strings[i] =
  3382. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3383. }
  3384. }
  3385. }
  3386. catch(...)
  3387. {
  3388. if (!RootTempDir.IsEmpty())
  3389. {
  3390. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3391. }
  3392. throw;
  3393. }
  3394. }
  3395. __finally
  3396. {
  3397. FAutoOperation = false;
  3398. Terminal->ExceptionOnFail = false;
  3399. }
  3400. }
  3401. //---------------------------------------------------------------------------
  3402. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3403. {
  3404. // Do not waste time checking for default editor list the next time,
  3405. // or testing if default editor is not notepad.
  3406. bool TryNextTime = false;
  3407. UnicodeString UsageState;
  3408. if (!WinConfiguration->EditorList->IsDefaultList())
  3409. {
  3410. UsageState = "H";
  3411. }
  3412. else
  3413. {
  3414. UnicodeString Executable;
  3415. UnicodeString ExecutableDescription;
  3416. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3417. {
  3418. UnicodeString Message =
  3419. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3420. unsigned int Answer =
  3421. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3422. if (Answer != qaOK)
  3423. {
  3424. UsageState = "R";
  3425. }
  3426. else
  3427. {
  3428. UsageState = "A";
  3429. TEditorData EditorData;
  3430. EditorData.Editor = edExternal;
  3431. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3432. EditorData.ExternalEditorOptionsAutodetect();
  3433. TEditorList EditorList;
  3434. EditorList = *WinConfiguration->EditorList;
  3435. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3436. WinConfiguration->EditorList = &EditorList;
  3437. }
  3438. }
  3439. }
  3440. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3441. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3442. }
  3443. //---------------------------------------------------------------------------
  3444. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3445. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3446. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3447. {
  3448. if (ExecuteFileBy == efDefaultEditor)
  3449. {
  3450. if (!WinConfiguration->OfferedEditorAutoConfig)
  3451. {
  3452. EditorAutoConfig();
  3453. }
  3454. const TEditorPreferences * Editor =
  3455. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3456. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3457. {
  3458. ExecuteFileBy = efInternalEditor;
  3459. ExternalEditor = NULL;
  3460. }
  3461. else if (Editor->Data->Editor == edOpen)
  3462. {
  3463. ExecuteFileBy = efShell;
  3464. ExternalEditor = NULL;
  3465. }
  3466. else
  3467. {
  3468. ExecuteFileBy = efExternalEditor;
  3469. ExternalEditor = Editor->Data;
  3470. }
  3471. }
  3472. }
  3473. //---------------------------------------------------------------------------
  3474. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3475. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3476. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3477. {
  3478. UnicodeString OriginalFileName;
  3479. UnicodeString LocalRootDirectory;
  3480. UnicodeString RemoteDirectory;
  3481. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3482. IsSideLocalBrowser(Side), MaskParams);
  3483. UnicodeString Counter;
  3484. UnicodeString LocalFileName;
  3485. bool Handled = false;
  3486. if (!IsSideLocalBrowser(Side))
  3487. {
  3488. // We need to trim VMS version here, so that we use name without version
  3489. // when uploading back to create a new version of the file
  3490. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3491. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3492. TObject * Token = NULL;
  3493. UnicodeString LocalDirectory;
  3494. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3495. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3496. LocalDirectory))
  3497. {
  3498. if (Token != NULL)
  3499. {
  3500. TForm * Form = dynamic_cast<TForm *>(Token);
  3501. if (Form->WindowState == wsMinimized)
  3502. {
  3503. ShowWindow(Form->Handle, SW_RESTORE);
  3504. }
  3505. else
  3506. {
  3507. Form->SetFocus();
  3508. }
  3509. Handled = true;
  3510. }
  3511. else
  3512. {
  3513. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3514. }
  3515. }
  3516. if (!Handled)
  3517. {
  3518. TStringList * FileList1 = new TStringList();
  3519. try
  3520. {
  3521. FileList1->AddObject(FullFileName, Object);
  3522. TemporarilyDownloadFiles(FileList1,
  3523. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3524. LocalRootDirectory, LocalDirectory, true, true, false);
  3525. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3526. }
  3527. __finally
  3528. {
  3529. delete FileList1;
  3530. }
  3531. switch (ExecuteFileBy)
  3532. {
  3533. case efShell:
  3534. Counter = "RemoteFilesExecuted";
  3535. break;
  3536. case efInternalEditor:
  3537. Counter = "RemoteFilesOpenedInInternalEditor";
  3538. break;
  3539. case efExternalEditor:
  3540. Counter = "RemoteFilesOpenedInExternalEditor";
  3541. break;
  3542. default:
  3543. DebugFail();
  3544. }
  3545. }
  3546. }
  3547. else
  3548. {
  3549. LocalFileName = FullFileName;
  3550. OriginalFileName = ExtractFileName(FullFileName);
  3551. switch (ExecuteFileBy)
  3552. {
  3553. case efShell:
  3554. Counter = "LocalFilesExecuted";
  3555. break;
  3556. case efInternalEditor:
  3557. Counter = "LocalFilesOpenedInInternalEditor";
  3558. break;
  3559. case efExternalEditor:
  3560. Counter = "LocalFilesOpenedInExternalEditor";
  3561. break;
  3562. default:
  3563. DebugFail();
  3564. }
  3565. }
  3566. if (!Handled)
  3567. {
  3568. Configuration->Usage->Inc(Counter);
  3569. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3570. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3571. }
  3572. }
  3573. //---------------------------------------------------------------------------
  3574. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3575. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3576. bool AllSelected, bool OnFocused)
  3577. {
  3578. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3579. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3580. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3581. Side = GetSide(Side);
  3582. TCustomDirView * DView = DirView(Side);
  3583. TStrings * FileList =
  3584. AllSelected ?
  3585. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3586. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3587. try
  3588. {
  3589. DebugAssert(AllSelected || (FileList->Count == 1));
  3590. for (int i = 0; i < FileList->Count; i++)
  3591. {
  3592. UnicodeString ListFileName = FileList->Strings[i];
  3593. UnicodeString FileNameOnly =
  3594. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3595. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3596. if (!DView->ItemIsDirectory(Item))
  3597. {
  3598. UnicodeString FullFileName;
  3599. if (!IsSideLocalBrowser(Side))
  3600. {
  3601. FullFileName = DirView(Side)->Path + ListFileName;
  3602. }
  3603. else
  3604. {
  3605. FullFileName = ListFileName;
  3606. }
  3607. TObject * Object = FileList->Objects[i];
  3608. TFileMasks::TParams MaskParams;
  3609. MaskParams.Size = DView->ItemFileSize(Item);
  3610. TDateTimePrecision Precision;
  3611. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3612. std::unique_ptr<TRemoteFile> File;
  3613. if (!IsSideLocalBrowser(Side))
  3614. {
  3615. File.reset(Terminal->TryReadFile(FullFileName));
  3616. if (File.get() != NULL)
  3617. {
  3618. File->FullFileName = FullFileName;
  3619. Object = File.get();
  3620. MaskParams.Size = File->Size;
  3621. MaskParams.Modification = File->Modification;
  3622. }
  3623. }
  3624. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3625. }
  3626. }
  3627. }
  3628. __finally
  3629. {
  3630. delete FileList;
  3631. }
  3632. }
  3633. //---------------------------------------------------------------------------
  3634. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3635. {
  3636. CopyParam.FileNameCase = ncNoChange;
  3637. CopyParam.PreserveRights = false;
  3638. CopyParam.PreserveReadOnly = false;
  3639. CopyParam.ReplaceInvalidChars = true;
  3640. CopyParam.IncludeFileMask = TFileMasks();
  3641. CopyParam.NewerOnly = false;
  3642. CopyParam.FileMask = L"";
  3643. }
  3644. //---------------------------------------------------------------------------
  3645. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3646. {
  3647. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3648. }
  3649. //---------------------------------------------------------------------------
  3650. class TEditorUploadQueueItem : public TUploadQueueItem
  3651. {
  3652. public:
  3653. __fastcall TEditorUploadQueueItem(
  3654. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3655. const TCopyParamType * CopyParam, int Params) :
  3656. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, true, false)
  3657. {
  3658. }
  3659. protected:
  3660. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3661. {
  3662. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3663. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3664. }
  3665. };
  3666. //---------------------------------------------------------------------------
  3667. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3668. {
  3669. if (WinConfiguration->EditorCheckNotModified) // optimization
  3670. {
  3671. UnicodeString RemoteFilePath;
  3672. {
  3673. TGuard Guard(FEditorManager->Section);
  3674. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3675. if (DebugAlwaysTrue(Data != NULL) &&
  3676. EditorCheckNotModified(Data))
  3677. {
  3678. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3679. }
  3680. }
  3681. if (!RemoteFilePath.IsEmpty())
  3682. {
  3683. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3684. if (File.get() != NULL)
  3685. {
  3686. TGuard Guard(FEditorManager->Section);
  3687. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3688. if (DebugAlwaysTrue(Data != NULL))
  3689. {
  3690. Data->SourceTimestamp = File->Modification;
  3691. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3692. }
  3693. }
  3694. }
  3695. }
  3696. }
  3697. //---------------------------------------------------------------------------
  3698. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3699. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3700. {
  3701. TTerminalManager * Manager = TTerminalManager::Instance();
  3702. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3703. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3704. {
  3705. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3706. Retry = true;
  3707. }
  3708. else if (!IsActiveTerminal(Data->Terminal))
  3709. {
  3710. if (!NonVisualDataModule->Busy)
  3711. {
  3712. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3713. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3714. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3715. if (Data->Terminal == NULL)
  3716. {
  3717. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3718. if (SameSiteTerminal != NULL)
  3719. {
  3720. UnicodeString Message =
  3721. FMTLOAD(EDIT_SESSION_REATTACH,
  3722. (FileNameOnly, Data->SessionName, FileNameOnly));
  3723. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3724. {
  3725. Data->Terminal = SameSiteTerminal;
  3726. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3727. // We might also overwrite session data
  3728. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3729. }
  3730. else
  3731. {
  3732. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3733. Abort();
  3734. }
  3735. }
  3736. }
  3737. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3738. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3739. {
  3740. UnicodeString Message =
  3741. MainInstructions(
  3742. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3743. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3744. {
  3745. if (Terminal->Disconnected)
  3746. {
  3747. Manager->ActiveSession = Terminal;
  3748. ReconnectSession();
  3749. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3750. if (!IsActiveTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3751. {
  3752. Abort();
  3753. }
  3754. }
  3755. else
  3756. {
  3757. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3758. }
  3759. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3760. }
  3761. else
  3762. {
  3763. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3764. Abort();
  3765. }
  3766. }
  3767. }
  3768. if (!IsActiveTerminal(Data->Terminal))
  3769. {
  3770. Configuration->Usage->Inc(L"EditInactiveSession");
  3771. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3772. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3773. (ExtractFileName(FileName), Data->SessionName)));
  3774. }
  3775. }
  3776. if (!Retry && EditorCheckNotModified(Data))
  3777. {
  3778. if (NonVisualDataModule->Busy)
  3779. {
  3780. Retry = true;
  3781. }
  3782. else
  3783. {
  3784. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3785. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3786. if (File.get() != NULL)
  3787. {
  3788. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3789. if (File->Modification != Data->SourceTimestamp)
  3790. {
  3791. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3792. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3793. {
  3794. Abort();
  3795. }
  3796. }
  3797. }
  3798. }
  3799. }
  3800. if (!Retry)
  3801. {
  3802. TStrings * FileList = new TStringList();
  3803. try
  3804. {
  3805. FileList->Add(FileName);
  3806. // Consider using the same settings (preset) as when the file was downloaded.
  3807. // More over this does not reflect the actual session that will do the upload.
  3808. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3809. TemporaryFileCopyParam(CopyParam);
  3810. if (Data->ForceText)
  3811. {
  3812. CopyParam.TransferMode = tmAscii;
  3813. }
  3814. // so i do not need to worry if masking algorithm works in all cases
  3815. // ("" means "copy file name", no masking is actually done)
  3816. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3817. {
  3818. CopyParam.FileMask = L"";
  3819. }
  3820. else
  3821. {
  3822. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3823. }
  3824. int Params = cpNoConfirmation | cpTemporary;
  3825. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3826. {
  3827. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3828. TQueueItem * QueueItem =
  3829. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3830. QueueItem->CompleteEvent = UploadCompleteEvent;
  3831. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3832. }
  3833. else
  3834. {
  3835. if (NonVisualDataModule->Busy)
  3836. {
  3837. Retry = true;
  3838. }
  3839. else
  3840. {
  3841. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3842. SetEvent(UploadCompleteEvent);
  3843. }
  3844. }
  3845. }
  3846. __finally
  3847. {
  3848. delete FileList;
  3849. }
  3850. }
  3851. }
  3852. //---------------------------------------------------------------------------
  3853. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3854. const UnicodeString & FileName, TEditedFileData * Data)
  3855. {
  3856. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3857. DebugAssert(!NonVisualDataModule->Busy);
  3858. if (!IsActiveTerminal(Data->Terminal))
  3859. {
  3860. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3861. (ExtractFileName(FileName), Data->SessionName)));
  3862. }
  3863. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3864. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3865. NonVisualDataModule->StartBusy();
  3866. try
  3867. {
  3868. std::unique_ptr<TRemoteFile> File;
  3869. UnicodeString RemoteFileName =
  3870. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3871. Terminal->ExceptionOnFail = true;
  3872. try
  3873. {
  3874. File.reset(Terminal->ReadFile(RemoteFileName));
  3875. if (!File->HaveFullFileName)
  3876. {
  3877. File->FullFileName = RemoteFileName;
  3878. }
  3879. }
  3880. __finally
  3881. {
  3882. Terminal->ExceptionOnFail = false;
  3883. }
  3884. std::unique_ptr<TStrings> FileList(new TStringList());
  3885. FileList->AddObject(RemoteFileName, File.get());
  3886. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3887. UnicodeString TempDir = ExtractFilePath(FileName);
  3888. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true, false);
  3889. if (EditorCheckNotModified(Data))
  3890. {
  3891. Data->SourceTimestamp = File->Modification;
  3892. }
  3893. // sanity check, the target file name should be still the same
  3894. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3895. }
  3896. __finally
  3897. {
  3898. NonVisualDataModule->EndBusy();
  3899. // it actually may not exist anymore...
  3900. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3901. }
  3902. }
  3903. //---------------------------------------------------------------------------
  3904. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3905. const TEditedFileData * Data, bool & KeepOpen)
  3906. {
  3907. // Command is set for external editors only (not for "shell" open).
  3908. if (!Data->Command.IsEmpty())
  3909. {
  3910. bool AnyFound = false;
  3911. bool AnyMDI = false;
  3912. bool AnyNonMDI = false;
  3913. bool AnyDetect = false;
  3914. TEditorList * EditorList = new TEditorList();
  3915. try
  3916. {
  3917. *EditorList = *WinConfiguration->EditorList;
  3918. for (int i = 0; i < EditorList->Count; i++)
  3919. {
  3920. const TEditorPreferences * Editor = EditorList->Editors[i];
  3921. if ((Editor->Data->Editor == edExternal) &&
  3922. (Editor->Data->ExternalEditor == Data->Command))
  3923. {
  3924. AnyFound = true;
  3925. if (Editor->Data->SDIExternalEditor)
  3926. {
  3927. AnyNonMDI = true;
  3928. if (Editor->Data->DetectMDIExternalEditor)
  3929. {
  3930. AnyDetect = true;
  3931. }
  3932. }
  3933. else
  3934. {
  3935. AnyMDI = true;
  3936. }
  3937. }
  3938. }
  3939. bool EnableMDI = false;
  3940. bool DisableDetect = false;
  3941. if (AnyMDI)
  3942. {
  3943. KeepOpen = true;
  3944. if (AnyNonMDI)
  3945. {
  3946. // there is at least one instance of the editor with MDI support enabled,
  3947. // and one with disabled, enable it for all instances
  3948. EnableMDI = true;
  3949. }
  3950. }
  3951. else if (AnyFound && !AnyDetect)
  3952. {
  3953. // at least once instance found but all have MDI autodetection disabled
  3954. // => close the file (default action)
  3955. }
  3956. else
  3957. {
  3958. // no instance of the editor has MDI support enabled
  3959. TMessageParams Params;
  3960. if (AnyFound)
  3961. {
  3962. // there is at least one instance of the editor
  3963. Params.Params |= mpNeverAskAgainCheck;
  3964. }
  3965. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3966. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3967. switch (Answer)
  3968. {
  3969. case qaNeverAskAgain:
  3970. DisableDetect = true;
  3971. break;
  3972. case qaNo:
  3973. EnableMDI = true;
  3974. KeepOpen = true;
  3975. break;
  3976. }
  3977. }
  3978. if (AnyFound && (EnableMDI || DisableDetect))
  3979. {
  3980. bool Changed = false;
  3981. for (int i = 0; i < EditorList->Count; i++)
  3982. {
  3983. const TEditorPreferences * Editor = EditorList->Editors[i];
  3984. if ((Editor->Data->Editor == edExternal) &&
  3985. (Editor->Data->ExternalEditor == Data->Command) &&
  3986. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3987. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3988. {
  3989. Changed = true;
  3990. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3991. if (EnableMDI)
  3992. {
  3993. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3994. }
  3995. if (DisableDetect)
  3996. {
  3997. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3998. }
  3999. EditorList->Change(i, UpdatedEditor);
  4000. }
  4001. }
  4002. if (Changed)
  4003. {
  4004. WinConfiguration->EditorList = EditorList;
  4005. }
  4006. }
  4007. }
  4008. __finally
  4009. {
  4010. delete EditorList;
  4011. }
  4012. }
  4013. else
  4014. {
  4015. // "open" case
  4016. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4017. qaOK, HELP_APP_EARLY_CLOSED);
  4018. }
  4019. }
  4020. //---------------------------------------------------------------------------
  4021. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4022. {
  4023. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4024. }
  4025. //---------------------------------------------------------------------------
  4026. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4027. {
  4028. SideEnter(osRemote);
  4029. }
  4030. //---------------------------------------------------------------------------
  4031. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4032. {
  4033. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4034. SideEnter(osRemote);
  4035. }
  4036. //---------------------------------------------------------------------------
  4037. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4038. {
  4039. FCurrentSide = Side;
  4040. if (Visible)
  4041. {
  4042. UpdateControls();
  4043. }
  4044. }
  4045. //---------------------------------------------------------------------------
  4046. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  4047. {
  4048. VisualiseOperationFinished(Side, FileName, Success);
  4049. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4050. {
  4051. FDeletedFiles->Add(FileName);
  4052. }
  4053. }
  4054. //---------------------------------------------------------------------------
  4055. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4056. TStrings * FileList, bool Alternative)
  4057. {
  4058. TCustomDirView * DView = DirView(Side);
  4059. DView->SaveSelection();
  4060. DView->SaveSelectedNames();
  4061. DebugAssert(!FAlternativeDelete);
  4062. FAlternativeDelete = Alternative;
  4063. try
  4064. {
  4065. if (!IsSideLocalBrowser(Side))
  4066. {
  4067. DebugAssert(Terminal != NULL);
  4068. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4069. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  4070. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  4071. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  4072. int Params = FLAGMASK(Alternative, dfAlternative);
  4073. try
  4074. {
  4075. DebugAssert(FDeletedFiles == NULL);
  4076. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles, DeletedFiles.get());
  4077. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4078. FOnFileOperationFinished = FileDeleted;
  4079. FMoveToQueue = false;
  4080. Terminal->DeleteFiles(FileList, Params);
  4081. // Probably not needed for deleting, just for consistency with transfer code
  4082. if (FMoveToQueue)
  4083. {
  4084. Abort();
  4085. }
  4086. }
  4087. catch (EAbort &)
  4088. {
  4089. if (FMoveToQueue)
  4090. {
  4091. DeletedFiles->Sorted = true;
  4092. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4093. {
  4094. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4095. {
  4096. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4097. DebugAssert(Index == 0);
  4098. PermanentFileList->Delete(Index);
  4099. Index--;
  4100. }
  4101. }
  4102. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4103. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4104. AddQueueItem(Queue, QueueItem, Terminal);
  4105. ClearOperationSelection(osRemote);
  4106. }
  4107. }
  4108. }
  4109. else
  4110. {
  4111. if (IsLocalBrowserMode())
  4112. {
  4113. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4114. }
  4115. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  4116. try
  4117. {
  4118. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  4119. }
  4120. __finally
  4121. {
  4122. ReloadLocalDirectory();
  4123. }
  4124. }
  4125. FAlternativeDelete = false;
  4126. }
  4127. catch(...)
  4128. {
  4129. FAlternativeDelete = false;
  4130. DView->DiscardSavedSelection();
  4131. throw;
  4132. }
  4133. DView->RestoreSelection();
  4134. }
  4135. //---------------------------------------------------------------------------
  4136. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4137. {
  4138. DebugAssert(Terminal);
  4139. DebugAssert(!IsLocalBrowserMode());
  4140. RemoteDirView->SaveSelection();
  4141. RemoteDirView->SaveSelectedNames();
  4142. try
  4143. {
  4144. if (Lock)
  4145. {
  4146. Terminal->LockFiles(FileList);
  4147. }
  4148. else
  4149. {
  4150. Terminal->UnlockFiles(FileList);
  4151. }
  4152. }
  4153. catch(...)
  4154. {
  4155. RemoteDirView->DiscardSavedSelection();
  4156. throw;
  4157. }
  4158. RemoteDirView->RestoreSelection();
  4159. }
  4160. //---------------------------------------------------------------------------
  4161. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4162. {
  4163. bool Result = false;
  4164. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4165. if (IsActiveTerminal(ATerminal))
  4166. {
  4167. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(Directory));
  4168. Result = File && File->IsDirectory;
  4169. }
  4170. return Result;
  4171. }
  4172. //---------------------------------------------------------------------------
  4173. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4174. {
  4175. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4176. return
  4177. !Terminal->IsCapable[fcRemoteCopy] ||
  4178. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4179. }
  4180. //---------------------------------------------------------------------------
  4181. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4182. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4183. bool NoConfirmation, bool Move)
  4184. {
  4185. DebugAssert(Terminal != NULL);
  4186. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4187. DebugAssert(!IsLocalBrowserMode());
  4188. if (Session == NULL)
  4189. {
  4190. Session = Terminal;
  4191. }
  4192. bool TargetConfirmed = false;
  4193. if (Session == Terminal)
  4194. {
  4195. if (RemoteDriveView->DropTarget != NULL)
  4196. {
  4197. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4198. TargetConfirmed = true;
  4199. }
  4200. else if (RemoteDirView->DropTarget != NULL)
  4201. {
  4202. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4203. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4204. TargetConfirmed = true;
  4205. }
  4206. else
  4207. {
  4208. Target = RemoteDirView->Path;
  4209. }
  4210. }
  4211. else
  4212. {
  4213. Target = GetSessionPath(Session, osRemote);
  4214. }
  4215. Target = UnixIncludeTrailingBackslash(Target);
  4216. if (FileList->Count == 1)
  4217. {
  4218. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4219. }
  4220. else
  4221. {
  4222. FileMask = AnyMask;
  4223. }
  4224. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4225. bool Result = true;
  4226. if (!NoConfirmation)
  4227. {
  4228. bool Multi = (FileList->Count > 1);
  4229. if (Move)
  4230. {
  4231. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4232. }
  4233. else
  4234. {
  4235. std::unique_ptr<TStrings> Sessions(new TStringList);
  4236. std::unique_ptr<TStrings> Directories(new TStringList);
  4237. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4238. for (int Index = 0; Index < SessionList->Count; Index++)
  4239. {
  4240. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4241. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4242. {
  4243. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4244. Directories->Add(GetSessionPath(ASession, osRemote));
  4245. }
  4246. }
  4247. bool AnyDirectory = false;
  4248. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4249. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4250. {
  4251. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4252. {
  4253. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4254. }
  4255. }
  4256. TDirectRemoteCopy AllowDirectCopy;
  4257. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4258. {
  4259. DebugAssert(DirectCopy);
  4260. AllowDirectCopy = drcAllow;
  4261. }
  4262. else if (Terminal->IsCapable[fcSecondaryShell])
  4263. {
  4264. DebugAssert(DirectCopy);
  4265. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4266. }
  4267. else
  4268. {
  4269. DebugAssert(!DirectCopy);
  4270. AllowDirectCopy = drcDisallow;
  4271. }
  4272. void * ASession = Session;
  4273. Result = DoRemoteCopyDialog(
  4274. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4275. DoDirectoryExists, TargetConfirmed);
  4276. Session = static_cast<TManagedTerminal *>(ASession);
  4277. }
  4278. }
  4279. return Result;
  4280. }
  4281. //---------------------------------------------------------------------------
  4282. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4283. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4284. {
  4285. DebugAssert(!IsLocalBrowserMode());
  4286. bool DirectCopy;
  4287. UnicodeString Target, FileMask;
  4288. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4289. if (Result)
  4290. {
  4291. if (!Move && !DirectCopy)
  4292. {
  4293. Configuration->Usage->Inc("RemoteCopyTemp");
  4294. UnicodeString RootTempDir;
  4295. UnicodeString TempDir;
  4296. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  4297. TStrings * TemporaryFilesList = new TStringList();
  4298. try
  4299. {
  4300. TMakeLocalFileListParams MakeFileListParam;
  4301. MakeFileListParam.FileList = TemporaryFilesList;
  4302. MakeFileListParam.FileTimes = NULL;
  4303. MakeFileListParam.IncludeDirs = true;
  4304. MakeFileListParam.Recursive = false;
  4305. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4306. TTerminalManager::Instance()->ActiveSession = Session;
  4307. if (TemporaryFilesList->Count > 0)
  4308. {
  4309. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4310. CopyParam.FileMask = FileMask;
  4311. DebugAssert(!FAutoOperation);
  4312. FAutoOperation = true;
  4313. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4314. }
  4315. }
  4316. __finally
  4317. {
  4318. delete TemporaryFilesList;
  4319. FAutoOperation = false;
  4320. if (!RootTempDir.IsEmpty())
  4321. {
  4322. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4323. }
  4324. }
  4325. }
  4326. else
  4327. {
  4328. RemoteDirView->SaveSelection();
  4329. RemoteDirView->SaveSelectedNames();
  4330. try
  4331. {
  4332. if (Move)
  4333. {
  4334. Configuration->Usage->Inc("RemoteMove");
  4335. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4336. }
  4337. else
  4338. {
  4339. Configuration->Usage->Inc("RemoteCopyDirect");
  4340. DebugAssert(DirectCopy);
  4341. DebugAssert(Session == Terminal);
  4342. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4343. Terminal->CommandSessionOpened ||
  4344. CommandSessionFallback())
  4345. {
  4346. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4347. }
  4348. }
  4349. }
  4350. catch(...)
  4351. {
  4352. RemoteDirView->DiscardSavedSelection();
  4353. throw;
  4354. }
  4355. RemoteDirView->RestoreSelection();
  4356. }
  4357. }
  4358. return Result;
  4359. }
  4360. //---------------------------------------------------------------------------
  4361. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4362. const UnicodeString & Path, TRemoteProperties & Properties)
  4363. {
  4364. DebugAssert(!IsLocalBrowserMode());
  4365. Properties.Valid = Properties.Valid << vpEncrypt;
  4366. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4367. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4368. }
  4369. //---------------------------------------------------------------------------
  4370. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4371. {
  4372. Side = GetSide(Side);
  4373. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4374. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4375. UnicodeString Name = LoadStr(NEW_FOLDER);
  4376. int AllowedChanges =
  4377. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4378. bool SaveSettings = false;
  4379. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4380. {
  4381. TWindowLock Lock(this);
  4382. if (!IsSideLocalBrowser(Side))
  4383. {
  4384. if (SaveSettings)
  4385. {
  4386. GUIConfiguration->NewDirectoryProperties = Properties;
  4387. }
  4388. CreateRemoteDirectory(Name, Properties);
  4389. }
  4390. else
  4391. {
  4392. DirView(Side)->CreateDirectory(Name);
  4393. }
  4394. }
  4395. }
  4396. //---------------------------------------------------------------------------
  4397. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4398. {
  4399. TWindowLock Lock(this);
  4400. DirView(Side)->ExecuteHomeDirectory();
  4401. }
  4402. //---------------------------------------------------------------------------
  4403. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4404. {
  4405. DoOpenDirectoryDialog(odBrowse, Side);
  4406. }
  4407. //---------------------------------------------------------------------------
  4408. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4409. {
  4410. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4411. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4412. bool Result = !Path.IsEmpty();
  4413. if (Result)
  4414. {
  4415. TryOpenDirectory(Side, Path);
  4416. }
  4417. return Result;
  4418. }
  4419. //---------------------------------------------------------------------------
  4420. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4421. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4422. bool & Close)
  4423. {
  4424. // terminal can be already closed (e.g. dropped connection)
  4425. if (Terminal != NULL)
  4426. {
  4427. try
  4428. {
  4429. TCalculateSizeParams Params;
  4430. Params.Stats = &Stats;
  4431. Terminal->CalculateFilesSize(FileList, Size, Params);
  4432. }
  4433. catch(...)
  4434. {
  4435. if (!Terminal->Active)
  4436. {
  4437. Close = true;
  4438. }
  4439. throw;
  4440. }
  4441. }
  4442. }
  4443. //---------------------------------------------------------------------------
  4444. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4445. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4446. bool & Close)
  4447. {
  4448. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4449. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4450. {
  4451. Configuration->Usage->Inc(L"ChecksumCalculated");
  4452. try
  4453. {
  4454. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4455. }
  4456. catch(...)
  4457. {
  4458. if (!Terminal->Active)
  4459. {
  4460. Close = true;
  4461. }
  4462. throw;
  4463. }
  4464. }
  4465. }
  4466. //---------------------------------------------------------------------------
  4467. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4468. {
  4469. if (Terminal->LoadFilesProperties(FileList))
  4470. {
  4471. RemoteDirView->Invalidate();
  4472. }
  4473. }
  4474. //---------------------------------------------------------------------------
  4475. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4476. {
  4477. return
  4478. Terminal->IsCapable[fcCalculatingChecksum] ||
  4479. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4480. }
  4481. //---------------------------------------------------------------------------
  4482. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4483. {
  4484. bool Result;
  4485. if (!IsSideLocalBrowser(Side))
  4486. {
  4487. TRemoteTokenList * GroupList = NULL;
  4488. TRemoteTokenList * UserList = NULL;
  4489. try
  4490. {
  4491. TRemoteProperties CurrentProperties;
  4492. LoadFilesProperties(FileList);
  4493. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4494. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4495. if (CapableGroupChanging || CapableOwnerChanging)
  4496. {
  4497. if (CapableGroupChanging)
  4498. {
  4499. GroupList = Terminal->Groups->Duplicate();
  4500. }
  4501. if (CapableOwnerChanging)
  4502. {
  4503. UserList = Terminal->Users->Duplicate();
  4504. }
  4505. TRemoteDirectory * Files = Terminal->Files;
  4506. int Count = Files->Count;
  4507. if (Count > 100)
  4508. {
  4509. Count = 100;
  4510. }
  4511. for (int Index = 0; Index < Count; Index++)
  4512. {
  4513. TRemoteFile * File = Files->Files[Index];
  4514. if (CapableGroupChanging)
  4515. {
  4516. GroupList->AddUnique(File->Group);
  4517. }
  4518. if (CapableOwnerChanging)
  4519. {
  4520. UserList->AddUnique(File->Owner);
  4521. }
  4522. }
  4523. // if we haven't collected tokens for all files in current directory,
  4524. // make sure we collect them at least for all selected files.
  4525. // (note that so far the files in FileList has to be from current direcotry)
  4526. if (Count < Files->Count)
  4527. {
  4528. for (int Index = 0; Index < FileList->Count; Index++)
  4529. {
  4530. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4531. if (CapableGroupChanging)
  4532. {
  4533. GroupList->AddUnique(File->Group);
  4534. }
  4535. if (CapableOwnerChanging)
  4536. {
  4537. UserList->AddUnique(File->Owner);
  4538. }
  4539. }
  4540. }
  4541. }
  4542. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4543. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4544. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4545. {
  4546. CapableAclChanging = false;
  4547. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4548. }
  4549. int Flags = 0;
  4550. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4551. if (CapableAclChanging) Flags |= cpAcl;
  4552. if (CapableOwnerChanging) Flags |= cpOwner;
  4553. if (CapableGroupChanging) Flags |= cpGroup;
  4554. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4555. if (CanCalculateChecksum())
  4556. {
  4557. CalculateChecksumEvent = CalculateChecksum;
  4558. }
  4559. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4560. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4561. TRemoteProperties NewProperties = CurrentProperties;
  4562. Result =
  4563. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4564. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4565. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4566. CalculateSize, CalculateChecksumEvent);
  4567. if (Result)
  4568. {
  4569. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4570. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4571. }
  4572. }
  4573. __finally
  4574. {
  4575. delete GroupList;
  4576. delete UserList;
  4577. }
  4578. }
  4579. else
  4580. {
  4581. DirView(Side)->DisplayPropertiesMenu();
  4582. Result = true;
  4583. }
  4584. return Result;
  4585. }
  4586. //---------------------------------------------------------------------------
  4587. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4588. {
  4589. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4590. {
  4591. FIgnoreNextDialogChar = Key;
  4592. }
  4593. Key = 0;
  4594. }
  4595. //---------------------------------------------------------------------------
  4596. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4597. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4598. {
  4599. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4600. if (Command != NULL)
  4601. {
  4602. KeyProcessed(Key, Shift);
  4603. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4604. {
  4605. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4606. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4607. false, false, const_cast<TCustomCommandType *>(Command));
  4608. }
  4609. }
  4610. }
  4611. //---------------------------------------------------------------------------
  4612. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4613. {
  4614. if (!NonVisualDataModule->Busy)
  4615. {
  4616. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4617. {
  4618. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4619. }
  4620. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4621. {
  4622. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4623. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4624. {
  4625. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4626. // But so far it's not a problem, as it does what we want.
  4627. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4628. if (((Action->ShortCut == KeyShortCut) ||
  4629. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4630. AllowedAction(Action, aaShortCut))
  4631. {
  4632. // Has to be called before the action as the dialog char is already in queue.
  4633. // So when the action consumes message queue, we already need to have the
  4634. // FIgnoreNextDialogChar set
  4635. KeyProcessed(Key, Shift);
  4636. // Reset reference to previous component (when menu/toolbar was clicked).
  4637. // Needed to detect that action was invoked by keyboard shortcut
  4638. // in TNonVisualDataModule::ExplorerActionsExecute
  4639. Action->ActionComponent = NULL;
  4640. Action->Execute();
  4641. return;
  4642. }
  4643. }
  4644. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4645. {
  4646. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4647. {
  4648. KeyProcessed(Key, Shift);
  4649. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4650. return;
  4651. }
  4652. }
  4653. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4654. {
  4655. KeyProcessed(Key, Shift);
  4656. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4657. }
  4658. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4659. if (IsCustomShortCut(CustomShortCut))
  4660. {
  4661. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4662. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4663. if (WinConfiguration->SharedBookmarks != NULL)
  4664. {
  4665. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4666. if ((Bookmark != NULL) &&
  4667. OpenBookmark(FCurrentSide, Bookmark))
  4668. {
  4669. KeyProcessed(Key, Shift);
  4670. }
  4671. }
  4672. }
  4673. }
  4674. }
  4675. TForm::KeyDown(Key, Shift);
  4676. }
  4677. //---------------------------------------------------------------------------
  4678. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4679. {
  4680. bool OpenedTerminal = false;
  4681. UnicodeString ProtocolName;
  4682. UnicodeString ProtocolNameHint;
  4683. UnicodeString SecurityProtocolName;
  4684. UnicodeString DurationHint;
  4685. // See the comment in TScpCommanderForm::UpdateControls()
  4686. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4687. if (ActiveTerminal != NULL)
  4688. {
  4689. // Active is not enough here
  4690. if (ActiveTerminal->Status == ssOpened)
  4691. {
  4692. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4693. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4694. if (FileSystemInfo.ProtocolName.IsEmpty())
  4695. {
  4696. ProtocolName = SessionInfo.ProtocolName;
  4697. }
  4698. else
  4699. {
  4700. ProtocolName = FileSystemInfo.ProtocolName;
  4701. }
  4702. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4703. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4704. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4705. OpenedTerminal = true;
  4706. }
  4707. else if (ActiveTerminal->Status > ssClosed)
  4708. {
  4709. ProtocolName = LoadStr(STATUS_CONNECTING);
  4710. }
  4711. else
  4712. {
  4713. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4714. }
  4715. }
  4716. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4717. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4718. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4719. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4720. if (ProtocolStatusPanel->Caption != ProtocolName)
  4721. {
  4722. ProtocolStatusPanel->Caption = ProtocolName;
  4723. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4724. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4725. }
  4726. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4727. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4728. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4729. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4730. SecurityStatusPanel->Enabled = SecurityEnabled;
  4731. UnicodeString SecurityProtocolHint;
  4732. if (SecurityEnabled)
  4733. {
  4734. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4735. }
  4736. else
  4737. {
  4738. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4739. }
  4740. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4741. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4742. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4743. DurationStatusPanel->Hint = DurationHint;
  4744. UpdateStatusBar();
  4745. }
  4746. //---------------------------------------------------------------------------
  4747. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4748. {
  4749. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4750. DebugAssert(SessionStatusBar != NULL);
  4751. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4752. if (!FNote.IsEmpty())
  4753. {
  4754. NoteStatusPanel->Caption = FNote;
  4755. }
  4756. else
  4757. {
  4758. UpdateStatusPanelText(NoteStatusPanel);
  4759. }
  4760. NoteStatusPanel->Hint = FNoteHints;
  4761. UnicodeString LoginTime;
  4762. // See the comment in TScpCommanderForm::UpdateControls()
  4763. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4764. // Active is not enough here
  4765. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4766. {
  4767. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4768. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4769. }
  4770. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4771. DurationStatusPanel->Caption = LoginTime;
  4772. }
  4773. //---------------------------------------------------------------------------
  4774. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4775. {
  4776. Panel->Caption = L"";
  4777. }
  4778. //---------------------------------------------------------------------------
  4779. void __fastcall TCustomScpExplorerForm::Idle()
  4780. {
  4781. if (FShowing ||
  4782. // Particularly for
  4783. // - Standalone editing
  4784. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4785. // while "keeping remote directory up to date".
  4786. StandaloneOperation)
  4787. {
  4788. FEditorManager->Check();
  4789. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4790. // that needs to know if queue view is visible (and it may be closed after queue update)
  4791. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4792. }
  4793. if (FShowing)
  4794. {
  4795. if (!NonVisualDataModule->Busy &&
  4796. // Menu is opened or drag&drop is going on
  4797. (Mouse->Capture == NULL))
  4798. {
  4799. if (FRefreshRemoteDirectory)
  4800. {
  4801. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4802. {
  4803. Terminal->RefreshDirectory();
  4804. }
  4805. FRefreshRemoteDirectory = false;
  4806. }
  4807. if (FRefreshLocalDirectory)
  4808. {
  4809. ReloadLocalDirectory();
  4810. FRefreshLocalDirectory = false;
  4811. }
  4812. if (WinConfiguration->RefreshRemotePanel)
  4813. {
  4814. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4815. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4816. {
  4817. RemoteDirView->ReloadDirectory();
  4818. }
  4819. }
  4820. }
  4821. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4822. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4823. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4824. // And the Alt key can be released even when other window or application is active, so handling the key up in explorer window won't do either.
  4825. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4826. MenuToolbar->Idle();
  4827. }
  4828. if (FShowing || StandaloneOperation)
  4829. {
  4830. if (FQueueStatusInvalidated)
  4831. {
  4832. UpdateQueueStatus(false);
  4833. }
  4834. RefreshQueueItems();
  4835. }
  4836. if (FShowing)
  4837. {
  4838. UpdateStatusBar();
  4839. }
  4840. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4841. {
  4842. FClipboardFakeMonitorsPendingReset = false;
  4843. FClipboardFakeMonitors.reset(NULL);
  4844. }
  4845. FIgnoreNextDialogChar = 0;
  4846. }
  4847. //---------------------------------------------------------------------------
  4848. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4849. {
  4850. try
  4851. {
  4852. FUserActionTimer->Enabled = false;
  4853. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4854. {
  4855. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4856. {
  4857. FPendingQueueActionItem->ProcessUserAction();
  4858. }
  4859. }
  4860. }
  4861. __finally
  4862. {
  4863. FPendingQueueActionItem = NULL;
  4864. }
  4865. }
  4866. //---------------------------------------------------------------------------
  4867. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4868. {
  4869. if (WinConfiguration->MinimizeToTray)
  4870. {
  4871. UpdateTrayIcon();
  4872. FTrayIcon->Visible = true;
  4873. if (Visible)
  4874. {
  4875. ShowWindow(Handle, SW_HIDE);
  4876. }
  4877. }
  4878. }
  4879. //---------------------------------------------------------------------------
  4880. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4881. {
  4882. // WORKAROUND
  4883. // When restoring maximized window from minimization,
  4884. // rarely some controls do not align properly.
  4885. // Two instances seen (both for Commander):
  4886. // - When restoring, window is temporarily narrower (not maximized),
  4887. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4888. // Once maximized already, top dock shinks back, but the session PageControl,
  4889. // do not align up, leaving space between TopDock and PageControl.
  4890. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4891. for (int Index = 0; Index < ControlCount; Index++)
  4892. {
  4893. RealignControl(Controls[Index]);
  4894. }
  4895. if (FTrayIcon->Visible)
  4896. {
  4897. FTrayIcon->Visible = false;
  4898. if (Visible)
  4899. {
  4900. ShowWindow(Handle, SW_SHOW);
  4901. }
  4902. }
  4903. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4904. {
  4905. FNeedSession = false;
  4906. NonVisualDataModule->StartBusy();
  4907. try
  4908. {
  4909. NeedSession(true);
  4910. }
  4911. __finally
  4912. {
  4913. NonVisualDataModule->EndBusy();
  4914. }
  4915. }
  4916. }
  4917. //---------------------------------------------------------------------------
  4918. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4919. {
  4920. FTrayIcon->Hint = GetMainForm()->Caption;
  4921. }
  4922. //---------------------------------------------------------------------------
  4923. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4924. {
  4925. UpdateTrayIcon();
  4926. }
  4927. //---------------------------------------------------------------------------
  4928. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4929. {
  4930. // workaround
  4931. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4932. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4933. // But WM_ACTIVATEAPP message can be received even when
  4934. // the main window is minimized to the tray and internal editor window is focused
  4935. // (after another application was previously active)
  4936. if (::IsIconic(Handle))
  4937. {
  4938. if (!IsAppIconic())
  4939. {
  4940. SetAppIconic(true);
  4941. }
  4942. }
  4943. ::ApplicationRestore();
  4944. Application->BringToFront();
  4945. }
  4946. //---------------------------------------------------------------------------
  4947. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4948. {
  4949. RestoreApp();
  4950. }
  4951. //---------------------------------------------------------------------------
  4952. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4953. {
  4954. if (OpenInNewWindow())
  4955. {
  4956. ExecuteNewInstance(SessionUrl);
  4957. }
  4958. else
  4959. {
  4960. TTerminalManager::Instance()->NewSession(SessionUrl);
  4961. }
  4962. }
  4963. //---------------------------------------------------------------------------
  4964. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4965. {
  4966. NewSession();
  4967. }
  4968. //---------------------------------------------------------------------------
  4969. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4970. {
  4971. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4972. StoredSessions->NewSession(SessionName, SessionData);
  4973. // modified only, explicit
  4974. StoredSessions->Save(false, true);
  4975. // encode session name because of slashes in hierarchical sessions
  4976. return EncodeUrlString(SessionName);
  4977. }
  4978. //---------------------------------------------------------------------------
  4979. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4980. {
  4981. // current working directories become defaults here, what is not right
  4982. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4983. return SaveHiddenDuplicateSession(SessionData.get());
  4984. }
  4985. //---------------------------------------------------------------------------
  4986. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  4987. {
  4988. if (OpenInNewWindow())
  4989. {
  4990. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4991. }
  4992. else
  4993. {
  4994. // current working directories become defaults here, what is not right
  4995. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4996. TTerminalManager * Manager = TTerminalManager::Instance();
  4997. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4998. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4999. // We definitely want these
  5000. ASession->Disconnected = ManagedSession->Disconnected;
  5001. // Not sure about these two
  5002. ASession->Permanent = ManagedSession->Permanent;
  5003. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  5004. Manager->ActiveSession = ASession;
  5005. }
  5006. }
  5007. //---------------------------------------------------------------------------
  5008. void __fastcall TCustomScpExplorerForm::RenameTab()
  5009. {
  5010. UnicodeString Name = ManagedSession->SessionData->SessionName;
  5011. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  5012. // When submitting the default name, do not fix it
  5013. (Name != ManagedSession->SessionData->SessionName))
  5014. {
  5015. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5016. TSessionData::ValidateName(Name);
  5017. // This is inconsistent with how color (for example) is handled.
  5018. ManagedSession->SessionData->Name = Name;
  5019. UpdateControls();
  5020. // Add/Remove distinguishing paths from sessions of the same name.
  5021. SessionListChanged();
  5022. }
  5023. }
  5024. //---------------------------------------------------------------------------
  5025. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5026. {
  5027. DebugAssert(Queue != NULL);
  5028. bool Result = Queue->IsEmpty;
  5029. if (!Result)
  5030. {
  5031. SetFocus();
  5032. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5033. }
  5034. return Result;
  5035. }
  5036. //---------------------------------------------------------------------------
  5037. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5038. {
  5039. return CanCloseQueue(FQueue);
  5040. }
  5041. //---------------------------------------------------------------------------
  5042. void __fastcall TCustomScpExplorerForm::CloseTab()
  5043. {
  5044. if (CanCloseQueue())
  5045. {
  5046. TTerminalManager::Instance()->FreeActiveTerminal();
  5047. }
  5048. }
  5049. //---------------------------------------------------------------------------
  5050. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5051. {
  5052. if (CanCloseQueue())
  5053. {
  5054. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5055. }
  5056. }
  5057. //---------------------------------------------------------------------------
  5058. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5059. {
  5060. DetachTerminal(Terminal);
  5061. RemoteDirView->Terminal = Terminal;
  5062. UpdateRemotePathComboBox(false);
  5063. InitStatusBar();
  5064. UpdateControls();
  5065. }
  5066. //---------------------------------------------------------------------------
  5067. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5068. {
  5069. InitStatusBar();
  5070. }
  5071. //---------------------------------------------------------------------------
  5072. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5073. {
  5074. if (DebugAlwaysTrue(!Terminal->Active))
  5075. {
  5076. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5077. }
  5078. }
  5079. //---------------------------------------------------------------------------
  5080. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5081. {
  5082. if (OpenInNewWindow())
  5083. {
  5084. // encode session name because of slashes in hierarchical sessions
  5085. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5086. }
  5087. else
  5088. {
  5089. TTerminalManager * Manager = TTerminalManager::Instance();
  5090. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5091. Manager->ActiveSession = Terminal;
  5092. }
  5093. }
  5094. //---------------------------------------------------------------------------
  5095. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5096. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5097. {
  5098. TTerminalManager * Manager = TTerminalManager::Instance();
  5099. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5100. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5101. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5102. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5103. {
  5104. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5105. // FirstSession can be null, if none of the workspace sites exist anymore
  5106. // or if all workspace sessions are not suported by the interface
  5107. // (when trying to open all local-local workspace in "explorer" interface)
  5108. if (FirstSession != NULL)
  5109. {
  5110. if (!ConnectFirstTerminal)
  5111. {
  5112. FirstSession->Disconnected = true;
  5113. FirstSession->DisconnectedTemporarily = true;
  5114. }
  5115. Manager->ActiveSession = FirstSession;
  5116. }
  5117. }
  5118. }
  5119. //---------------------------------------------------------------------------
  5120. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5121. {
  5122. if (OpenInNewWindow())
  5123. {
  5124. ExecuteNewInstance(Name);
  5125. }
  5126. else
  5127. {
  5128. DoOpenFolderOrWorkspace(Name, true, false);
  5129. }
  5130. }
  5131. //---------------------------------------------------------------------------
  5132. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5133. bool &CanClose)
  5134. {
  5135. AppLog(L"Windows close query");
  5136. // See the comment in CloseApp()
  5137. if (NonVisualDataModule->Busy)
  5138. {
  5139. CanClose = false;
  5140. }
  5141. else
  5142. {
  5143. TTerminalManager * Manager = TTerminalManager::Instance();
  5144. int ActiveSessions = 0;
  5145. for (int Index = 0; Index < Manager->Count; Index++)
  5146. {
  5147. if (Manager->Sessions[Index]->Active)
  5148. {
  5149. ActiveSessions++;
  5150. }
  5151. }
  5152. // Confirm, when there's at least one active remote session or
  5153. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5154. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5155. WinConfiguration->ConfirmClosingSession)
  5156. {
  5157. unsigned int Result;
  5158. TMessageParams Params(mpNeverAskAgainCheck);
  5159. UnicodeString Message;
  5160. int Answers = qaOK | qaCancel;
  5161. // The current session is the only active session
  5162. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5163. {
  5164. if (!WinConfiguration->AutoSaveWorkspace)
  5165. {
  5166. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5167. }
  5168. else
  5169. {
  5170. Message = LoadStr(CLOSE_SESSION);
  5171. }
  5172. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5173. }
  5174. // Multiple active sessions or one active session, but it's not the current one
  5175. else if (ActiveSessions > 0)
  5176. {
  5177. if (!WinConfiguration->AutoSaveWorkspace)
  5178. {
  5179. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5180. }
  5181. else
  5182. {
  5183. Message = LoadStr(CLOSE_SESSIONS);
  5184. }
  5185. }
  5186. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5187. else
  5188. {
  5189. DebugAlwaysTrue(Manager->Count > 1);
  5190. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5191. Message = LoadStr(CLOSE_WORKSPACE);
  5192. }
  5193. UnicodeString Note;
  5194. if (WinConfiguration->AutoSaveWorkspace)
  5195. {
  5196. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5197. }
  5198. else
  5199. {
  5200. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5201. Answers = qaYes | qaNo | qaCancel;
  5202. }
  5203. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5204. SetFocus();
  5205. Result = MessageDialog(Message, qtConfirmation,
  5206. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5207. if (Result == qaNeverAskAgain)
  5208. {
  5209. WinConfiguration->ConfirmClosingSession = false;
  5210. }
  5211. if (Result == qaNo)
  5212. {
  5213. CanClose = SaveWorkspace(true);
  5214. // note that the workspace will be saved redundatly again from FormClose
  5215. }
  5216. else
  5217. {
  5218. CanClose =
  5219. (Result == qaOK) ||
  5220. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5221. (Result == qaNeverAskAgain);
  5222. }
  5223. }
  5224. if (CanClose && HasActiveTerminal())
  5225. {
  5226. CanClose = CanCloseQueue();
  5227. }
  5228. }
  5229. if (CanClose)
  5230. {
  5231. CanClose =
  5232. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5233. FEditorManager->CloseExternalFilesWithoutProcess();
  5234. if (CanClose)
  5235. {
  5236. while (CanClose && (FLocalEditors->Count > 0))
  5237. {
  5238. int PrevCount = FLocalEditors->Count;
  5239. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5240. CanClose = (FLocalEditors->Count < PrevCount);
  5241. }
  5242. if (CanClose)
  5243. {
  5244. CanClose = FEditorManager->Empty(true);
  5245. if (!CanClose)
  5246. {
  5247. SetFocus();
  5248. CanClose =
  5249. (MessageDialog(
  5250. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5251. }
  5252. }
  5253. }
  5254. }
  5255. }
  5256. //---------------------------------------------------------------------------
  5257. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5258. {
  5259. TForm * Form = dynamic_cast<TForm *>(Sender);
  5260. DebugAssert(Form != NULL);
  5261. Form->Close();
  5262. }
  5263. //---------------------------------------------------------------------------
  5264. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5265. {
  5266. TForm * Form = dynamic_cast<TForm *>(Sender);
  5267. delete Form;
  5268. }
  5269. //---------------------------------------------------------------------------
  5270. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5271. {
  5272. while (FLocalEditors->Count > 0)
  5273. {
  5274. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5275. }
  5276. }
  5277. //---------------------------------------------------------------------------
  5278. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5279. TObject *Sender)
  5280. {
  5281. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5282. try
  5283. {
  5284. SetProperties(osRemote, FileList);
  5285. }
  5286. __finally
  5287. {
  5288. delete FileList;
  5289. }
  5290. }
  5291. //---------------------------------------------------------------------------
  5292. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5293. {
  5294. if (value)
  5295. {
  5296. if (Component == fcCustomCommandsBand)
  5297. {
  5298. UpdateCustomCommandsToolbar();
  5299. }
  5300. if (Component == fcQueueFileList)
  5301. {
  5302. DebugAssert(!QueueFileListSplitter->Visible);
  5303. AdjustQueueLayout();
  5304. UpdateQueueFileList();
  5305. }
  5306. }
  5307. }
  5308. //---------------------------------------------------------------------------
  5309. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5310. {
  5311. int MinHeightLimit =
  5312. GetStaticQueuePanelComponentsHeight() +
  5313. QueueFileListSplitter->Height +
  5314. QueueFileList->Height +
  5315. GetMinQueueViewHeight();
  5316. if (QueuePanel->ClientHeight < MinHeightLimit)
  5317. {
  5318. QueuePanel->ClientHeight = MinHeightLimit;
  5319. }
  5320. }
  5321. //---------------------------------------------------------------------------
  5322. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5323. {
  5324. TControl * Control = GetComponent(Component);
  5325. DebugAssert(Control);
  5326. bool Changed = (Control->Visible != value);
  5327. if (Changed)
  5328. {
  5329. ComponentShowing(Component, value);
  5330. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5331. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5332. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5333. if (value)
  5334. {
  5335. int RemainingHeight = Control->Parent->ClientHeight;
  5336. int RemainingWidth = Control->Parent->ClientWidth;
  5337. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5338. {
  5339. TControl * ChildControl = Control->Parent->Controls[i];
  5340. if (ChildControl->Visible)
  5341. {
  5342. switch (ChildControl->Align)
  5343. {
  5344. case alTop:
  5345. case alBottom:
  5346. RemainingHeight -= ChildControl->Height;
  5347. break;
  5348. case alLeft:
  5349. case alRight:
  5350. RemainingWidth -= ChildControl->Width;
  5351. break;
  5352. }
  5353. }
  5354. }
  5355. int Reserve = ScaleByTextHeight(this, 32);
  5356. // queue in explorer, trees in commander
  5357. if (Control->Height > RemainingHeight - Reserve)
  5358. {
  5359. Control->Height = RemainingHeight / 2;
  5360. }
  5361. if (Control->Width > RemainingWidth - Reserve)
  5362. {
  5363. Control->Width = RemainingWidth / 2;
  5364. }
  5365. }
  5366. Control->Visible = value;
  5367. if (WasFocused && Visible)
  5368. {
  5369. DirView(osCurrent)->SetFocus();
  5370. }
  5371. FixControlsPlacement();
  5372. }
  5373. }
  5374. //---------------------------------------------------------------------------
  5375. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5376. {
  5377. TControl * Control = GetComponent(Component);
  5378. if (Control == NULL)
  5379. {
  5380. return false;
  5381. }
  5382. else
  5383. {
  5384. return Control->Visible;
  5385. }
  5386. }
  5387. //---------------------------------------------------------------------------
  5388. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5389. {
  5390. bool Result;
  5391. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5392. {
  5393. Result = !IsUWP();
  5394. }
  5395. else
  5396. {
  5397. Result = true;
  5398. }
  5399. return Result;
  5400. }
  5401. //---------------------------------------------------------------------------
  5402. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5403. {
  5404. if (DirView->ItemFocused != NULL)
  5405. {
  5406. DirView->ItemFocused->MakeVisible(false);
  5407. }
  5408. }
  5409. //---------------------------------------------------------------------------
  5410. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5411. {
  5412. MakeFocusedItemVisible(RemoteDirView);
  5413. QueueSplitter->Visible = QueuePanel->Visible;
  5414. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5415. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5416. TControl * TopControlsOrder[] =
  5417. { TopDock, MessageDock, SessionsPageControl };
  5418. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5419. TControl * QueueControlsOrder[] =
  5420. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5421. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5422. }
  5423. //---------------------------------------------------------------------------
  5424. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5425. {
  5426. switch (Component) {
  5427. case fcStatusBar: return RemoteStatusBar;
  5428. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5429. case fcQueueView: return QueuePanel;
  5430. case fcQueueToolbar: return QueueDock;
  5431. case fcRemoteTree: return RemoteDrivePanel;
  5432. case fcSessionsTabs: return SessionsPageControl;
  5433. case fcQueueFileList: return QueueFileList;
  5434. default: return NULL;
  5435. }
  5436. }
  5437. //---------------------------------------------------------------------------
  5438. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5439. TObject *Sender, TListColumn *Column, TPoint &Point)
  5440. {
  5441. DebugAssert(NonVisualDataModule && Column && Sender);
  5442. NonVisualDataModule->ListColumn = Column;
  5443. TPopupMenu * DirViewColumnMenu;
  5444. if (Sender == DirView(osOther))
  5445. {
  5446. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5447. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5448. bool SizeColumn = (Column->Index == uvSize);
  5449. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5450. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5451. }
  5452. else
  5453. {
  5454. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5455. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5456. bool SizeColumn = (Column->Index == dvSize);
  5457. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5458. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5459. }
  5460. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5461. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5462. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5463. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5464. }
  5465. //---------------------------------------------------------------------------
  5466. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5467. TObject *Sender, TListItem *Item, bool &AllowExec)
  5468. {
  5469. DoDirViewExecFile(Sender, Item, AllowExec);
  5470. }
  5471. //---------------------------------------------------------------------------
  5472. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5473. TListItem * Item, bool & AllowExec)
  5474. {
  5475. DebugAssert(Sender && Item && Configuration);
  5476. DebugAssert(AllowExec);
  5477. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5478. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5479. bool Remote = !IsSideLocalBrowser(Side);
  5480. DebugAssert(Item == ADirView->ItemFocused);
  5481. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5482. TResolvedDoubleClickAction Action;
  5483. if (FForceExecution)
  5484. {
  5485. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5486. }
  5487. else
  5488. {
  5489. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5490. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5491. }
  5492. if (Action == rdcaCopy)
  5493. {
  5494. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5495. UnlockWindow();
  5496. try
  5497. {
  5498. if (IsLocalBrowserMode())
  5499. {
  5500. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5501. }
  5502. else
  5503. {
  5504. if (HasActiveTerminal())
  5505. {
  5506. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5507. }
  5508. }
  5509. }
  5510. __finally
  5511. {
  5512. LockWindow();
  5513. }
  5514. AllowExec = false;
  5515. }
  5516. else if (Action == rdcaEdit)
  5517. {
  5518. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5519. {
  5520. ExecuteFile(Side, efDefaultEditor);
  5521. AllowExec = false;
  5522. }
  5523. }
  5524. else if (Action == rdcaOpen)
  5525. {
  5526. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5527. {
  5528. ExecuteFile(osRemote, efShell);
  5529. AllowExec = false;
  5530. }
  5531. }
  5532. }
  5533. //---------------------------------------------------------------------------
  5534. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5535. {
  5536. return ((Side == osRemote) || (Side == osCurrent));
  5537. }
  5538. //---------------------------------------------------------------------------
  5539. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5540. {
  5541. DebugFail();
  5542. }
  5543. //---------------------------------------------------------------------------
  5544. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5545. {
  5546. DebugFail();
  5547. }
  5548. //---------------------------------------------------------------------------
  5549. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5550. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5551. {
  5552. TSynchronizeParamType Params;
  5553. Params.LocalDirectory = LocalDirectory;
  5554. Params.RemoteDirectory = RemoteDirectory;
  5555. int UnusedParams =
  5556. (GUIConfiguration->SynchronizeParams &
  5557. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5558. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5559. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5560. Params.Options = GUIConfiguration->SynchronizeOptions;
  5561. bool SaveSettings = false;
  5562. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5563. &DoSynchronizeTooManyDirectories);
  5564. DebugAssert(FSynchronizeController == NULL);
  5565. FSynchronizeController = &Controller;
  5566. bool Result;
  5567. try
  5568. {
  5569. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5570. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5571. int Options =
  5572. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5573. DebugAssert(FOnFeedSynchronizeError == NULL);
  5574. DebugAssert(FOnSynchronizeAbort == NULL);
  5575. DebugAssert(FSynchronizeTerminal == NULL);
  5576. FSynchronizeTerminal = Terminal;
  5577. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5578. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5579. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5580. if (Result)
  5581. {
  5582. if (SaveSettings)
  5583. {
  5584. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5585. GUIConfiguration->SynchronizeOptions = Params.Options;
  5586. }
  5587. else
  5588. {
  5589. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5590. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5591. FLAGSET(Params.Options, soSynchronize))
  5592. {
  5593. GUIConfiguration->SynchronizeOptions =
  5594. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5595. soSynchronize;
  5596. }
  5597. }
  5598. LocalDirectory = Params.LocalDirectory;
  5599. RemoteDirectory = Params.RemoteDirectory;
  5600. }
  5601. }
  5602. __finally
  5603. {
  5604. FSynchronizeController = NULL;
  5605. DebugAssert(FOnFeedSynchronizeError == NULL);
  5606. FOnFeedSynchronizeError = NULL;
  5607. DebugAssert(FOnSynchronizeAbort == NULL);
  5608. FOnSynchronizeAbort = NULL;
  5609. FSynchronizeTerminal = NULL;
  5610. }
  5611. return Result;
  5612. }
  5613. //---------------------------------------------------------------------------
  5614. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5615. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5616. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5617. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5618. TSynchronizeOptions * Options, bool Full)
  5619. {
  5620. // Keep-up-to-date mode
  5621. if (Terminal->Status == ssOpened)
  5622. {
  5623. try
  5624. {
  5625. int PParams = Params.Params;
  5626. if (!Full)
  5627. {
  5628. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5629. if (FLAGSET(Params.Options, soRecurse))
  5630. {
  5631. PParams |= TTerminal::spSubDirs;
  5632. }
  5633. }
  5634. else
  5635. {
  5636. // if keepuptodate is non-recursive,
  5637. // full sync before has to be non-recursive as well
  5638. if (FLAGCLEAR(Params.Options, soRecurse))
  5639. {
  5640. PParams |= TTerminal::spNoRecurse;
  5641. }
  5642. }
  5643. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5644. PParams, Checklist, Options);
  5645. }
  5646. catch (Exception & E)
  5647. {
  5648. if (!Terminal->Active)
  5649. {
  5650. ShowExtendedExceptionEx(Terminal, &E);
  5651. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5652. if (!Terminal->Active)
  5653. {
  5654. throw;
  5655. }
  5656. }
  5657. else
  5658. {
  5659. if (FLAGSET(Params.Options, soContinueOnError) &&
  5660. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5661. {
  5662. // noop, already logged in MoreMessageDialog
  5663. }
  5664. else
  5665. {
  5666. // We get mostly EAbort here, so this is noop.
  5667. // Exception is an error when listing directories while looking for differences.
  5668. ShowExtendedExceptionEx(Terminal, &E);
  5669. throw;
  5670. }
  5671. }
  5672. }
  5673. }
  5674. }
  5675. //---------------------------------------------------------------------------
  5676. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5677. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5678. const UnicodeString ErrorStr)
  5679. {
  5680. if (!Directory.IsEmpty())
  5681. {
  5682. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5683. }
  5684. else
  5685. {
  5686. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5687. }
  5688. }
  5689. //---------------------------------------------------------------------------
  5690. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5691. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5692. {
  5693. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5694. {
  5695. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5696. }
  5697. else
  5698. {
  5699. TMessageParams Params(mpNeverAskAgainCheck);
  5700. unsigned int Result = MessageDialog(
  5701. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5702. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5703. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5704. {
  5705. MaxDirectories *= 2;
  5706. if (Result == qaNeverAskAgain)
  5707. {
  5708. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5709. }
  5710. }
  5711. else
  5712. {
  5713. Abort();
  5714. }
  5715. }
  5716. }
  5717. //---------------------------------------------------------------------------
  5718. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5719. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5720. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5721. TSynchronizeOptions * Options)
  5722. {
  5723. // Keep-up-to-date mode
  5724. DebugAssert(!FAutoOperation);
  5725. void * BatchStorage;
  5726. BatchStart(BatchStorage);
  5727. FAutoOperation = true;
  5728. bool AnyOperation = false;
  5729. TDateTime StartTime = Now();
  5730. TSynchronizeChecklist * AChecklist = NULL;
  5731. try
  5732. {
  5733. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5734. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5735. {
  5736. FSynchronizeProgressForm->Start();
  5737. }
  5738. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5739. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5740. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5741. Options);
  5742. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5743. SAFE_DESTROY(FSynchronizeProgressForm);
  5744. AnyOperation = (AChecklist->CheckedCount > 0);
  5745. if (AnyOperation)
  5746. {
  5747. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5748. CreateProgressForm(&SynchronizeProgress);
  5749. try
  5750. {
  5751. Terminal->SynchronizeApply(
  5752. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5753. SynchronizeProcessedItem, NULL, NULL, NULL);
  5754. }
  5755. __finally
  5756. {
  5757. DestroyProgressForm();
  5758. }
  5759. }
  5760. }
  5761. __finally
  5762. {
  5763. if (Checklist == NULL)
  5764. {
  5765. delete AChecklist;
  5766. }
  5767. else
  5768. {
  5769. *Checklist = AChecklist;
  5770. }
  5771. FAutoOperation = false;
  5772. SAFE_DESTROY(FSynchronizeProgressForm);
  5773. BatchEnd(BatchStorage);
  5774. ReloadLocalDirectory();
  5775. if (AnyOperation)
  5776. {
  5777. OperationComplete(StartTime);
  5778. }
  5779. }
  5780. }
  5781. //---------------------------------------------------------------------------
  5782. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5783. {
  5784. // can be called from command line
  5785. return Visible &&
  5786. ((DirView(osRemote)->SelCount > 0) ||
  5787. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5788. }
  5789. //---------------------------------------------------------------------------
  5790. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5791. {
  5792. LogSynchronizeEvent(Terminal, Message);
  5793. }
  5794. //---------------------------------------------------------------------------
  5795. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5796. int Params, TSynchronizeOptions & Options)
  5797. {
  5798. DebugAssert(!IsLocalBrowserMode());
  5799. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5800. {
  5801. Options.Filter = new TStringList();
  5802. Options.Filter->CaseSensitive = false;
  5803. Options.Filter->Duplicates = Types::dupAccept;
  5804. if (DirView(osRemote)->SelCount > 0)
  5805. {
  5806. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5807. }
  5808. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5809. {
  5810. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5811. }
  5812. Options.Filter->Sort();
  5813. }
  5814. }
  5815. //---------------------------------------------------------------------------
  5816. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5817. {
  5818. TCopyParamType Defaults;
  5819. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5820. ConfigStorage->AccessMode = smRead;
  5821. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5822. {
  5823. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5824. }
  5825. ConfigStorage.reset(NULL);
  5826. std::unique_ptr<TStringList> Options(new TStringList());
  5827. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5828. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5829. UnicodeString Result;
  5830. if (Options->Count > 0)
  5831. {
  5832. Result =
  5833. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5834. }
  5835. return Result;
  5836. }
  5837. //---------------------------------------------------------------------------
  5838. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5839. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5840. {
  5841. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5842. UnicodeString AdditionalParams =
  5843. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5844. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5845. SerializeCopyParamForCommandLine(CopyParams),
  5846. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5847. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5848. ExecuteNewInstance(SessionName, AdditionalParams);
  5849. }
  5850. //---------------------------------------------------------------------------
  5851. struct TSynchronizeParams
  5852. {
  5853. UnicodeString LocalDirectory;
  5854. UnicodeString RemoteDirectory;
  5855. TSynchronizeMode Mode;
  5856. TSynchronizeChecklist * Checklist;
  5857. int Params;
  5858. TCopyParamType * CopyParam;
  5859. TDateTime CollectElapsed;
  5860. TDateTime * StartTime;
  5861. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5862. };
  5863. //---------------------------------------------------------------------------
  5864. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5865. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5866. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5867. {
  5868. DebugAssert(!FAutoOperation);
  5869. void * BatchStorage;
  5870. BatchStart(BatchStorage);
  5871. FAutoOperation = true;
  5872. TFileOperationStatistics Statistics;
  5873. TDateTime Start = Now();
  5874. try
  5875. {
  5876. Params.OnProcessedItem = OnProcessedItem;
  5877. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5878. CreateProgressForm(&SynchronizeProgress);
  5879. Terminal->SynchronizeApply(
  5880. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5881. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5882. &Statistics);
  5883. }
  5884. __finally
  5885. {
  5886. Params.OnProcessedItem = NULL;
  5887. FAutoOperation = false;
  5888. DestroyProgressForm();
  5889. BatchEnd(BatchStorage);
  5890. ReloadLocalDirectory();
  5891. }
  5892. if (WinConfiguration->SynchronizeSummary)
  5893. {
  5894. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5895. // The statistics should be 0 anyway in this case
  5896. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5897. {
  5898. Message += L"\n";
  5899. if (Statistics.FilesUploaded > 0)
  5900. {
  5901. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5902. }
  5903. if (Statistics.FilesDownloaded > 0)
  5904. {
  5905. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5906. }
  5907. if (Statistics.FilesDeletedLocal > 0)
  5908. {
  5909. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5910. }
  5911. if (Statistics.FilesDeletedRemote > 0)
  5912. {
  5913. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5914. }
  5915. }
  5916. TDateTime Elapsed = (Now() - Start);
  5917. Message +=
  5918. L"\n" +
  5919. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5920. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5921. TMessageParams Params(mpNeverAskAgainCheck);
  5922. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5923. if (Result == qaNeverAskAgain)
  5924. {
  5925. WinConfiguration->SynchronizeSummary = false;
  5926. }
  5927. }
  5928. }
  5929. //---------------------------------------------------------------------------
  5930. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5931. {
  5932. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5933. {
  5934. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5935. }
  5936. // Not set in keep-up-to-date mode - Synchronize() method
  5937. if (Token != NULL)
  5938. {
  5939. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5940. if (Params.OnProcessedItem != NULL)
  5941. {
  5942. Params.OnProcessedItem(NULL, ChecklistItem);
  5943. }
  5944. }
  5945. }
  5946. //---------------------------------------------------------------------------
  5947. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5948. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5949. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5950. {
  5951. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5952. *Params.StartTime = Now();
  5953. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5954. }
  5955. //---------------------------------------------------------------------------
  5956. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5957. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5958. {
  5959. // terminal can be already closed (e.g. dropped connection)
  5960. if (Terminal != NULL)
  5961. {
  5962. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5963. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5964. }
  5965. }
  5966. //---------------------------------------------------------------------------
  5967. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5968. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5969. {
  5970. DebugAssert(!IsLocalBrowserMode());
  5971. TAutoBatch AutoBatch(this);
  5972. TAutoFlag AutoOperationFlag(FAutoOperation);
  5973. if (Side == osRemote)
  5974. {
  5975. std::unique_ptr<TStrings> FileList(new TStringList());
  5976. FileList->AddObject(FileName, RemoteFile);
  5977. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5978. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5979. RemoteDirView->SaveSelection();
  5980. RemoteDirView->SaveSelectedNames();
  5981. try
  5982. {
  5983. Terminal->MoveFiles(FileList.get(), Target, FileMask, false);
  5984. }
  5985. catch(...)
  5986. {
  5987. RemoteDirView->DiscardSavedSelection();
  5988. throw;
  5989. }
  5990. RemoteDirView->RestoreSelection();
  5991. }
  5992. else if (DebugAlwaysTrue(Side == osLocal))
  5993. {
  5994. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5995. {
  5996. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5997. }
  5998. UnicodeString Directory = ExtractFileDir(FileName);
  5999. ReloadLocalDirectory(Directory);
  6000. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  6001. if (!SamePaths(Directory, NewDirectory))
  6002. {
  6003. ReloadLocalDirectory(NewDirectory);
  6004. }
  6005. }
  6006. }
  6007. //---------------------------------------------------------------------------
  6008. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  6009. {
  6010. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  6011. if (Side == osLocal)
  6012. {
  6013. if (Action == TSynchronizeChecklist::saDownloadNew)
  6014. {
  6015. OpenFolderInExplorer(LocalPath);
  6016. }
  6017. else
  6018. {
  6019. OpenFileInExplorer(CombinePaths(LocalPath, Item->GetFileName()));
  6020. }
  6021. }
  6022. else if (DebugAlwaysTrue(Side == osRemote))
  6023. {
  6024. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6025. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6026. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6027. if (!LocalPath.IsEmpty())
  6028. {
  6029. SessionData->LocalDirectory = LocalPath;
  6030. }
  6031. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6032. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  6033. }
  6034. }
  6035. //---------------------------------------------------------------------------
  6036. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6037. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6038. const TCopyParamType * CopyParams)
  6039. {
  6040. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6041. UnicodeString AdditionalParams =
  6042. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6043. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6044. SerializeCopyParamForCommandLine(CopyParams),
  6045. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6046. LocalDirectory, RemoteDirectory, Mode, Params));
  6047. ExecuteNewInstance(SessionName, AdditionalParams);
  6048. }
  6049. //---------------------------------------------------------------------------
  6050. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6051. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6052. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6053. {
  6054. int Result;
  6055. bool SaveSettings = false;
  6056. int Options =
  6057. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6058. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6059. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6060. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6061. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6062. bool Continue =
  6063. ((UseDefaults == 0) ||
  6064. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6065. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6066. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6067. if (Continue)
  6068. {
  6069. Configuration->Usage->Inc(L"Synchronizations");
  6070. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6071. UpdateCopyParamCounters(CopyParam);
  6072. TSynchronizeOptions SynchronizeOptions;
  6073. GetSynchronizeOptions(Params, SynchronizeOptions);
  6074. if (SaveSettings)
  6075. {
  6076. GUIConfiguration->SynchronizeParams = Params;
  6077. }
  6078. else
  6079. {
  6080. SaveMode = false;
  6081. }
  6082. TDateTime StartTime = Now();
  6083. TSynchronizeChecklist * Checklist = NULL;
  6084. try
  6085. {
  6086. DebugAssert(!FAutoOperation);
  6087. FAutoOperation = true;
  6088. try
  6089. {
  6090. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6091. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6092. int Files = -1;
  6093. if (DataList->Count >= 1)
  6094. {
  6095. Files = StrToIntDef(DataList->Strings[0], Files);
  6096. }
  6097. else
  6098. {
  6099. DataList->Add(UnicodeString());
  6100. }
  6101. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6102. FSynchronizeProgressForm->Start();
  6103. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6104. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6105. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6106. &SynchronizeOptions);
  6107. if (Terminal->SessionData->CacheDirectories)
  6108. {
  6109. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6110. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6111. }
  6112. }
  6113. __finally
  6114. {
  6115. FAutoOperation = false;
  6116. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6117. SAFE_DESTROY(FSynchronizeProgressForm);
  6118. }
  6119. TSynchronizeParams SynchronizeParams;
  6120. SynchronizeParams.LocalDirectory = LocalDirectory;
  6121. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6122. SynchronizeParams.Mode = Mode;
  6123. SynchronizeParams.CopyParam = &CopyParam;
  6124. SynchronizeParams.Params = Params;
  6125. SynchronizeParams.Checklist = Checklist;
  6126. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6127. SynchronizeParams.StartTime = &StartTime;
  6128. SynchronizeParams.OnProcessedItem = NULL;
  6129. Result = Checklist->Count;
  6130. if (Checklist->Count > 0)
  6131. {
  6132. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6133. {
  6134. if (!DoSynchronizeChecklistDialog(
  6135. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6136. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  6137. {
  6138. Result = -1;
  6139. }
  6140. }
  6141. else
  6142. {
  6143. FullSynchronize(SynchronizeParams, NULL, NULL);
  6144. }
  6145. }
  6146. else
  6147. {
  6148. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6149. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6150. }
  6151. }
  6152. __finally
  6153. {
  6154. delete Checklist;
  6155. }
  6156. OperationComplete(StartTime);
  6157. }
  6158. else
  6159. {
  6160. Result = -1;
  6161. }
  6162. return Result;
  6163. }
  6164. //---------------------------------------------------------------------------
  6165. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6166. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6167. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6168. {
  6169. if (Collect)
  6170. {
  6171. DebugAssert(FSynchronizeProgressForm != NULL);
  6172. if (!FSynchronizeProgressForm->Started)
  6173. {
  6174. FSynchronizeProgressForm->Start();
  6175. }
  6176. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6177. SetTaskbarListProgressValue(CompareProgress);
  6178. }
  6179. else
  6180. {
  6181. DebugAssert(FSynchronizeProgressForm == NULL);
  6182. DebugAssert(FProgressForm != NULL);
  6183. }
  6184. }
  6185. //---------------------------------------------------------------------------
  6186. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6187. {
  6188. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6189. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6190. if (File.get() != NULL)
  6191. {
  6192. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6193. Application->ShowMainForm = false;
  6194. Application->Run();
  6195. }
  6196. }
  6197. //---------------------------------------------------------------------------
  6198. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6199. {
  6200. DebugFail();
  6201. }
  6202. //---------------------------------------------------------------------------
  6203. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6204. {
  6205. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6206. SessionData->Assign(ManagedSession->SessionData);
  6207. UpdateSessionData(SessionData.get());
  6208. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6209. if (IsActiveTerminal(ManagedSession))
  6210. {
  6211. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6212. }
  6213. if (!ManagedSession->SessionData->HasSessionName())
  6214. {
  6215. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6216. // once IsWorkspace is cleared
  6217. SessionData->Name = UnicodeString();
  6218. }
  6219. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6220. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6221. SessionData->IsWorkspace = false;
  6222. return SessionData.release();
  6223. }
  6224. //---------------------------------------------------------------------------
  6225. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6226. {
  6227. TSessionData * SessionData = CloneCurrentSessionData();
  6228. try
  6229. {
  6230. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6231. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6232. }
  6233. __finally
  6234. {
  6235. delete SessionData;
  6236. }
  6237. }
  6238. //---------------------------------------------------------------------------
  6239. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6240. {
  6241. TTerminalManager * Manager = TTerminalManager::Instance();
  6242. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6243. if (DebugAlwaysTrue(ManagedSession != NULL))
  6244. {
  6245. // Update ManagedSession->StateData
  6246. UpdateSession(ManagedSession);
  6247. }
  6248. Manager->SaveWorkspace(DataList.get());
  6249. return DataList.release();
  6250. }
  6251. //---------------------------------------------------------------------------
  6252. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6253. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6254. {
  6255. WinConfiguration->LastWorkspace = Name;
  6256. if (!SavePasswords)
  6257. {
  6258. for (int Index = 0; Index < DataList->Count; Index++)
  6259. {
  6260. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6261. if (SessionData->Link.IsEmpty())
  6262. {
  6263. SessionData->ClearSessionPasswords();
  6264. }
  6265. }
  6266. }
  6267. StoredSessions->NewWorkspace(Name, DataList);
  6268. // modified only
  6269. StoredSessions->Save(false, Explicit);
  6270. }
  6271. //---------------------------------------------------------------------------
  6272. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6273. {
  6274. return
  6275. DefaultStr(WinConfiguration->LastWorkspace,
  6276. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6277. }
  6278. //---------------------------------------------------------------------------
  6279. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6280. {
  6281. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6282. bool AnyNonStoredSessionWithPassword = false;
  6283. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6284. bool AllNonStoredSessionsAnonymous = true;
  6285. TTerminalManager * Manager = TTerminalManager::Instance();
  6286. for (int Index = 0; Index < DataList->Count; Index++)
  6287. {
  6288. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6289. if (SessionData->Link.IsEmpty())
  6290. {
  6291. if (SessionData->HasAnySessionPassword())
  6292. {
  6293. AnyNonStoredSessionWithPassword = true;
  6294. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6295. {
  6296. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6297. }
  6298. }
  6299. if (!SameText(SessionData->UserName, AnonymousUserName))
  6300. {
  6301. AllNonStoredSessionsAnonymous = false;
  6302. }
  6303. }
  6304. }
  6305. bool SavePasswords;
  6306. bool * PSavePasswords;
  6307. bool NotRecommendedSavingPasswords =
  6308. !CustomWinConfiguration->UseMasterPassword &&
  6309. !AllNonStoredSessionsAnonymous;
  6310. if (Configuration->DisablePasswordStoring ||
  6311. !AnyNonStoredSessionWithPassword)
  6312. {
  6313. PSavePasswords = NULL;
  6314. SavePasswords = false;
  6315. }
  6316. else
  6317. {
  6318. PSavePasswords = &SavePasswords;
  6319. SavePasswords =
  6320. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6321. !NotRecommendedSavingPasswords;
  6322. }
  6323. UnicodeString Name = WorkspaceName();
  6324. bool CreateShortcut = false;
  6325. bool Result =
  6326. DoSaveWorkspaceDialog(
  6327. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6328. EnableAutoSave);
  6329. if (Result)
  6330. {
  6331. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6332. if (CreateShortcut)
  6333. {
  6334. TOperationVisualizer Visualizer;
  6335. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6336. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6337. }
  6338. if (EnableAutoSave)
  6339. {
  6340. WinConfiguration->AutoSaveWorkspace = true;
  6341. WinConfiguration->AutoWorkspace = Name;
  6342. if (PSavePasswords != NULL)
  6343. {
  6344. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6345. }
  6346. }
  6347. }
  6348. return Result;
  6349. }
  6350. //---------------------------------------------------------------------------
  6351. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6352. {
  6353. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6354. DebugAssert(Session == ManagedSession);
  6355. if (!IsLocalBrowserMode())
  6356. {
  6357. SAFE_DESTROY(Session->RemoteExplorerState);
  6358. if (WinConfiguration->PreservePanelState)
  6359. {
  6360. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6361. }
  6362. }
  6363. UpdateSessionData(Session->StateData);
  6364. }
  6365. //---------------------------------------------------------------------------
  6366. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6367. {
  6368. // Keep in sync with TSessionData::CopyStateData
  6369. DebugAssert(Data != NULL);
  6370. // This is inconsistent with how color (for example) is handled.
  6371. Data->Name = ManagedSession->SessionData->Name;
  6372. if (!IsLocalBrowserMode())
  6373. {
  6374. // cannot use RemoteDirView->Path, because it is empty if connection
  6375. // was already closed
  6376. // also only peek, we may not be connected at all atm
  6377. // so make sure we do not try retrieving current directory from the server
  6378. // (particularly with FTP)
  6379. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6380. if (!ACurrentDirectory.IsEmpty())
  6381. {
  6382. Data->RemoteDirectory = ACurrentDirectory;
  6383. }
  6384. }
  6385. Data->Color = SessionColor;
  6386. }
  6387. //---------------------------------------------------------------------------
  6388. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6389. {
  6390. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6391. DebugAssert(Toolbar != NULL);
  6392. for (int i = 0; i < Toolbar->Items->Count; i++)
  6393. {
  6394. TTBXCustomDropDownItem * DropDownItem;
  6395. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6396. if (DropDownItem != NULL)
  6397. {
  6398. ToolbarItemResize(DropDownItem,
  6399. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6400. Toolbar->NonClientWidth);
  6401. break;
  6402. }
  6403. }
  6404. }
  6405. //---------------------------------------------------------------------------
  6406. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6407. {
  6408. Item->EditWidth = Width;
  6409. }
  6410. //---------------------------------------------------------------------------
  6411. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6412. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6413. {
  6414. for (int i = 0; i < Toolbar->Items->Count; i++)
  6415. {
  6416. TTBXCustomDropDownItem * DropDownItem;
  6417. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6418. if (DropDownItem != NULL)
  6419. {
  6420. ASize.x -= DropDownItem->EditWidth;
  6421. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6422. }
  6423. }
  6424. }
  6425. //---------------------------------------------------------------------------
  6426. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6427. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6428. {
  6429. if (WinConfiguration->DDWarnLackOfTempSpace)
  6430. {
  6431. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6432. if (!ADrive.IsEmpty())
  6433. {
  6434. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6435. DebugAssert(RequiredSpace >= 0);
  6436. __int64 RequiredWithReserve;
  6437. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6438. if (FreeSpace < RequiredWithReserve)
  6439. {
  6440. unsigned int Result;
  6441. TMessageParams Params(mpNeverAskAgainCheck);
  6442. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6443. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6444. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6445. if (Result == qaNeverAskAgain)
  6446. {
  6447. WinConfiguration->DDWarnLackOfTempSpace = false;
  6448. }
  6449. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6450. }
  6451. }
  6452. }
  6453. }
  6454. //---------------------------------------------------------------------------
  6455. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6456. {
  6457. DoOpenDirectoryDialog(odAddBookmark, Side);
  6458. }
  6459. //---------------------------------------------------------------------------
  6460. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6461. {
  6462. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6463. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6464. try
  6465. {
  6466. TCustomDirView * DView = DirView(Side);
  6467. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6468. {
  6469. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6470. }
  6471. }
  6472. catch (...)
  6473. {
  6474. delete VisitedDirectories;
  6475. throw;
  6476. }
  6477. return VisitedDirectories;
  6478. }
  6479. //---------------------------------------------------------------------------
  6480. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6481. TOpenDirectoryMode Mode, TOperationSide Side)
  6482. {
  6483. bool Continue = true;
  6484. if (Mode == odAddBookmark)
  6485. {
  6486. TMessageParams Params(mpNeverAskAgainCheck);
  6487. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6488. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6489. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6490. unsigned int Answer =
  6491. MessageDialog(Message,
  6492. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6493. if (Answer == qaNeverAskAgain)
  6494. {
  6495. Continue = true;
  6496. WinConfiguration->UseSharedBookmarks = true;
  6497. }
  6498. else if (Answer == qaOK)
  6499. {
  6500. Continue = true;
  6501. WinConfiguration->UseSharedBookmarks = false;
  6502. }
  6503. else
  6504. {
  6505. Continue = false;
  6506. }
  6507. }
  6508. if (Continue)
  6509. {
  6510. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6511. try
  6512. {
  6513. UnicodeString Name = DirView(Side)->PathName;
  6514. bool Repeat;
  6515. do
  6516. {
  6517. Repeat = false;
  6518. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6519. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6520. // do not allow switching to location profiles,
  6521. // if we are not connected
  6522. HasDirView[osLocal] && (Terminal != NULL)))
  6523. {
  6524. TWindowLock Lock(this);
  6525. if (!TryOpenDirectory(Side, Name))
  6526. {
  6527. Repeat = true;
  6528. Mode = odBrowse;
  6529. }
  6530. }
  6531. }
  6532. while (Repeat);
  6533. }
  6534. __finally
  6535. {
  6536. delete VisitedDirectories;
  6537. }
  6538. }
  6539. }
  6540. //---------------------------------------------------------------------------
  6541. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6542. {
  6543. DebugAssert(!Terminal->CommandSessionOpened);
  6544. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6545. }
  6546. //---------------------------------------------------------------------------
  6547. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6548. {
  6549. bool Result = Terminal->IsCapable[Capability] ||
  6550. Terminal->CommandSessionOpened;
  6551. if (!Result)
  6552. {
  6553. // We might get here for example when "checksum" synchronization is requested from command-line
  6554. // on server that supports neither checksum nor shell
  6555. if (!Terminal->IsCapable[fcSecondaryShell])
  6556. {
  6557. NotSupported();
  6558. }
  6559. else if (!GUIConfiguration->ConfirmCommandSession)
  6560. {
  6561. Result = true;
  6562. }
  6563. else
  6564. {
  6565. TMessageParams Params(mpNeverAskAgainCheck);
  6566. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6567. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6568. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6569. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6570. if (Answer == qaNeverAskAgain)
  6571. {
  6572. GUIConfiguration->ConfirmCommandSession = false;
  6573. Result = true;
  6574. }
  6575. else if (Answer == qaOK)
  6576. {
  6577. Result = true;
  6578. }
  6579. }
  6580. if (Result)
  6581. {
  6582. Result = CommandSessionFallback();
  6583. }
  6584. }
  6585. return Result;
  6586. }
  6587. //---------------------------------------------------------------------------
  6588. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6589. {
  6590. if (EnsureCommandSessionFallback(fcAnyCommand))
  6591. {
  6592. DoConsoleDialog(Terminal, Command);
  6593. }
  6594. }
  6595. //---------------------------------------------------------------------------
  6596. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6597. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6598. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6599. {
  6600. if (!IsSideLocalBrowser(osRemote) &&
  6601. IsFileControl(DropSourceControl, osRemote) &&
  6602. (FDDExtMapFile != NULL))
  6603. {
  6604. Accept = true;
  6605. }
  6606. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6607. DebugAssert(FDDTargetControl != NULL);
  6608. }
  6609. //---------------------------------------------------------------------------
  6610. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6611. _di_IDataObject DataObj, int KeyState,
  6612. const TPoint & Point, int & Effect, bool & Accept)
  6613. {
  6614. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6615. }
  6616. //---------------------------------------------------------------------------
  6617. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6618. _di_IDataObject DataObj, int KeyState,
  6619. const TPoint & Point, int & Effect, bool & Accept)
  6620. {
  6621. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6622. }
  6623. //---------------------------------------------------------------------------
  6624. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6625. TObject * Sender)
  6626. {
  6627. DebugUsedParam(Sender);
  6628. DebugAssert(FDDTargetControl == Sender);
  6629. FDDTargetControl = NULL;
  6630. }
  6631. //---------------------------------------------------------------------------
  6632. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6633. {
  6634. FileControlDDDragLeave(SessionsPageControl);
  6635. }
  6636. //---------------------------------------------------------------------------
  6637. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6638. {
  6639. FileControlDDDragLeave(QueueView3);
  6640. }
  6641. //---------------------------------------------------------------------------
  6642. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6643. {
  6644. DebugAssert(!IsSideLocalBrowser(Side));
  6645. DebugUsedParam(Side);
  6646. bool Edit = false;
  6647. TRemoteFile * File = NULL;
  6648. UnicodeString FileName;
  6649. UnicodeString PointTo;
  6650. bool SymbolicLink = true;
  6651. if (RemoteDirView->ItemFocused)
  6652. {
  6653. DebugAssert(RemoteDirView->ItemFocused->Data);
  6654. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6655. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6656. if (Edit)
  6657. {
  6658. FileName = File->FileName;
  6659. PointTo = File->LinkTo;
  6660. }
  6661. else if (!File->IsParentDirectory)
  6662. {
  6663. PointTo = File->FileName;
  6664. }
  6665. }
  6666. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6667. Terminal->IsCapable[fcHardLink]))
  6668. {
  6669. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6670. if (Edit)
  6671. {
  6672. DebugAssert(File->FileName == FileName);
  6673. int Params = dfNoRecursive;
  6674. Terminal->ExceptionOnFail = true;
  6675. try
  6676. {
  6677. Terminal->DeleteFile(L"", File, &Params);
  6678. }
  6679. __finally
  6680. {
  6681. Terminal->ExceptionOnFail = false;
  6682. }
  6683. }
  6684. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6685. }
  6686. }
  6687. //---------------------------------------------------------------------------
  6688. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6689. {
  6690. return
  6691. (IsSideLocalBrowser(Side) ||
  6692. (HasActiveTerminal() &&
  6693. Terminal->ResolvingSymlinks &&
  6694. Terminal->IsCapable[fcSymbolicLink]));
  6695. }
  6696. //---------------------------------------------------------------------------
  6697. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6698. {
  6699. return
  6700. !IsSideLocalBrowser(FCurrentSide) &&
  6701. (RemoteDirView->ItemFocused != NULL) &&
  6702. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6703. Terminal->SessionData->ResolveSymlinks;
  6704. }
  6705. //---------------------------------------------------------------------------
  6706. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6707. {
  6708. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6709. FForceExecution = true;
  6710. try
  6711. {
  6712. DirView(osCurrent)->ExecuteCurrentFile();
  6713. }
  6714. __finally
  6715. {
  6716. FForceExecution = false;
  6717. }
  6718. }
  6719. //---------------------------------------------------------------------------
  6720. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6721. {
  6722. TEditorData ExternalEditor;
  6723. ExternalEditor.Editor = edExternal;
  6724. bool Remember = false;
  6725. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6726. {
  6727. if (Remember)
  6728. {
  6729. TEditorList * EditorList = new TEditorList;
  6730. try
  6731. {
  6732. *EditorList = *WinConfiguration->EditorList;
  6733. bool Found = false;
  6734. int i = 0;
  6735. while (!Found && (i < EditorList->Count))
  6736. {
  6737. const TEditorPreferences * Editor = EditorList->Editors[i];
  6738. if ((Editor->Data->Editor == edExternal) &&
  6739. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6740. {
  6741. Found = true;
  6742. }
  6743. i++;
  6744. }
  6745. if (!Found)
  6746. {
  6747. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6748. WinConfiguration->EditorList = EditorList;
  6749. }
  6750. }
  6751. __finally
  6752. {
  6753. delete EditorList;
  6754. }
  6755. }
  6756. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6757. }
  6758. }
  6759. //---------------------------------------------------------------------------
  6760. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6761. {
  6762. if (FFileFindTerminal == ATerminal)
  6763. {
  6764. FFileFindTerminal = NULL;
  6765. HideFileFindDialog();
  6766. }
  6767. if (FClipboardTerminal == ATerminal)
  6768. {
  6769. ClipboardClear(); // implies ClipboardStop
  6770. }
  6771. if ((FOnSynchronizeAbort != NULL) &&
  6772. (ATerminal == FManagedSession))
  6773. {
  6774. FOnSynchronizeAbort(NULL);
  6775. }
  6776. }
  6777. //---------------------------------------------------------------------------
  6778. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6779. {
  6780. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6781. DetachTerminal(Sender);
  6782. }
  6783. //---------------------------------------------------------------------------
  6784. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6785. const UnicodeString FileName, TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6786. {
  6787. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6788. if (Data->Terminal == Terminal)
  6789. {
  6790. Data->Terminal = ATerminal;
  6791. }
  6792. }
  6793. //---------------------------------------------------------------------------
  6794. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6795. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6796. {
  6797. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6798. DebugAssert(Terminal != NULL);
  6799. if (Data->Terminal == Terminal)
  6800. {
  6801. Data->Terminal = NULL;
  6802. }
  6803. }
  6804. //---------------------------------------------------------------------------
  6805. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6806. {
  6807. return NULL;
  6808. }
  6809. //---------------------------------------------------------------------------
  6810. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6811. {
  6812. UpdateControls();
  6813. SessionColor = TColor(0);
  6814. UpdateRemotePathComboBox(false);
  6815. NeedSession(false);
  6816. }
  6817. //---------------------------------------------------------------------------
  6818. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6819. {
  6820. try
  6821. {
  6822. // Cache, as the login dialog can change its value.
  6823. // See also DoShow. Also see TTerminalManager::NewSession.
  6824. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6825. try
  6826. {
  6827. if (ShowLogin)
  6828. {
  6829. bool ReloadSessions = !Startup;
  6830. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6831. }
  6832. }
  6833. __finally
  6834. {
  6835. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6836. // (so there was no chance for the user to open any session yet)
  6837. if ((ShowLogin || !Startup) &&
  6838. !WinConfiguration->KeepOpenWhenNoSession &&
  6839. // this rules out the implicit Commander's local-local browser
  6840. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6841. {
  6842. TerminateApplication();
  6843. }
  6844. }
  6845. }
  6846. catch (EAbort &)
  6847. {
  6848. // swallow
  6849. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6850. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6851. }
  6852. }
  6853. //---------------------------------------------------------------------------
  6854. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6855. {
  6856. TTerminalManager * Manager = TTerminalManager::Instance();
  6857. DebugAssert(!Manager->Updating);
  6858. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6859. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6860. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6861. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6862. try
  6863. {
  6864. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6865. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6866. {
  6867. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6868. }
  6869. for (int Index = 0; Index <= Manager->Count; Index++)
  6870. {
  6871. TThemeTabSheet * TabSheet;
  6872. if (Index >= SessionsPageControl->PageCount)
  6873. {
  6874. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6875. TabSheet->PageControl = SessionsPageControl;
  6876. }
  6877. else
  6878. {
  6879. TabSheet = SessionsPageControl->Pages[Index];
  6880. }
  6881. bool IsSessionTab = (Index < Manager->Count);
  6882. if (IsSessionTab)
  6883. {
  6884. TTerminal * Terminal = Manager->Sessions[Index];
  6885. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6886. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  6887. UpdateSessionTab(TabSheet);
  6888. }
  6889. else
  6890. {
  6891. TabSheet->Tag = 0; // not really needed
  6892. TabSheet->Shadowed = false;
  6893. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6894. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  6895. // 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)
  6896. UpdateNewTabTab();
  6897. }
  6898. }
  6899. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6900. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6901. {
  6902. SessionsPageControl->UpdateTabsCaptionTruncation();
  6903. }
  6904. }
  6905. __finally
  6906. {
  6907. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6908. }
  6909. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6910. }
  6911. //---------------------------------------------------------------------------
  6912. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  6913. {
  6914. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  6915. }
  6916. //---------------------------------------------------------------------------
  6917. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6918. {
  6919. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6920. }
  6921. //---------------------------------------------------------------------------
  6922. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  6923. {
  6924. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6925. }
  6926. //---------------------------------------------------------------------------
  6927. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6928. {
  6929. TThemeTabSheet * TabSheet = GetNewTabTab();
  6930. UnicodeString TabCaption;
  6931. if (WinConfiguration->SelectiveToolbarText)
  6932. {
  6933. TabCaption = GetNewTabTabCaption();
  6934. }
  6935. TabSheet->BaseCaption = TabCaption;
  6936. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6937. }
  6938. //---------------------------------------------------------------------------
  6939. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6940. {
  6941. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6942. }
  6943. //---------------------------------------------------------------------------
  6944. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6945. {
  6946. DebugFail();
  6947. return UnicodeString();
  6948. }
  6949. //---------------------------------------------------------------------------
  6950. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6951. {
  6952. if (DebugAlwaysTrue(TabSheet != NULL))
  6953. {
  6954. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6955. if (DebugAlwaysTrue(ASession != NULL))
  6956. {
  6957. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6958. if (ASession->LocalBrowser)
  6959. {
  6960. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6961. }
  6962. else
  6963. {
  6964. TabSheet->ImageIndex = AddSessionColor(Color);
  6965. }
  6966. TTerminalManager * Manager = TTerminalManager::Instance();
  6967. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6968. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6969. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6970. }
  6971. }
  6972. }
  6973. //---------------------------------------------------------------------------
  6974. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6975. {
  6976. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6977. }
  6978. //---------------------------------------------------------------------------
  6979. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6980. {
  6981. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6982. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6983. bool Result = (Session != NULL);
  6984. if (Result)
  6985. {
  6986. TTerminalManager::Instance()->ActiveSession = Session;
  6987. }
  6988. else
  6989. {
  6990. try
  6991. {
  6992. NewTab();
  6993. }
  6994. __finally
  6995. {
  6996. SessionListChanged();
  6997. }
  6998. FSessionsPageControlNewTabTime = Now();
  6999. }
  7000. return Result;
  7001. }
  7002. //---------------------------------------------------------------------------
  7003. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  7004. {
  7005. TWindowLock Lock(this);
  7006. SessionTabSwitched();
  7007. }
  7008. //---------------------------------------------------------------------------
  7009. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  7010. {
  7011. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  7012. DebugAssert(TransferList != NULL);
  7013. UnicodeString Name;
  7014. if (TransferList->ItemIndex <= 0)
  7015. {
  7016. Name = L"";
  7017. }
  7018. else
  7019. {
  7020. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7021. }
  7022. if (FCopyParamAutoSelected.IsEmpty())
  7023. {
  7024. // if previous preset was not autoselected, make new preset the "default"
  7025. FCopyParamDefault = Name;
  7026. }
  7027. GUIConfiguration->CopyParamCurrent = Name;
  7028. }
  7029. //---------------------------------------------------------------------------
  7030. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7031. {
  7032. // sanity check
  7033. bool ExistingPreset =
  7034. (FTransferListHoverIndex >= 0) &&
  7035. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7036. DebugAssert(ExistingPreset);
  7037. if (ExistingPreset)
  7038. {
  7039. HDC DC = GetDC(0);
  7040. TCanvas * Canvas = new TCanvas();
  7041. try
  7042. {
  7043. Canvas->Handle = DC;
  7044. Canvas->Font = GetToolbarFont(this);
  7045. UnicodeString Name;
  7046. if (FTransferListHoverIndex == 0)
  7047. {
  7048. Name = L"";
  7049. }
  7050. else
  7051. {
  7052. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7053. }
  7054. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7055. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7056. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7057. static_cast<TObject*>(GetComponent(fcTransferList)));
  7058. UnicodeString InfoStr =
  7059. GUIConfiguration->CopyParamPreset[Name].
  7060. GetInfoStr(L"; ",
  7061. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7062. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7063. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7064. {
  7065. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7066. {
  7067. InfoStr.SetLength(InfoStr.Length() - 1);
  7068. }
  7069. InfoStr += Ellipsis;
  7070. }
  7071. // UpdateCaption does not cause invalidation of whole submenu, while
  7072. // setting Caption property does.
  7073. // also it probably does not resize the label, even if necessary
  7074. // (we do not want that anyway)
  7075. TransferLabel->UpdateCaption(InfoStr);
  7076. }
  7077. __finally
  7078. {
  7079. Canvas->Handle = NULL;
  7080. ReleaseDC(0, DC);
  7081. delete Canvas;
  7082. }
  7083. }
  7084. }
  7085. //---------------------------------------------------------------------------
  7086. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7087. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7088. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7089. {
  7090. if (FTransferListHoverIndex != AHoverIndex)
  7091. {
  7092. FTransferListHoverIndex = AHoverIndex;
  7093. UpdateTransferLabel();
  7094. }
  7095. }
  7096. //---------------------------------------------------------------------------
  7097. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7098. {
  7099. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7100. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7101. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7102. {
  7103. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7104. {
  7105. if (!NonVisualDataModule->Busy)
  7106. {
  7107. OpenDirectory(GetSide(osCurrent));
  7108. }
  7109. Message.Result = 1;
  7110. }
  7111. else
  7112. {
  7113. TForm::Dispatch(&Message);
  7114. }
  7115. }
  7116. else
  7117. {
  7118. TForm::Dispatch(&Message);
  7119. }
  7120. }
  7121. //---------------------------------------------------------------------------
  7122. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7123. {
  7124. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7125. if ((FIgnoreNextDialogChar != 0) &&
  7126. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7127. {
  7128. Message.Result = 1;
  7129. }
  7130. else
  7131. {
  7132. TForm::Dispatch(&Message);
  7133. }
  7134. FIgnoreNextDialogChar = 0;
  7135. }
  7136. //---------------------------------------------------------------------------
  7137. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7138. {
  7139. // The four low-order bits are used internally by Windows
  7140. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7141. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7142. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7143. // 61730 - restore thru double click - undocumented
  7144. // 61490 - maximize thru double click - undocumented
  7145. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7146. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7147. {
  7148. SysResizing(Cmd);
  7149. }
  7150. TForm::Dispatch(&Message);
  7151. }
  7152. //---------------------------------------------------------------------------
  7153. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7154. {
  7155. AppLog(L"Windows session end query");
  7156. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7157. // Also there no point returning TRUE as we are not able to
  7158. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7159. // Hence the process termination might be safer :)
  7160. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7161. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7162. {
  7163. Message.Result = FALSE;
  7164. }
  7165. else
  7166. {
  7167. Message.Result = TRUE;
  7168. }
  7169. // Do not call default handling as that triggers OnCloseQuery,
  7170. // where our implementation will popup confirmation dialogs, what we do not want,
  7171. // as per Vista guidelines:
  7172. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7173. }
  7174. //---------------------------------------------------------------------------
  7175. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7176. {
  7177. AppLog(L"Windows session end");
  7178. if (Message.EndSession && IsApplicationMinimized())
  7179. {
  7180. // WORKAROUND
  7181. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7182. // when it receives WM_ENDSESSION,
  7183. // but that sometimes (particularly when application is minimized) cause crashes.
  7184. // Crash popups message that blocks log off.
  7185. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7186. // so we call ExitProcess() immediately, not even trying to cleanup.
  7187. // It still causes beep, so there's likely some popup, but it does not block
  7188. // log off.
  7189. ExitProcess(0);
  7190. }
  7191. TForm::Dispatch(&Message);
  7192. }
  7193. #ifdef _DEBUG
  7194. //---------------------------------------------------------------------------
  7195. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7196. {
  7197. TForm::Dispatch(&Message);
  7198. }
  7199. #endif
  7200. //---------------------------------------------------------------------------
  7201. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7202. {
  7203. }
  7204. //---------------------------------------------------------------------------
  7205. void __fastcall TCustomScpExplorerForm::DoShow()
  7206. {
  7207. // Called from TCustomScpExplorerForm::CMShowingChanged
  7208. // only now are the controls resized finally, so the size constraints
  7209. // will not conflict with possibly very small window size
  7210. RestoreFormParams();
  7211. // This indicates that the form was rescaled after parameters were loaded and
  7212. // as most probably the parameters were actually saved with the current form scaling
  7213. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7214. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7215. // and no rounding problems will occur.
  7216. // See also RestoreForm.
  7217. // (we should be safe to call RestoreParams unconditionally)
  7218. if (PixelsPerInch != Screen->PixelsPerInch)
  7219. {
  7220. RestoreParams();
  7221. }
  7222. FixControlsPlacement();
  7223. if (Position == poDefaultPosOnly)
  7224. {
  7225. CutFormToDesktop(this);
  7226. }
  7227. TForm::DoShow();
  7228. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7229. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7230. // This was previously in NeedSession, where other related code is.
  7231. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7232. // unpleasantly shows briefly.
  7233. if ((ManagedSession == NULL) &&
  7234. !WinConfiguration->ShowLoginWhenNoSession &&
  7235. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7236. // This detects if workspace was saved the last time the main widow was closed
  7237. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7238. {
  7239. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7240. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7241. }
  7242. // Before main window displays
  7243. if (ManagedSession == NULL)
  7244. {
  7245. StartingWithoutSession();
  7246. }
  7247. UpdatePixelsPerInchMainWindowCounter();
  7248. FShowing = true;
  7249. }
  7250. //---------------------------------------------------------------------------
  7251. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7252. {
  7253. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7254. }
  7255. //---------------------------------------------------------------------------
  7256. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7257. {
  7258. SessionListChanged();
  7259. InitStatusBar();
  7260. UpdateControls();
  7261. }
  7262. //---------------------------------------------------------------------------
  7263. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7264. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7265. TNotifyEvent OnBalloonClick, TObject * UserData)
  7266. {
  7267. bool Do;
  7268. UnicodeString Message;
  7269. if (E == NULL)
  7270. {
  7271. Message = Str;
  7272. Do = true;
  7273. }
  7274. else
  7275. {
  7276. Do = ExceptionMessage(E, Message);
  7277. }
  7278. if (Do && WinConfiguration->BalloonNotifications)
  7279. {
  7280. UnicodeString Title;
  7281. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7282. {
  7283. Message = TrimLeft(Message);
  7284. }
  7285. else
  7286. {
  7287. Message = UnformatMessage(Message);
  7288. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7289. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7290. Title = LoadResourceString(Captions[Type]);
  7291. if (Terminal != NULL)
  7292. {
  7293. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7294. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7295. }
  7296. }
  7297. if (Seconds == 0)
  7298. {
  7299. Seconds = WinConfiguration->NotificationsTimeout;
  7300. }
  7301. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7302. }
  7303. }
  7304. //---------------------------------------------------------------------------
  7305. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7306. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7307. UnicodeString HelpKeyword, const TMessageParams * Params,
  7308. TTerminal * Terminal)
  7309. {
  7310. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7311. (FOnFeedSynchronizeError != NULL)) &&
  7312. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7313. {
  7314. if (FOnFeedSynchronizeError != NULL)
  7315. {
  7316. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7317. }
  7318. else
  7319. {
  7320. DebugAssert(FErrorList != NULL);
  7321. TStringList * MoreMessagesCopy = NULL;
  7322. if (MoreMessages)
  7323. {
  7324. MoreMessagesCopy = new TStringList();
  7325. MoreMessagesCopy->Assign(MoreMessages);
  7326. }
  7327. FErrorList->AddObject(Message, MoreMessagesCopy);
  7328. }
  7329. PopupTrayBalloon(Terminal, Message, Type);
  7330. return ContinueAnswer(Answers);
  7331. }
  7332. else
  7333. {
  7334. bool UseBalloon = FTrayIcon->Visible;
  7335. if (UseBalloon)
  7336. {
  7337. PopupTrayBalloon(Terminal, Message, Type);
  7338. }
  7339. unsigned int Result;
  7340. try
  7341. {
  7342. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7343. }
  7344. __finally
  7345. {
  7346. // cancel only balloon we popped up, otherwise we may cancel notification
  7347. // balloon that was there before the message dialog
  7348. // (such as "dd confirmation opt in balloon)
  7349. if (UseBalloon)
  7350. {
  7351. FTrayIcon->CancelBalloon();
  7352. }
  7353. }
  7354. return Result;
  7355. }
  7356. }
  7357. //---------------------------------------------------------------------------
  7358. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7359. TTerminal * Terminal, Exception * E)
  7360. {
  7361. if (FTrayIcon->Visible)
  7362. {
  7363. PopupTrayBalloon(Terminal, L"", qtError, E);
  7364. }
  7365. // particularly prevent opening new session from jump list,
  7366. // while exception is shown
  7367. NonVisualDataModule->StartBusy();
  7368. try
  7369. {
  7370. ShowExtendedExceptionEx(Terminal, E);
  7371. }
  7372. __finally
  7373. {
  7374. NonVisualDataModule->EndBusy();
  7375. FTrayIcon->CancelBalloon();
  7376. }
  7377. }
  7378. //---------------------------------------------------------------------------
  7379. void __fastcall TCustomScpExplorerForm::SessionReady()
  7380. {
  7381. InitStatusBar();
  7382. // cannot rely on active page being page for active terminal,
  7383. // as it can happen that active page is the "new session" page
  7384. // (e.g. when reconnecting active terminal, while login dialog
  7385. // invoked from "new session" page is modal)
  7386. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7387. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7388. }
  7389. //---------------------------------------------------------------------------
  7390. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7391. TTerminal * Terminal, Exception * E)
  7392. {
  7393. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7394. if (!Terminal->Active)
  7395. {
  7396. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7397. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7398. {
  7399. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7400. }
  7401. }
  7402. }
  7403. //---------------------------------------------------------------------------
  7404. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7405. UnicodeString Message, TQueryType Type,
  7406. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7407. {
  7408. if ((E == NULL) ||
  7409. ExceptionMessage(E, Message))
  7410. {
  7411. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7412. if (Important)
  7413. {
  7414. Seconds *= 5;
  7415. }
  7416. UnicodeString NoteMessage(UnformatMessage(Message));
  7417. if (Terminal != NULL)
  7418. {
  7419. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7420. NoteMessage = FORMAT(L"%s: %s",
  7421. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7422. }
  7423. if (WinConfiguration->BalloonNotifications)
  7424. {
  7425. AddNote(NoteMessage);
  7426. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7427. }
  7428. else
  7429. {
  7430. FlashOnBackground();
  7431. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7432. }
  7433. }
  7434. }
  7435. //---------------------------------------------------------------------------
  7436. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7437. {
  7438. RestoreApp();
  7439. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7440. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7441. !NonVisualDataModule->Busy)
  7442. {
  7443. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7444. TTerminalManager::Instance()->ActiveSession = Terminal;
  7445. if (!ComponentVisible[fcQueueView])
  7446. {
  7447. ToggleQueueVisibility();
  7448. GoToQueue();
  7449. }
  7450. }
  7451. }
  7452. //---------------------------------------------------------------------------
  7453. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7454. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7455. {
  7456. UnicodeString Message;
  7457. TNotifyEvent OnClick = NULL;
  7458. TObject * UserData = NULL;
  7459. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7460. switch (Event)
  7461. {
  7462. case qeEmptyButMonitored:
  7463. if ((ATerminal != Terminal) || QueueInvisible)
  7464. {
  7465. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7466. OnClick = QueueEmptyNoteClicked;
  7467. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7468. TerminalNoteData->Terminal = ATerminal;
  7469. UserData = TerminalNoteData;
  7470. }
  7471. break;
  7472. case qeEmpty:
  7473. OperationComplete(ATerminal->QueueOperationStart);
  7474. break;
  7475. case qePendingUserAction:
  7476. if ((ATerminal != Terminal) ||
  7477. (QueueInvisible && !IsQueueAutoPopup()))
  7478. {
  7479. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7480. }
  7481. break;
  7482. default:
  7483. DebugFail();
  7484. }
  7485. if (!Message.IsEmpty())
  7486. {
  7487. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7488. }
  7489. }
  7490. //---------------------------------------------------------------------------
  7491. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7492. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7493. {
  7494. if (FDDExtMapFile != NULL)
  7495. {
  7496. CloseHandle(FDDExtMapFile);
  7497. FDDExtMapFile = NULL;
  7498. }
  7499. if (WinConfiguration->DDFakeFile)
  7500. {
  7501. DDFakeFileInitDrag(FileList, Created);
  7502. }
  7503. }
  7504. //---------------------------------------------------------------------------
  7505. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7506. {
  7507. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7508. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7509. {
  7510. FFakeFileDropTarget = FileName;
  7511. }
  7512. }
  7513. //---------------------------------------------------------------------------
  7514. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7515. {
  7516. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7517. if (!ForceDirectories(ApiPath(Result)))
  7518. {
  7519. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7520. }
  7521. FileSetAttr(ApiPath(Result), faHidden);
  7522. return Result;
  7523. }
  7524. //---------------------------------------------------------------------------
  7525. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7526. bool & Created)
  7527. {
  7528. FFakeFileDropTarget = UnicodeString();
  7529. FDragFakeDirectory = CreateFakeTransferDirectory();
  7530. FileList->AddItem(NULL, FDragFakeDirectory);
  7531. Created = true;
  7532. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7533. {
  7534. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7535. }
  7536. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7537. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7538. {
  7539. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7540. TDragExtCommStruct* CommStruct;
  7541. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7542. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7543. DebugAssert(CommStruct != NULL);
  7544. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7545. CommStruct->Dragging = true;
  7546. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7547. LENOF(CommStruct->DropDest));
  7548. NULL_TERMINATE(CommStruct->DropDest);
  7549. UnmapViewOfFile(CommStruct);
  7550. }
  7551. }
  7552. //---------------------------------------------------------------------------
  7553. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7554. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7555. {
  7556. bool Result;
  7557. DebugAssert(!IsLocalBrowserMode());
  7558. if (Sender == RemoteDirView)
  7559. {
  7560. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7561. }
  7562. else
  7563. {
  7564. DebugAssert(Sender == RemoteDriveView);
  7565. TStrings * FileList = RemoteDriveView->DragFileList();
  7566. try
  7567. {
  7568. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7569. }
  7570. __finally
  7571. {
  7572. delete FileList;
  7573. }
  7574. }
  7575. if (FDDTargetControl == RemoteDriveView)
  7576. {
  7577. RemoteDriveView->UpdateDropTarget();
  7578. }
  7579. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7580. // or from tree view to dir view.
  7581. // foMove happens when file/dir is dragged from remote tree view outside of
  7582. // application via dragex
  7583. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7584. (DropSourceControl == RemoteDriveView))
  7585. {
  7586. RemoteDriveView->UpdateDropSource();
  7587. }
  7588. return Result;
  7589. }
  7590. //---------------------------------------------------------------------------
  7591. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7592. {
  7593. DebugAssert(!IsLocalBrowserMode());
  7594. // This also handles drops of remote files to queue.
  7595. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7596. SAFE_DESTROY(FDDFileList);
  7597. if (!FFakeFileDropTarget.IsEmpty())
  7598. {
  7599. RemoveDir(ApiPath(FFakeFileDropTarget));
  7600. }
  7601. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7602. {
  7603. try
  7604. {
  7605. TDragResult DDResult = (Sender == RemoteDirView) ?
  7606. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7607. // Focus is moved to the target application,
  7608. // but as we are going to present the UI, we need to steal the focus back.
  7609. // This most likely won't work though (windows does not allow application
  7610. // to steal focus most of the time)
  7611. Application->BringToFront();
  7612. // On older version of Windows we never got drMove here, see also comment below.
  7613. // On Windows 10, we get the "move".
  7614. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7615. {
  7616. UnicodeString TargetDirectory;
  7617. TFileOperation Operation;
  7618. // drInvalid may mean drMove, see comment below
  7619. switch (DDResult)
  7620. {
  7621. case drCopy:
  7622. Operation = foCopy;
  7623. break;
  7624. case drMove:
  7625. Operation = foMove;
  7626. break;
  7627. default:
  7628. DebugFail();
  7629. case drInvalid:
  7630. // prefer "copy" for safety
  7631. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7632. break;
  7633. }
  7634. TTransferOperationParam Param;
  7635. UnicodeString CounterName;
  7636. bool ForceQueue;
  7637. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7638. {
  7639. // we get drInvalid both if d&d was intercepted by ddext,
  7640. // and when users drops on no-drop location.
  7641. // we tell the difference by existence of response from ddext,
  7642. // so we ignore absence of response in this case
  7643. if (DDResult != drInvalid)
  7644. {
  7645. // here we know that the extension is installed,
  7646. // as it is checked as soon as drag&drop starts from
  7647. // RemoteFileControlDDCreateDragFileList
  7648. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7649. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7650. {
  7651. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7652. }
  7653. else
  7654. {
  7655. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7656. }
  7657. }
  7658. }
  7659. else
  7660. {
  7661. // download using fake file
  7662. Param.Temp = false;
  7663. Param.DragDrop = true;
  7664. if (ForceQueue)
  7665. {
  7666. Param.Queue = asOn;
  7667. }
  7668. if (Sender == RemoteDirView)
  7669. {
  7670. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7671. }
  7672. if (RemoteFileControlFileOperation(Sender, Operation,
  7673. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7674. {
  7675. Configuration->Usage->Inc(CounterName);
  7676. }
  7677. }
  7678. }
  7679. }
  7680. __finally
  7681. {
  7682. CloseHandle(FDDExtMapFile);
  7683. FDDExtMapFile = NULL;
  7684. delete FDragFakeMonitors;
  7685. FDragFakeMonitors = NULL;
  7686. RemoveDir(ApiPath(FDragFakeDirectory));
  7687. FDragFakeDirectory = L"";
  7688. FFakeFileDropTarget = UnicodeString();
  7689. }
  7690. }
  7691. if (FDragDropSshTerminate.get() != NULL)
  7692. {
  7693. FDragDropSshTerminate->Rethrow();
  7694. }
  7695. }
  7696. //---------------------------------------------------------------------------
  7697. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7698. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7699. {
  7700. // Remember drop effect so we know (when user drops files), if we copy or move
  7701. FLastDropEffect = dwEffect;
  7702. }
  7703. //---------------------------------------------------------------------------
  7704. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7705. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7706. {
  7707. bool Result;
  7708. if (FDDTargetControl == QueueView3)
  7709. {
  7710. Directory = DefaultDownloadTargetDirectory();
  7711. Result = true;
  7712. CounterName = L"DownloadsDragDropQueue";
  7713. ForceQueue = true;
  7714. }
  7715. else if (!FFakeFileDropTarget.IsEmpty())
  7716. {
  7717. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7718. Result = true;
  7719. ForceQueue = false;
  7720. CounterName = L"DownloadsDragDropFakeFile";
  7721. }
  7722. else
  7723. {
  7724. ForceQueue = false;
  7725. Enabled = false;
  7726. try
  7727. {
  7728. int Timer = 0;
  7729. Result = false;
  7730. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7731. {
  7732. {
  7733. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7734. TDragExtCommStruct* CommStruct;
  7735. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7736. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7737. DebugAssert(CommStruct != NULL);
  7738. Result = !CommStruct->Dragging;
  7739. if (Result)
  7740. {
  7741. Directory = ExtractFilePath(CommStruct->DropDest);
  7742. CounterName = L"DownloadsDragDropExternalExt";
  7743. }
  7744. UnmapViewOfFile(CommStruct);
  7745. }
  7746. if (!Result)
  7747. {
  7748. Sleep(50);
  7749. Timer += 50;
  7750. Application->ProcessMessages();
  7751. }
  7752. }
  7753. }
  7754. __finally
  7755. {
  7756. Enabled = true;
  7757. }
  7758. }
  7759. return Result;
  7760. }
  7761. //---------------------------------------------------------------------------
  7762. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7763. const UnicodeString TempDir, int SecDelay)
  7764. {
  7765. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7766. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7767. if (FDelayedDeletionTimer == NULL)
  7768. {
  7769. DebugAssert(HandleAllocated());
  7770. FDelayedDeletionTimer = new TTimer(this);
  7771. FDelayedDeletionTimer->Interval = 10000;
  7772. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7773. }
  7774. else
  7775. {
  7776. FDelayedDeletionTimer->Enabled = true;
  7777. }
  7778. }
  7779. //---------------------------------------------------------------------------
  7780. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7781. {
  7782. DebugAssert(FDelayedDeletionList != NULL);
  7783. TDateTime N = Now();
  7784. TDateTime Alert;
  7785. UnicodeString Directory;
  7786. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7787. {
  7788. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7789. if ((N >= Alert) || (Sender == NULL))
  7790. {
  7791. Directory = FDelayedDeletionList->Strings[Index];
  7792. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7793. {
  7794. FDelayedDeletionList->Delete(Index);
  7795. }
  7796. }
  7797. }
  7798. if (FDelayedDeletionList->Count == 0)
  7799. {
  7800. FDelayedDeletionTimer->Enabled = false;
  7801. }
  7802. }
  7803. //---------------------------------------------------------------------------
  7804. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7805. {
  7806. DebugAssert(!IsLocalBrowserMode());
  7807. if (IsFileControl(FDDTargetControl, osRemote) ||
  7808. (FDDTargetControl == SessionsPageControl))
  7809. {
  7810. TManagedTerminal * TargetTerminal = NULL;
  7811. TFileOperation Operation = foNone;
  7812. if (FDDTargetControl == SessionsPageControl)
  7813. {
  7814. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7815. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7816. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7817. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7818. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7819. {
  7820. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7821. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7822. {
  7823. Operation = foRemoteMove;
  7824. }
  7825. else
  7826. {
  7827. Operation = foRemoteCopy;
  7828. }
  7829. }
  7830. }
  7831. else
  7832. {
  7833. if (FLastDropEffect == DROPEFFECT_MOVE)
  7834. {
  7835. Operation = foRemoteMove;
  7836. }
  7837. else if (FLastDropEffect == DROPEFFECT_COPY)
  7838. {
  7839. Operation = foRemoteCopy;
  7840. }
  7841. }
  7842. if (Operation != foNone)
  7843. {
  7844. RemoteFileControlFileOperation(DropSourceControl,
  7845. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7846. }
  7847. // abort drag&drop
  7848. Abort();
  7849. }
  7850. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7851. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7852. (FDDTargetControl != QueueView3))
  7853. {
  7854. DebugAssert(!FDragTempDir.IsEmpty());
  7855. TTransferType Type;
  7856. UnicodeString TempDir = FDragTempDir;
  7857. // We clear FDragTempDir before calling
  7858. // just in case it fail (raises exception)
  7859. FDragTempDir = L"";
  7860. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7861. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7862. // empty directory parameter means temp directory -> don't display it!
  7863. UnicodeString TargetDir = L"";
  7864. int Options = 0;
  7865. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7866. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7867. {
  7868. Abort();
  7869. }
  7870. // TargetDir is set when dropped on local file control
  7871. // (this was workaround for legacy dirview event handling, now it should be
  7872. // made prettier)
  7873. if (TargetDir.IsEmpty())
  7874. {
  7875. TargetDir = TempDir;
  7876. if (ForceDirectories(ApiPath(TargetDir)))
  7877. {
  7878. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7879. FPendingTempSpaceWarn = true;
  7880. try
  7881. {
  7882. FDragDropOperation = true;
  7883. int Params = cpTemporary |
  7884. (Type == ttMove ? cpDelete : 0);
  7885. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7886. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7887. }
  7888. __finally
  7889. {
  7890. FDragDropOperation = false;
  7891. FPendingTempSpaceWarn = false;
  7892. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7893. }
  7894. }
  7895. else
  7896. {
  7897. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7898. }
  7899. }
  7900. }
  7901. }
  7902. //---------------------------------------------------------------------------
  7903. void __fastcall TCustomScpExplorerForm::DDDownload(
  7904. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7905. {
  7906. DebugAssert(!IsLocalBrowserMode());
  7907. TAutoBatch AutoBatch(this);
  7908. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7909. UpdateCopyParamCounters(*CopyParam);
  7910. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7911. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7912. {
  7913. RemoteDriveView->UpdateDropSource();
  7914. }
  7915. }
  7916. //---------------------------------------------------------------------------
  7917. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7918. {
  7919. public:
  7920. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7921. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7922. {
  7923. }
  7924. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7925. {
  7926. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7927. TDataObjectFilesEx::AllowData(FormatEtc);
  7928. }
  7929. };
  7930. //---------------------------------------------------------------------------
  7931. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7932. TObject * Sender, TDataObject *& DataObject)
  7933. {
  7934. if (FDDExtMapFile != NULL)
  7935. {
  7936. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7937. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7938. {
  7939. Abort();
  7940. }
  7941. if (FileList->Count > 0)
  7942. {
  7943. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7944. if (!FilesObject->IsValid(true, true))
  7945. {
  7946. FilesObject->_Release();
  7947. }
  7948. else
  7949. {
  7950. DataObject = FilesObject;
  7951. }
  7952. }
  7953. }
  7954. }
  7955. //---------------------------------------------------------------------------
  7956. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7957. {
  7958. DebugFail();
  7959. }
  7960. //---------------------------------------------------------------------------
  7961. void __fastcall TCustomScpExplorerForm::GoToTree()
  7962. {
  7963. ComponentVisible[fcRemoteTree] = true;
  7964. DriveView(osRemote)->SetFocus();
  7965. }
  7966. //---------------------------------------------------------------------------
  7967. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7968. TPanelExport Export)
  7969. {
  7970. TCustomDirView * DirView = this->DirView(Side);
  7971. std::unique_ptr<TStrings> ExportData(new TStringList());
  7972. switch (Export)
  7973. {
  7974. case pePath:
  7975. ExportData->Add(DirView->PathName);
  7976. break;
  7977. case peFileList:
  7978. case peFullFileList:
  7979. {
  7980. bool FullPath = (Export == peFullFileList);
  7981. DirView->CreateFileList(false, FullPath, ExportData.get());
  7982. for (int Index = 0; Index < ExportData->Count; Index++)
  7983. {
  7984. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7985. {
  7986. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7987. }
  7988. }
  7989. }
  7990. break;
  7991. default:
  7992. DebugFail();
  7993. }
  7994. return ExportData.release();
  7995. }
  7996. //---------------------------------------------------------------------------
  7997. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7998. TPanelExport Export, TPanelExportDestination Destination)
  7999. {
  8000. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  8001. PanelExportStore(Side, Export, Destination, ExportData.get());
  8002. }
  8003. //---------------------------------------------------------------------------
  8004. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  8005. TPanelExport /*Export*/, TPanelExportDestination Destination,
  8006. TStrings * ExportData)
  8007. {
  8008. if (Destination == pedClipboard)
  8009. {
  8010. TInstantOperationVisualizer Visualizer;
  8011. CopyToClipboard(ExportData);
  8012. }
  8013. else
  8014. {
  8015. DebugFail();
  8016. }
  8017. }
  8018. //---------------------------------------------------------------------------
  8019. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8020. {
  8021. TCustomDirView * DirView = this->DirView(Side);
  8022. UnicodeString Mask = DirView->Mask;
  8023. if (DoFilterMaskDialog(DirView, Mask))
  8024. {
  8025. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8026. Configuration->Usage->Inc(L"Filters");
  8027. }
  8028. }
  8029. //---------------------------------------------------------------------------
  8030. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8031. {
  8032. return FQueueController->DefaultOperation();
  8033. }
  8034. //---------------------------------------------------------------------------
  8035. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8036. TQueueOperation Operation, void ** Param)
  8037. {
  8038. switch (Operation)
  8039. {
  8040. case qoPreferences:
  8041. return true;
  8042. case qoGoTo:
  8043. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8044. case qoOnceEmpty:
  8045. return IsAnythingQueued();
  8046. default:
  8047. return FQueueController->AllowOperation(Operation, Param);
  8048. }
  8049. }
  8050. //---------------------------------------------------------------------------
  8051. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8052. {
  8053. if (DebugAlwaysTrue(QueueView3->Visible))
  8054. {
  8055. QueueView3->SetFocus();
  8056. }
  8057. }
  8058. //---------------------------------------------------------------------------
  8059. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8060. TQueueOperation Operation, void * Param)
  8061. {
  8062. if (Operation == qoGoTo)
  8063. {
  8064. GoToQueue();
  8065. }
  8066. else if (Operation == qoPreferences)
  8067. {
  8068. PreferencesDialog(pmQueue);
  8069. }
  8070. else
  8071. {
  8072. FQueueController->ExecuteOperation(Operation, Param);
  8073. }
  8074. }
  8075. //---------------------------------------------------------------------------
  8076. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8077. {
  8078. return (Queue != NULL) && Queue->Enabled;
  8079. }
  8080. //---------------------------------------------------------------------------
  8081. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8082. {
  8083. DebugAssert(Queue != NULL);
  8084. if (Queue != NULL)
  8085. {
  8086. Queue->Enabled = !Queue->Enabled;
  8087. }
  8088. }
  8089. //---------------------------------------------------------------------------
  8090. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8091. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8092. {
  8093. FQueueActedItem = QueueView3->ItemFocused;
  8094. }
  8095. //---------------------------------------------------------------------------
  8096. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8097. {
  8098. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8099. }
  8100. //---------------------------------------------------------------------------
  8101. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8102. {
  8103. return
  8104. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8105. (QueueDock->Visible ? QueueDock->Height : 0) +
  8106. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8107. }
  8108. //---------------------------------------------------------------------------
  8109. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8110. {
  8111. return ScaleByTextHeight(this, 48);
  8112. }
  8113. //---------------------------------------------------------------------------
  8114. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8115. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8116. {
  8117. // when queue is hidden by double-clicking splitter, stray attempt to
  8118. // resize the panel with strange value arrives, make sure it is ignored
  8119. if (ComponentVisible[fcQueueView])
  8120. {
  8121. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8122. if (NewSize > MaxHeightLimit)
  8123. {
  8124. NewSize = MaxHeightLimit;
  8125. }
  8126. int MinHeightLimit =
  8127. GetStaticQueuePanelComponentsHeight() +
  8128. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8129. GetMinQueueViewHeight();
  8130. if (NewSize < MinHeightLimit)
  8131. {
  8132. NewSize = MinHeightLimit;
  8133. }
  8134. }
  8135. else
  8136. {
  8137. Accept = false;
  8138. }
  8139. }
  8140. //---------------------------------------------------------------------------
  8141. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8142. {
  8143. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8144. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8145. if (QueueViewHeight < GetMinQueueViewHeight())
  8146. {
  8147. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8148. }
  8149. }
  8150. //---------------------------------------------------------------------------
  8151. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8152. TDragObject *& /*DragObject*/)
  8153. {
  8154. FQueueActedItem = QueueView3->ItemFocused;
  8155. FQueueScrollOnDragOver->StartDrag();
  8156. }
  8157. //---------------------------------------------------------------------------
  8158. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8159. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8160. {
  8161. FQueueScrollOnDragOver->EndDrag();
  8162. }
  8163. //---------------------------------------------------------------------------
  8164. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8165. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8166. {
  8167. Accept = true;
  8168. if (Source == QueueView3)
  8169. {
  8170. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8171. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8172. if (Accept)
  8173. {
  8174. TQueueItemProxy * QueueItem;
  8175. TQueueItemProxy * DestQueueItem;
  8176. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8177. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8178. Accept = (QueueItem != DestQueueItem) &&
  8179. (QueueItem->Status == TQueueItem::qsPending) &&
  8180. (DestQueueItem->Status == TQueueItem::qsPending);
  8181. }
  8182. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8183. }
  8184. }
  8185. //---------------------------------------------------------------------------
  8186. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8187. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8188. {
  8189. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8190. {
  8191. TQueueItemProxy * QueueItem;
  8192. TQueueItemProxy * DestQueueItem;
  8193. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8194. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8195. QueueItem->Move(DestQueueItem);
  8196. }
  8197. }
  8198. //---------------------------------------------------------------------------
  8199. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8200. {
  8201. if ((QueueView3->ItemFocused == NULL) &&
  8202. (QueueView3->Items->Count > 0))
  8203. {
  8204. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8205. }
  8206. QueueLabelUpdateStatus();
  8207. }
  8208. //---------------------------------------------------------------------------
  8209. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8210. {
  8211. QueueLabelUpdateStatus();
  8212. }
  8213. //---------------------------------------------------------------------------
  8214. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8215. {
  8216. QueueLabel->UpdateStatus();
  8217. }
  8218. //---------------------------------------------------------------------------
  8219. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8220. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8221. {
  8222. if (Selected)
  8223. {
  8224. NonVisualDataModule->UpdateNonVisibleActions();
  8225. }
  8226. }
  8227. //---------------------------------------------------------------------------
  8228. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8229. {
  8230. TDragDropFilesEx * Result = NULL;
  8231. if (Sender == SessionsPageControl)
  8232. {
  8233. Result = FSessionsDragDropFilesEx;
  8234. }
  8235. else if (Sender == QueueView3)
  8236. {
  8237. Result = FQueueDragDropFilesEx;
  8238. }
  8239. else
  8240. {
  8241. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8242. if (DirView != NULL)
  8243. {
  8244. Result = DirView->DragDropFilesEx;
  8245. }
  8246. else
  8247. {
  8248. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8249. if (DriveView != NULL)
  8250. {
  8251. Result = DriveView->DragDropFilesEx;
  8252. }
  8253. }
  8254. }
  8255. DebugAssert(Result != NULL);
  8256. return Result;
  8257. }
  8258. //---------------------------------------------------------------------------
  8259. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8260. {
  8261. return (DView->SelCount == DView->FilesCount);
  8262. }
  8263. //---------------------------------------------------------------------------
  8264. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8265. {
  8266. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8267. }
  8268. //---------------------------------------------------------------------------
  8269. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8270. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8271. {
  8272. DebugAssert(!IsLocalBrowserMode());
  8273. TFileOperation Operation;
  8274. switch (Effect)
  8275. {
  8276. case DROPEFFECT_MOVE:
  8277. Operation = foMove;
  8278. break;
  8279. case DROPEFFECT_COPY:
  8280. // occures on WinXP (reported by user)
  8281. default:
  8282. Operation = foCopy;
  8283. break;
  8284. };
  8285. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8286. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8287. if (DragDropFilesEx->FileList->Count > 0)
  8288. {
  8289. TStrings * FileList = new TStringList();
  8290. try
  8291. {
  8292. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8293. {
  8294. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8295. }
  8296. FDragDropOperation = true;
  8297. TTransferOperationParam Param;
  8298. Param.TargetDirectory = TargetPath;
  8299. // upload, no temp dirs
  8300. Param.Temp = false;
  8301. Param.DragDrop = DragDrop;
  8302. Param.Options =
  8303. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8304. if (ForceQueue)
  8305. {
  8306. Param.Queue = asOn;
  8307. }
  8308. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8309. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8310. {
  8311. if (IsFileControl(DropSourceControl, osLocal))
  8312. {
  8313. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8314. }
  8315. else
  8316. {
  8317. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8318. }
  8319. }
  8320. }
  8321. __finally
  8322. {
  8323. FDragDropOperation = false;
  8324. delete FileList;
  8325. }
  8326. }
  8327. }
  8328. //---------------------------------------------------------------------------
  8329. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8330. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8331. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8332. {
  8333. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8334. }
  8335. //---------------------------------------------------------------------------
  8336. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8337. TObject * Sender, int grfKeyState, int & dwEffect)
  8338. {
  8339. DebugAssert(!IsLocalBrowserMode());
  8340. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8341. if ((dwEffect != DROPEFFECT_NONE) &&
  8342. IsFileControl(DropSourceControl, osRemote))
  8343. {
  8344. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8345. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8346. (RemoteDirView->DropTarget == NULL))
  8347. {
  8348. dwEffect = DROPEFFECT_NONE;
  8349. }
  8350. else
  8351. {
  8352. if (dwEffect == DROPEFFECT_COPY)
  8353. {
  8354. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8355. // currently we support copying always (at least via temporary directory);
  8356. // remove associated checks once this all proves stable and working
  8357. bool CopyCapable = true;
  8358. // if we do not support neither of operations, there's no discussion
  8359. if (!MoveCapable && !CopyCapable)
  8360. {
  8361. dwEffect = DROPEFFECT_NONE;
  8362. }
  8363. else
  8364. {
  8365. // The default effect inside remote panel is move,
  8366. // unless we do not support it, but support copy
  8367. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8368. {
  8369. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8370. }
  8371. else
  8372. {
  8373. // with ctrl-down, we want copy unless it is not supported
  8374. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8375. }
  8376. }
  8377. }
  8378. }
  8379. }
  8380. }
  8381. //---------------------------------------------------------------------------
  8382. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8383. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8384. {
  8385. DebugAssert(!IsLocalBrowserMode());
  8386. if (FDDTotalSize >= 0)
  8387. {
  8388. if (File->IsDirectory)
  8389. {
  8390. FDDTotalSize = -1;
  8391. }
  8392. else
  8393. {
  8394. FDDTotalSize += File->Size;
  8395. }
  8396. }
  8397. DebugAssert(!FDragTempDir.IsEmpty());
  8398. // TODO: this is quite ineffective
  8399. // TODO: what if invalid character replacement is disabled?
  8400. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8401. UnicodeString TransferFileName;
  8402. if (Sender == RemoteDriveView)
  8403. {
  8404. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8405. }
  8406. else
  8407. {
  8408. TransferFileName = File->FileName;
  8409. }
  8410. FDDFileList->AddObject(TransferFileName, File);
  8411. }
  8412. //---------------------------------------------------------------------------
  8413. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8414. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8415. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8416. {
  8417. // sometimes we do not get DDEnd so the list is not released
  8418. SAFE_DESTROY(FDDFileList);
  8419. FDDFileList = new TStringList();
  8420. FDragTempDir = WinConfiguration->TemporaryDir();
  8421. FDDTotalSize = 0;
  8422. FDragDropSshTerminate.reset(NULL);
  8423. }
  8424. //---------------------------------------------------------------------------
  8425. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8426. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8427. HRESULT & Result)
  8428. {
  8429. if (Result == DRAGDROP_S_DROP)
  8430. {
  8431. try
  8432. {
  8433. GlobalDragImageList->HideDragImage();
  8434. try
  8435. {
  8436. RemoteFileControlDDTargetDrop();
  8437. }
  8438. catch(ESshTerminate & E)
  8439. {
  8440. FDragDropSshTerminate.reset(E.Clone());
  8441. }
  8442. }
  8443. catch (Exception &E)
  8444. {
  8445. // If downloading fails we need to cancel drag&drop, otherwise
  8446. // Explorer shows error
  8447. // But by the way exception probably never reach this point as
  8448. // it's catched on way.
  8449. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8450. Result = DRAGDROP_S_CANCEL;
  8451. ShowExtendedException(Terminal, &E);
  8452. }
  8453. }
  8454. }
  8455. //---------------------------------------------------------------------------
  8456. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8457. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8458. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8459. {
  8460. TFileMasks::TParams MaskParams;
  8461. MaskParams.Size = Size;
  8462. MaskParams.Modification = Modification;
  8463. // this does not re-parse the mask if it is the same as the last time
  8464. FDirViewMatchMask = Masks;
  8465. bool ImplicitMatch;
  8466. Matches =
  8467. // Local and RecurseInclude parameters have no effect as there's no path.
  8468. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8469. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8470. (AllowImplicitMatches || !ImplicitMatch);
  8471. }
  8472. //---------------------------------------------------------------------------
  8473. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8474. TObject * Sender, TListItem * Item, WORD & Indexes)
  8475. {
  8476. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8477. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8478. {
  8479. Indexes |= oiPartial;
  8480. }
  8481. }
  8482. //---------------------------------------------------------------------------
  8483. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8484. {
  8485. return
  8486. DirViewEnabled(osCurrent) &&
  8487. DirView(osCurrent)->CanPasteFromClipBoard();
  8488. }
  8489. //---------------------------------------------------------------------------
  8490. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8491. {
  8492. bool Result = false;
  8493. if (CanPasteToDirViewFromClipBoard())
  8494. {
  8495. Result = true;
  8496. }
  8497. else
  8498. {
  8499. UnicodeString ClipboardText;
  8500. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8501. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8502. {
  8503. if (StoredSessions->IsUrl(ClipboardText))
  8504. {
  8505. Result = true;
  8506. }
  8507. else
  8508. {
  8509. Result = DirViewEnabled(osCurrent);
  8510. }
  8511. }
  8512. }
  8513. return Result;
  8514. }
  8515. //---------------------------------------------------------------------------
  8516. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8517. {
  8518. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8519. if (DoesClipboardContainOurFiles())
  8520. {
  8521. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8522. {
  8523. DebugAssert(!IsLocalBrowserMode());
  8524. TTerminalManager * Manager = TTerminalManager::Instance();
  8525. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8526. Manager->ActiveSession = FClipboardTerminal;
  8527. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8528. }
  8529. }
  8530. else if (CanPasteToDirViewFromClipBoard())
  8531. {
  8532. DirView(osCurrent)->PasteFromClipBoard();
  8533. }
  8534. else
  8535. {
  8536. UnicodeString ClipboardText;
  8537. if (NonEmptyTextFromClipboard(ClipboardText))
  8538. {
  8539. if (StoredSessions->IsUrl(ClipboardText))
  8540. {
  8541. NewSession(ClipboardText);
  8542. }
  8543. else
  8544. {
  8545. DirView(osCurrent)->Path = ClipboardText;
  8546. }
  8547. }
  8548. }
  8549. }
  8550. //---------------------------------------------------------------------------
  8551. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8552. {
  8553. // TBD
  8554. }
  8555. //---------------------------------------------------------------------------
  8556. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8557. {
  8558. TCustomDirView * ADirView = DirView(Side);
  8559. ADirView->SelectAll(Mode);
  8560. ADirView->SetFocus();
  8561. }
  8562. //---------------------------------------------------------------------------
  8563. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8564. {
  8565. TCustomDirView * ADirView = DirView(Side);
  8566. TFileFilter Filter;
  8567. DefaultFileFilter(Filter);
  8568. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8569. {
  8570. Configuration->Usage->Inc(L"MaskSelections");
  8571. ADirView->SelectFiles(Filter, Select);
  8572. ADirView->SetFocus();
  8573. }
  8574. }
  8575. //---------------------------------------------------------------------------
  8576. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8577. {
  8578. TCustomDirView * ADirView = DirView(Side);
  8579. ADirView->RestoreSelectedNames();
  8580. ADirView->SetFocus();
  8581. }
  8582. //---------------------------------------------------------------------------
  8583. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8584. {
  8585. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8586. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8587. {
  8588. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8589. UnicodeString Ext;
  8590. if (!IsSideLocalBrowser(osCurrent))
  8591. {
  8592. Ext = UnixExtractFileExt(FileName);
  8593. }
  8594. else
  8595. {
  8596. Ext = ExtractFileExt(FileName);
  8597. }
  8598. if (Ext.IsEmpty())
  8599. {
  8600. Ext = L".";
  8601. }
  8602. TFileFilter Filter;
  8603. Filter.Masks = FORMAT(L"*%s", (Ext));
  8604. Filter.Directories = false;
  8605. CurrentDirView->SelectFiles(Filter, Select);
  8606. }
  8607. }
  8608. //---------------------------------------------------------------------------
  8609. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8610. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8611. {
  8612. UnicodeString Result;
  8613. if (FIncrementalSearchState.Searching && (Side == GetSide(osCurrent)))
  8614. {
  8615. Result = FormatIncrementalSearchStatus(FIncrementalSearchState);
  8616. }
  8617. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8618. {
  8619. // noop
  8620. }
  8621. else
  8622. {
  8623. Result =
  8624. FMTLOAD(FILE_INFO_FORMAT,
  8625. (FormatBytes(FileInfo.SelectedSize),
  8626. FormatBytes(FileInfo.FilesSize),
  8627. FormatNumber(FileInfo.SelectedCount),
  8628. FormatNumber(FileInfo.FilesCount)));
  8629. }
  8630. return Result;
  8631. }
  8632. //---------------------------------------------------------------------------
  8633. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8634. TTBXStatusPanel * Panel, TOperationSide Side)
  8635. {
  8636. if (Panel->Index == 1)
  8637. {
  8638. ToggleShowHiddenFiles();
  8639. }
  8640. else if (Panel->Index == 2)
  8641. {
  8642. Filter(Side);
  8643. }
  8644. }
  8645. //---------------------------------------------------------------------------
  8646. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8647. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8648. {
  8649. DebugAssert(!StatusBar->SimplePanel);
  8650. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8651. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8652. }
  8653. //---------------------------------------------------------------------------
  8654. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8655. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8656. {
  8657. DebugAssert(StatusBar->Panels->Count >= 3);
  8658. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8659. if (FileInfo.HiddenCount > 0)
  8660. {
  8661. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8662. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8663. }
  8664. else
  8665. {
  8666. HiddenFilesPanel->ViewPriority = 0;
  8667. // not really necessary, just to cleanup no-longer-valid data
  8668. HiddenFilesPanel->Caption = L"";
  8669. }
  8670. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8671. if (FileInfo.FilteredCount > 0)
  8672. {
  8673. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8674. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8675. }
  8676. else
  8677. {
  8678. FilteredFilesPanel->ViewPriority = 0;
  8679. // not really necessary, just to cleanup no-longer-valid data
  8680. FilteredFilesPanel->Caption = L"";
  8681. }
  8682. }
  8683. //---------------------------------------------------------------------------
  8684. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8685. TObject * /*Sender*/)
  8686. {
  8687. if (DirView(osOther)->Enabled)
  8688. {
  8689. DirView(osOther)->SetFocus();
  8690. }
  8691. }
  8692. //---------------------------------------------------------------------------
  8693. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8694. {
  8695. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8696. switch (Config.Show)
  8697. {
  8698. case qvShow:
  8699. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8700. {
  8701. Config.Show = qvHide;
  8702. }
  8703. else
  8704. {
  8705. Config.Show = Config.LastHideShow;
  8706. }
  8707. break;
  8708. case qvHideWhenEmpty:
  8709. if (ComponentVisible[fcQueueView])
  8710. {
  8711. Config.Show = qvHide;
  8712. }
  8713. else
  8714. {
  8715. Config.LastHideShow = Config.Show;
  8716. Config.Show = qvShow;
  8717. }
  8718. break;
  8719. case qvHide:
  8720. Config.LastHideShow = Config.Show;
  8721. Config.Show = qvShow;
  8722. break;
  8723. }
  8724. WinConfiguration->QueueView = Config;
  8725. }
  8726. //---------------------------------------------------------------------------
  8727. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8728. {
  8729. UnicodeString Result;
  8730. if (Terminal != NULL)
  8731. {
  8732. switch (WinConfiguration->PathInCaption)
  8733. {
  8734. case picShort:
  8735. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8736. break;
  8737. case picFull:
  8738. Result = Terminal->CurrentDirectory;
  8739. break;
  8740. }
  8741. }
  8742. return Result;
  8743. }
  8744. //---------------------------------------------------------------------------
  8745. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8746. {
  8747. TColor Result = GetWindowColor(FSessionColor);
  8748. return Result;
  8749. }
  8750. //---------------------------------------------------------------------------
  8751. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8752. {
  8753. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8754. return Result;
  8755. }
  8756. //---------------------------------------------------------------------------
  8757. void TCustomScpExplorerForm::UpdatePanelControls(TCustomDirView * ADirView, TCustomDriveView * ADriveView)
  8758. {
  8759. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8760. ADirView->DarkMode = UseDarkTheme;
  8761. ADriveView->DarkMode = UseDarkTheme;
  8762. }
  8763. //---------------------------------------------------------------------------
  8764. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8765. {
  8766. if (!FSessionChanging)
  8767. {
  8768. TTerminalManager::Instance()->UpdateAppTitle();
  8769. }
  8770. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8771. // background to gray on Windows 7 (works on Windows 10).
  8772. // See also EnableControl
  8773. if (Showing)
  8774. {
  8775. if (ManagedSession != NULL)
  8776. {
  8777. // Update path when it changes
  8778. if ((SessionsPageControl->ActivePage != NULL) &&
  8779. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8780. {
  8781. UpdateSessionTab(SessionsPageControl->ActivePage);
  8782. }
  8783. }
  8784. NonVisualDataModule->ReconnectSessionAction->Update();
  8785. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8786. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8787. CenterReconnectToolbar();
  8788. bool HasTerminal = HasActiveTerminal();
  8789. RemoteDirView->Enabled = HasTerminal;
  8790. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8791. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8792. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8793. RemoteDriveView->Color = RemoteDirView->Color;
  8794. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8795. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8796. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8797. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8798. QueueFileList->Enabled = QueueView3->Enabled;
  8799. QueueFileList->Color = QueueView3->Color;
  8800. QueueFileList->Font->Color = QueueView3->Font->Color;
  8801. QueueLabelUpdateStatus();
  8802. UpdatePanelControls(RemoteDirView, RemoteDriveView);
  8803. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8804. if (FImmersiveDarkMode != UseDarkTheme)
  8805. {
  8806. UpdateDarkMode();
  8807. }
  8808. SessionsPageControl->TabTheme = UseDarkTheme ? CurrentTheme : NULL;
  8809. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8810. bool HiContrast = WinConfiguration->HiContrast;
  8811. UnicodeString NewHiContrastThemeName = HiContrast ? GetThemeName(!UseDarkTheme) : EmptyStr;
  8812. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8813. {
  8814. ReleaseHiContrastTheme();
  8815. if (!NewHiContrastThemeName.IsEmpty())
  8816. {
  8817. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8818. }
  8819. }
  8820. SessionsPageControl->ActiveTabTheme = HiContrast ? DebugNotNull(FHiContrastTheme) : NULL;
  8821. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8822. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8823. }
  8824. }
  8825. //---------------------------------------------------------------------------
  8826. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8827. {
  8828. UpdateControls();
  8829. }
  8830. //---------------------------------------------------------------------------
  8831. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8832. TObject * Sender)
  8833. {
  8834. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8835. DebugAssert(DirView != NULL);
  8836. DoDirViewLoaded(DirView);
  8837. TransferPresetAutoSelect();
  8838. TUnixDirView * UnixDirView = dynamic_cast<TUnixDirView *>(DirView);
  8839. if (UnixDirView != NULL)
  8840. {
  8841. TManagedTerminal * ATerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(UnixDirView->Terminal));
  8842. TTerminalManager::Instance()->TerminalLoadedDirectory(ATerminal);
  8843. }
  8844. }
  8845. //---------------------------------------------------------------------------
  8846. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8847. {
  8848. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8849. // first run after installation
  8850. if (double(Updates.LastCheck) == 0)
  8851. {
  8852. AppLog(L"First run, scheduling updates check for the next run");
  8853. // make sure next time there will be an update (if enabled)
  8854. Updates.LastCheck = TDateTime(1);
  8855. WinConfiguration->Updates = Updates;
  8856. }
  8857. else
  8858. {
  8859. TDateTime Period;
  8860. if (IsUWP() && !IsOfficialPackage())
  8861. {
  8862. Period = DefaultUpdatesPeriod;
  8863. AppLog(L"Thirdparty UWP package, using default updates check period");
  8864. }
  8865. else
  8866. {
  8867. Period = Updates.Period;
  8868. }
  8869. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8870. if (double(Period) > 0)
  8871. {
  8872. TDateTime Interval = Now() - Updates.LastCheck;
  8873. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8874. if (Interval >= Period)
  8875. {
  8876. StartUpdateThread(UpdatesChecked);
  8877. }
  8878. }
  8879. }
  8880. }
  8881. //---------------------------------------------------------------------------
  8882. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8883. {
  8884. AppLog(L"Updates check done");
  8885. UnicodeString Message;
  8886. bool New;
  8887. TQueryType Type;
  8888. GetUpdatesMessage(Message, New, Type, false);
  8889. if (!Message.IsEmpty())
  8890. {
  8891. AppLogFmt(L"Updates check message: %s", (Message));
  8892. if (New)
  8893. {
  8894. AppLog(L"New version detected");
  8895. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8896. }
  8897. if (!New && (Type != qtWarning))
  8898. {
  8899. AppLog(L"Posting non-critical updates note");
  8900. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8901. }
  8902. else
  8903. {
  8904. AppLog(L"Posting new version or critical message notification");
  8905. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8906. }
  8907. if (New)
  8908. {
  8909. Configuration->Usage->Inc(L"UpdateNotifications");
  8910. }
  8911. }
  8912. }
  8913. //---------------------------------------------------------------------------
  8914. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8915. {
  8916. RestoreApp();
  8917. bool CanDisplay = !NonVisualDataModule->Busy;
  8918. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8919. {
  8920. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8921. }
  8922. if (CanDisplay)
  8923. {
  8924. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8925. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  8926. NonVisualDataModule->StartBusy();
  8927. try
  8928. {
  8929. CheckForUpdates(true);
  8930. }
  8931. __finally
  8932. {
  8933. NonVisualDataModule->EndBusy();
  8934. }
  8935. }
  8936. else
  8937. {
  8938. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8939. }
  8940. }
  8941. //---------------------------------------------------------------------------
  8942. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8943. TCopyParamRuleData & Data)
  8944. {
  8945. DebugAssert(Terminal != NULL);
  8946. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8947. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8948. Data.RemoteDirectory = RemoteDirView->PathName;
  8949. }
  8950. //---------------------------------------------------------------------------
  8951. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8952. {
  8953. // Terminal can be null when we are changing local directory implicitly,
  8954. // because it has been deleted, while no session is connected
  8955. // (Login dialog is open)
  8956. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8957. {
  8958. DebugAssert(!IsLocalBrowserMode());
  8959. TCopyParamRuleData Data;
  8960. GetTransferPresetAutoSelectData(Data);
  8961. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8962. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8963. if (CopyParamIndex < 0)
  8964. {
  8965. // there is no preset that matches autoselection
  8966. // set preset that we consider "default"
  8967. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8968. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8969. }
  8970. else
  8971. {
  8972. // there is preset matching autoselection
  8973. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8974. if (CopyParamName == FCopyParamAutoSelected)
  8975. {
  8976. // autoselected the same preset as the last time
  8977. // make no change (i.e. preserve custom user preset, if any)
  8978. }
  8979. else
  8980. {
  8981. // autoselected the different preset then the last time (or there
  8982. // was default preset set)
  8983. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8984. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8985. }
  8986. }
  8987. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8988. {
  8989. if (CopyParamIndex >= 0)
  8990. {
  8991. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8992. }
  8993. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8994. try
  8995. {
  8996. int Fmt =
  8997. (CopyParamIndex < 0) ?
  8998. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8999. COPY_PARAM_AUTOSELECTED;
  9000. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  9001. Data->Message = MainInstructions(Message);
  9002. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  9003. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  9004. CopyParamAttrs);
  9005. if (CopyParamIndex >= 0)
  9006. {
  9007. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  9008. Info = FORMAT(L"%s\n \n%s", (Info,
  9009. FMTLOAD(COPY_PARAM_RULE,
  9010. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  9011. }
  9012. Data->Message += L"\n\n" + Info;
  9013. if (WinConfiguration->CopyParamAutoSelectNotice)
  9014. {
  9015. TransferPresetNoteMessage(Data, true);
  9016. }
  9017. else
  9018. {
  9019. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  9020. Data = NULL; // ownership passed
  9021. }
  9022. }
  9023. __finally
  9024. {
  9025. delete Data;
  9026. }
  9027. }
  9028. }
  9029. }
  9030. //---------------------------------------------------------------------------
  9031. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9032. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9033. {
  9034. DebugAssert(NoteData != NULL);
  9035. DebugAssert(!IsLocalBrowserMode());
  9036. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9037. TQueryButtonAlias Aliases[1];
  9038. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9039. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9040. Params.Aliases = Aliases;
  9041. Params.AliasesCount = LENOF(Aliases);
  9042. unsigned int Result =
  9043. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9044. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9045. switch (Result)
  9046. {
  9047. case qaNeverAskAgain:
  9048. DebugAssert(AllowNeverAskAgain);
  9049. WinConfiguration->CopyParamAutoSelectNotice = false;
  9050. break;
  9051. case qaIgnore:
  9052. PreferencesDialog(pmPresets);
  9053. break;
  9054. }
  9055. }
  9056. //---------------------------------------------------------------------------
  9057. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9058. {
  9059. // as of now useless, as this is used for notes only, never for balloons, ...
  9060. RestoreApp();
  9061. // .. and we should never be busy here
  9062. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9063. {
  9064. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9065. }
  9066. }
  9067. //---------------------------------------------------------------------------
  9068. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9069. TPreferencesMode APreferencesMode)
  9070. {
  9071. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9072. TCopyParamRuleData Data;
  9073. if (Terminal != NULL)
  9074. {
  9075. PreferencesData.reset(new TPreferencesDialogData());
  9076. GetTransferPresetAutoSelectData(Data);
  9077. PreferencesData->CopyParamRuleData = &Data;
  9078. }
  9079. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9080. }
  9081. //---------------------------------------------------------------------------
  9082. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9083. const TCustomCommandType & Command)
  9084. {
  9085. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9086. {
  9087. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9088. }
  9089. }
  9090. //---------------------------------------------------------------------------
  9091. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9092. {
  9093. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9094. TCustomCommandType Command;
  9095. // make sure we use local custom command when remote are not supported
  9096. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9097. {
  9098. Command = FLastCustomCommand;
  9099. }
  9100. else
  9101. {
  9102. Command.Params = Command.Params | ccLocal;
  9103. }
  9104. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9105. FEditingFocusedAdHocCommand = OnFocused;
  9106. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9107. int Options =
  9108. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9109. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9110. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9111. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9112. {
  9113. FLastCustomCommand = Command;
  9114. UpdateCustomCommandsToolbar();
  9115. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9116. }
  9117. }
  9118. //---------------------------------------------------------------------------
  9119. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9120. {
  9121. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9122. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9123. DebugAssert(State > 0);
  9124. if (State <= 0)
  9125. {
  9126. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9127. }
  9128. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9129. }
  9130. //---------------------------------------------------------------------------
  9131. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9132. TCustomCommandType & Command, int & State)
  9133. {
  9134. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9135. if (Result)
  9136. {
  9137. Command = FLastCustomCommand;
  9138. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9139. }
  9140. return Result;
  9141. }
  9142. //---------------------------------------------------------------------------
  9143. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9144. {
  9145. ResetIncrementalSearch();
  9146. }
  9147. //---------------------------------------------------------------------------
  9148. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9149. {
  9150. DebugAssert(ComponentVisible[Component]);
  9151. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9152. }
  9153. //---------------------------------------------------------------------------
  9154. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9155. {
  9156. // when queue panel is resized here directly, the status bar is stretched
  9157. // over whole space the panel occupied
  9158. PostComponentHide(fcQueueView);
  9159. }
  9160. //---------------------------------------------------------------------------
  9161. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9162. {
  9163. ComponentVisible[fcQueueFileList] = false;
  9164. }
  9165. //---------------------------------------------------------------------------
  9166. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9167. {
  9168. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9169. RefreshColorMode();
  9170. ResetSysDarkTheme();
  9171. ConfigurationChanged();
  9172. ConfigureInterface();
  9173. // Should be called for all controls
  9174. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  9175. }
  9176. //---------------------------------------------------------------------------
  9177. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9178. {
  9179. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9180. if (!FInvalid &&
  9181. (Message.LParam != 0) &&
  9182. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9183. {
  9184. ThemeChanged();
  9185. }
  9186. TForm::Dispatch(&Message);
  9187. }
  9188. //---------------------------------------------------------------------------
  9189. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9190. {
  9191. TMessage * M = static_cast<TMessage*>(Message);
  9192. switch (M->Msg)
  9193. {
  9194. case CM_DIALOGCHAR:
  9195. CMDialogChar(*M);
  9196. break;
  9197. case WM_APPCOMMAND:
  9198. WMAppCommand(*M);
  9199. break;
  9200. case WM_SYSCOMMAND:
  9201. WMSysCommand(*M);
  9202. break;
  9203. case WM_QUERYENDSESSION:
  9204. WMQueryEndSession(*M);
  9205. break;
  9206. case WM_ENDSESSION:
  9207. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9208. break;
  9209. #ifdef _DEBUG
  9210. case WM_WINDOWPOSCHANGED:
  9211. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9212. break;
  9213. case CM_CUSTOMSTYLECHANGED:
  9214. TForm::Dispatch(Message);
  9215. break;
  9216. #endif
  9217. case WM_COMPONENT_HIDE:
  9218. {
  9219. Byte Component = static_cast<Byte>(M->WParam);
  9220. // sanity check
  9221. if (ComponentVisible[Component])
  9222. {
  9223. // special treatment
  9224. if (Component == fcQueueView)
  9225. {
  9226. ToggleQueueVisibility();
  9227. DebugAssert(!ComponentVisible[fcQueueView]);
  9228. }
  9229. else
  9230. {
  9231. ComponentVisible[Component] = false;
  9232. }
  9233. }
  9234. }
  9235. break;
  9236. case WM_COPYDATA:
  9237. WMCopyData(*M);
  9238. break;
  9239. case WM_MANAGES_CAPTION:
  9240. // caption managed in TTerminalManager::UpdateAppTitle()
  9241. M->Result = 1;
  9242. break;
  9243. case WM_WANTS_MOUSEWHEEL:
  9244. M->Result = 1;
  9245. break;
  9246. case CM_SHOWINGCHANGED:
  9247. CMShowingChanged(*M);
  9248. break;
  9249. case WM_CLOSE:
  9250. WMClose(*M);
  9251. break;
  9252. case WM_DPICHANGED:
  9253. WMDpiChanged(*M);
  9254. break;
  9255. case CM_DPICHANGED:
  9256. CMDpiChanged(*M);
  9257. break;
  9258. case WM_SETTINGCHANGE:
  9259. WMSettingChange(*M);
  9260. break;
  9261. case CM_DIALOGKEY:
  9262. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9263. break;
  9264. case WM_PASTE_FILES:
  9265. PasteFiles();
  9266. break;
  9267. case WM_IS_HIDDEN:
  9268. // To treat master password prompt as a main window while showing it when workspace is loading while
  9269. // the exporer is showing up (Visible is true already)
  9270. M->Result = !FShowing;
  9271. break;
  9272. case WM_SHOWWINDOW:
  9273. if (M->WParam)
  9274. {
  9275. AddStartupSequence(L"J");
  9276. }
  9277. TForm::Dispatch(Message);
  9278. break;
  9279. case WM_QUEUE_CALLBACK:
  9280. WMQueueCallback(*M);
  9281. break;
  9282. default:
  9283. TForm::Dispatch(Message);
  9284. break;
  9285. }
  9286. }
  9287. //---------------------------------------------------------------------------
  9288. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9289. {
  9290. // noop
  9291. }
  9292. //---------------------------------------------------------------------------
  9293. void TCustomScpExplorerForm::RegenerateSessionColorsImageList()
  9294. {
  9295. FSessionColors->Clear();
  9296. AddFixedSessionImages();
  9297. ::RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9298. UpdateImages();
  9299. }
  9300. //---------------------------------------------------------------------------
  9301. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  9302. {
  9303. TForm::Dispatch(&Message);
  9304. RegenerateSessionColorsImageList();
  9305. }
  9306. //---------------------------------------------------------------------------
  9307. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9308. {
  9309. TForm::Dispatch(&Message);
  9310. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9311. UpdatePixelsPerInchMainWindowCounter();
  9312. }
  9313. //---------------------------------------------------------------------------
  9314. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9315. {
  9316. AppLog(L"Main window WM_CLOSE");
  9317. // Cannot close window while we are busy.
  9318. // We cannot test this in FormCloseQuery as that is called also from
  9319. // Close(), which is called by CloseApplicationAction. So we can be busy
  9320. // there already even, when it is legitimate to close the application.
  9321. // Possibly a better place to handle this would be WMSysCommand.
  9322. if (NonVisualDataModule->Busy)
  9323. {
  9324. Message.Result = 1;
  9325. }
  9326. else
  9327. {
  9328. TForm::Dispatch(&Message);
  9329. }
  9330. }
  9331. //---------------------------------------------------------------------------
  9332. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9333. {
  9334. if (!FShowingChanged)
  9335. {
  9336. AddStartupSequence(L"D");
  9337. FShowingChanged = true;
  9338. }
  9339. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9340. bool NoSession = (ManagedSession == NULL);
  9341. // This calls TCustomScpExplorerForm::DoShow
  9342. TForm::Dispatch(&Message);
  9343. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9344. if (Showing && !FStarted)
  9345. {
  9346. FStarted = true;
  9347. InterfaceStarted();
  9348. }
  9349. if (Showing && NoSession)
  9350. {
  9351. // When we are starting minimized (i.e. from an installer),
  9352. // postpone showing Login dialog until we get restored.
  9353. // Otherwise the Login dialog (and Authentication window) show restored
  9354. // over invisible (minimized) main window.
  9355. if (WindowState == wsMinimized)
  9356. {
  9357. FNeedSession = true;
  9358. }
  9359. else
  9360. {
  9361. // This happens before application ever goes idle, so the toolbars would
  9362. // stay enabled (initial state) until the Login dialog is dismissed.
  9363. UpdateActions();
  9364. NonVisualDataModule->StartBusy();
  9365. try
  9366. {
  9367. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9368. // otherwise the dialog does not receive focus.
  9369. // With Commander interface the ProcessMessages is called already
  9370. // by TDriveView, but with Explorer interface, we need to call it explicily
  9371. Application->ProcessMessages();
  9372. // do not reload sessions, they have been loaded just now (optimization)
  9373. NeedSession(true);
  9374. }
  9375. __finally
  9376. {
  9377. NonVisualDataModule->EndBusy();
  9378. }
  9379. }
  9380. }
  9381. }
  9382. //---------------------------------------------------------------------------
  9383. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9384. {
  9385. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9386. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9387. }
  9388. //---------------------------------------------------------------------------
  9389. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9390. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9391. int & MaxHeight)
  9392. {
  9393. // workaround for bug in TWinControl.CalcConstraints
  9394. // Check for empty rect (restore from iconic state) is done there only after
  9395. // call to AdjustClientRect, which enlarges the rect (for forms).
  9396. TRect R = GetClientRect();
  9397. // when restoring from iconic state, place no restrictions
  9398. if (IsRectEmpty(R))
  9399. {
  9400. MinWidth = 0;
  9401. MinHeight = 0;
  9402. MaxWidth = 32000;
  9403. MaxHeight = 32000;
  9404. }
  9405. }
  9406. //---------------------------------------------------------------------------
  9407. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9408. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9409. {
  9410. // terminal can be already closed (e.g. dropped connection)
  9411. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9412. {
  9413. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9414. try
  9415. {
  9416. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9417. }
  9418. catch(...)
  9419. {
  9420. if (!Terminal->Active)
  9421. {
  9422. Close = true;
  9423. }
  9424. throw;
  9425. }
  9426. }
  9427. }
  9428. //---------------------------------------------------------------------------
  9429. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9430. {
  9431. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9432. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9433. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9434. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9435. {
  9436. OnGetSpaceAvailable = GetSpaceAvailable;
  9437. }
  9438. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9439. OnGetSpaceAvailable);
  9440. }
  9441. //---------------------------------------------------------------------------
  9442. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9443. {
  9444. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9445. Terminal->FillSessionDataForCode(Data.get());
  9446. return Data.release();
  9447. }
  9448. //---------------------------------------------------------------------------
  9449. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9450. {
  9451. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9452. DoGenerateUrlDialog(Data.get(), Paths);
  9453. }
  9454. //---------------------------------------------------------------------------
  9455. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9456. {
  9457. GenerateUrl(NULL);
  9458. }
  9459. //---------------------------------------------------------------------------
  9460. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9461. {
  9462. std::unique_ptr<TStrings> Paths(new TStringList());
  9463. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9464. GenerateUrl(Paths.get());
  9465. }
  9466. //---------------------------------------------------------------------------
  9467. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9468. {
  9469. FSessionColor = value;
  9470. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9471. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9472. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9473. DebugAssert(ColorItem != NULL);
  9474. ColorItem->Color = C;
  9475. NonVisualDataModule->ColorMenuItem->Color = C;
  9476. UpdateControls();
  9477. }
  9478. //---------------------------------------------------------------------------
  9479. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9480. {
  9481. if (value != FSessionColor)
  9482. {
  9483. UpdateSessionColor(value);
  9484. // Is null when called from LastTerminalClosed
  9485. if (Terminal != NULL)
  9486. {
  9487. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9488. }
  9489. }
  9490. }
  9491. //---------------------------------------------------------------------------
  9492. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9493. {
  9494. bool Result = FNoteTimer->Enabled;
  9495. if (Result)
  9496. {
  9497. // cannot cancel note too early
  9498. bool NotEarly =
  9499. (Now() - FNoteShown >
  9500. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9501. if (Force || NotEarly)
  9502. {
  9503. FNoteTimer->Enabled = false;
  9504. FNote = L"";
  9505. SAFE_DESTROY(FNoteData);
  9506. FOnNoteClick = NULL;
  9507. FNoteHints = FNotes->Text;
  9508. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9509. UpdateStatusBar();
  9510. }
  9511. }
  9512. return Result;
  9513. }
  9514. //---------------------------------------------------------------------------
  9515. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9516. {
  9517. DebugAssert(FNoteTimer->Enabled);
  9518. CancelNote(true);
  9519. }
  9520. //---------------------------------------------------------------------------
  9521. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9522. {
  9523. FNoteHints = FNotes->Text.TrimRight();
  9524. }
  9525. //---------------------------------------------------------------------------
  9526. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9527. {
  9528. int P = Note.Pos(L"\n");
  9529. if (P > 0)
  9530. {
  9531. Note.SetLength(P - 1);
  9532. }
  9533. FNotes->Add(FORMAT(L"[%s] %s",
  9534. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9535. while (FNotes->Count > 10)
  9536. {
  9537. FNotes->Delete(0);
  9538. }
  9539. if (UpdateNow)
  9540. {
  9541. UpdateNoteHints();
  9542. UpdateStatusBar();
  9543. }
  9544. }
  9545. //---------------------------------------------------------------------------
  9546. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9547. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9548. {
  9549. int P = Note.Pos(L"\n");
  9550. if (P > 0)
  9551. {
  9552. Note.SetLength(P - 1);
  9553. }
  9554. UpdateNoteHints();
  9555. FNote = Note;
  9556. SAFE_DESTROY(FNoteData);
  9557. FNoteData = NoteData;
  9558. FOnNoteClick = OnNoteClick;
  9559. AddNote(Note, false);
  9560. UpdateStatusBar();
  9561. FNoteShown = Now();
  9562. FNoteTimer->Enabled = false;
  9563. if (Seconds == 0)
  9564. {
  9565. Seconds = WinConfiguration->NotificationsTimeout;
  9566. }
  9567. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9568. FNoteTimer->Enabled = true;
  9569. }
  9570. //---------------------------------------------------------------------------
  9571. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9572. {
  9573. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9574. }
  9575. //---------------------------------------------------------------------------
  9576. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9577. {
  9578. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9579. {
  9580. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9581. }
  9582. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9583. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9584. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9585. 0, NULL, NULL);
  9586. }
  9587. //---------------------------------------------------------------------------
  9588. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9589. {
  9590. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9591. UnicodeString Note =
  9592. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9593. PostNote(Note, 0, NULL, NULL);
  9594. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9595. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9596. }
  9597. //---------------------------------------------------------------------------
  9598. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9599. {
  9600. WinConfiguration->FormatSizeBytes = Style;
  9601. }
  9602. //---------------------------------------------------------------------------
  9603. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9604. {
  9605. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9606. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9607. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9608. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9609. }
  9610. //---------------------------------------------------------------------------
  9611. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9612. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9613. {
  9614. if (Panel->Index == 0)
  9615. {
  9616. if (FOnNoteClick != NULL)
  9617. {
  9618. // prevent the user data from being freed by possible call
  9619. // to CancelNote or PostNote during call to OnNoteClick
  9620. std::unique_ptr<TObject> NoteData(FNoteData);
  9621. TNotifyEvent OnNoteClick = FOnNoteClick;
  9622. FNoteData = NULL;
  9623. // need to cancel the note as we are going to delete its user data
  9624. CancelNote(true);
  9625. OnNoteClick(NoteData.get());
  9626. }
  9627. }
  9628. if (HasActiveTerminal() &&
  9629. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9630. {
  9631. FileSystemInfo();
  9632. }
  9633. }
  9634. //---------------------------------------------------------------------------
  9635. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9636. {
  9637. // workaround:
  9638. // 1) for unknown reason, disabling window, while minimized,
  9639. // prevents it from restoring, even if it was enabled again meanwhile
  9640. // 2) when disabling the main window, while another has focus
  9641. // minimize is no longer possible
  9642. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9643. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9644. // Shouldn't we use IsApplicationMinimized() here?
  9645. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9646. {
  9647. Enabled = false;
  9648. }
  9649. FLockLevel++;
  9650. }
  9651. //---------------------------------------------------------------------------
  9652. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9653. {
  9654. DebugAssert(FLockLevel > 0);
  9655. FLockLevel--;
  9656. if (FLockLevel == 0)
  9657. {
  9658. DebugAssert(FLockSuspendLevel == 0);
  9659. Enabled = true;
  9660. // VCL_COPY (TCustomForm.SetWindowFocus)
  9661. if (Active && (ActiveControl != NULL))
  9662. {
  9663. ::SetFocus(ActiveControl->Handle);
  9664. if (GetFocus() == ActiveControl->Handle)
  9665. {
  9666. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9667. }
  9668. }
  9669. }
  9670. }
  9671. //---------------------------------------------------------------------------
  9672. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9673. {
  9674. // We need to make sure that window is enabled when the last modal window closes
  9675. // otherwise focus is not restored correctly.
  9676. // So we re-enable the window when modal window opens and
  9677. // disable it back after is closes
  9678. if (FLockLevel > 0)
  9679. {
  9680. // while we have nesting counter, we know that we never be called
  9681. // recursivelly as Application->OnModalBegin is called only
  9682. // for the top-level modal window
  9683. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9684. {
  9685. // won't be disabled when conditions in LockWindow() were not satisfied
  9686. FDisabledOnLockSuspend = !Enabled;
  9687. // When minimized to tray (or actually when set to SW_HIDE),
  9688. // setting Enabled makes the window focusable even when there's
  9689. // modal window over it
  9690. if (!FTrayIcon->Visible)
  9691. {
  9692. Enabled = true;
  9693. }
  9694. }
  9695. FLockSuspendLevel++;
  9696. }
  9697. }
  9698. //---------------------------------------------------------------------------
  9699. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9700. {
  9701. if (FLockSuspendLevel > 0)
  9702. {
  9703. DebugAssert(FLockLevel > 0);
  9704. FLockSuspendLevel--;
  9705. // see comment in SuspendWindowLock
  9706. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9707. {
  9708. // Note that window can be enabled here, when we were minized to tray when
  9709. // was SuspendWindowLock() called.
  9710. // We should possibly do the same check as in LockWindow(),
  9711. // if it is ever possible that the consitions change between
  9712. // SuspendWindowLock() and ResumeWindowLock()
  9713. Enabled = !FDisabledOnLockSuspend;
  9714. }
  9715. }
  9716. }
  9717. //---------------------------------------------------------------------------
  9718. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9719. {
  9720. TTBXComboBoxItem * RemotePathComboBox =
  9721. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9722. if (!TextOnly)
  9723. {
  9724. TStrings * Items = RemotePathComboBox->Strings;
  9725. Items->BeginUpdate();
  9726. try
  9727. {
  9728. Items->Clear();
  9729. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9730. {
  9731. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9732. while (!IsUnixRootPath(APath))
  9733. {
  9734. int P = APath.LastDelimiter(L'/');
  9735. DebugAssert(P >= 0);
  9736. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9737. APath.SetLength(P - 1);
  9738. }
  9739. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9740. }
  9741. }
  9742. __finally
  9743. {
  9744. Items->EndUpdate();
  9745. }
  9746. }
  9747. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9748. // Setting ItemIndex to -1 does not reset its text
  9749. if (RemotePathComboBox->Strings->Count == 0)
  9750. {
  9751. RemotePathComboBox->Text = L"";
  9752. }
  9753. }
  9754. //---------------------------------------------------------------------------
  9755. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9756. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9757. {
  9758. if (AIndex < 0)
  9759. {
  9760. AIndex = Sender->ItemIndex;
  9761. }
  9762. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9763. }
  9764. //---------------------------------------------------------------------------
  9765. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9766. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9767. int & ImageIndex)
  9768. {
  9769. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9770. }
  9771. //---------------------------------------------------------------------------
  9772. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9773. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9774. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9775. {
  9776. if (!IsLocalBrowserMode())
  9777. {
  9778. ARect.Left += (10 * AIndex);
  9779. }
  9780. }
  9781. //---------------------------------------------------------------------------
  9782. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9783. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9784. {
  9785. AWidth += (10 * AIndex);
  9786. }
  9787. //---------------------------------------------------------------------------
  9788. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9789. {
  9790. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9791. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9792. int Index = RemotePathComboBox->ItemIndex;
  9793. while (Index < RemotePathComboBox->Strings->Count - 1)
  9794. {
  9795. APath = UnixExtractFileDir(APath);
  9796. Index++;
  9797. }
  9798. // VanDyke style paths
  9799. if (APath.IsEmpty())
  9800. {
  9801. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9802. APath = ROOTDIRECTORY;
  9803. }
  9804. if (RemoteDirView->Path != APath)
  9805. {
  9806. RemoteDirView->Path = APath;
  9807. }
  9808. }
  9809. //---------------------------------------------------------------------------
  9810. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9811. {
  9812. DoRemotePathComboBoxItemClick(Sender);
  9813. }
  9814. //---------------------------------------------------------------------------
  9815. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9816. {
  9817. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9818. DebugUsedParam(Sender);
  9819. UpdateRemotePathComboBox(true);
  9820. }
  9821. //---------------------------------------------------------------------------
  9822. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9823. {
  9824. DoRemotePathComboBoxCancel(Sender);
  9825. }
  9826. //---------------------------------------------------------------------------
  9827. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9828. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9829. {
  9830. ResetIncrementalSearch();
  9831. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9832. DebugAssert(DirView != NULL);
  9833. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9834. {
  9835. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9836. // OnEditing is called also from TCustomListView::CanEdit
  9837. if (Edit != NULL)
  9838. {
  9839. EditSelectBaseName(Edit);
  9840. }
  9841. }
  9842. }
  9843. //---------------------------------------------------------------------------
  9844. //---------------------------------------------------------------------------
  9845. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9846. {
  9847. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9848. Result->AutoDetectDnD = false;
  9849. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9850. Result->RenderDataOn = rdoEnterAndDropSync;
  9851. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9852. return Result;
  9853. }
  9854. //---------------------------------------------------------------------------
  9855. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9856. {
  9857. if (IsWin10Build(19041))
  9858. {
  9859. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9860. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9861. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9862. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9863. }
  9864. }
  9865. //---------------------------------------------------------------------------
  9866. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9867. {
  9868. TForm::CreateWnd();
  9869. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9870. UpdateDarkMode();
  9871. if (FSessionsDragDropFilesEx == NULL)
  9872. {
  9873. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9874. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9875. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9876. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9877. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9878. }
  9879. if (FQueueDragDropFilesEx == NULL)
  9880. {
  9881. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9882. // No need to set OnDragOver as we do not have any restrictions
  9883. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9884. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9885. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9886. }
  9887. }
  9888. //---------------------------------------------------------------------------
  9889. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9890. {
  9891. TForm::DestroyWnd();
  9892. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9893. FQueueDragDropFilesEx->DragDropControl = NULL;
  9894. }
  9895. //---------------------------------------------------------------------------
  9896. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9897. {
  9898. SideEnter(FCurrentSide);
  9899. FEverShown = true;
  9900. }
  9901. //---------------------------------------------------------------------------
  9902. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9903. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9904. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9905. {
  9906. if (!NonVisualDataModule->Busy)
  9907. {
  9908. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9909. Configuration->Usage->Inc(L"FileFinds");
  9910. LockWindow(true);
  9911. NonVisualDataModule->StartBusy();
  9912. WinConfiguration->LockedInterface = true;
  9913. try
  9914. {
  9915. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9916. }
  9917. __finally
  9918. {
  9919. WinConfiguration->LockedInterface = false;
  9920. NonVisualDataModule->EndBusy();
  9921. UnlockWindow();
  9922. }
  9923. }
  9924. }
  9925. //---------------------------------------------------------------------------
  9926. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9927. {
  9928. if (!NonVisualDataModule->Busy)
  9929. {
  9930. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9931. SetFocus();
  9932. RemoteDirView->Path = UnixExtractFilePath(Path);
  9933. UnicodeString FileName = UnixExtractFileName(Path);
  9934. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9935. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9936. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9937. if (Item == NULL)
  9938. {
  9939. ReloadDirectory(osRemote);
  9940. Item = RemoteDirView->FindFileItem(FileName);
  9941. }
  9942. if (Item != NULL)
  9943. {
  9944. RemoteDirView->ItemFocused = Item;
  9945. RemoteDirView->ItemFocused->MakeVisible(false);
  9946. RemoteDirView->SetFocus();
  9947. }
  9948. }
  9949. }
  9950. //---------------------------------------------------------------------------
  9951. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9952. {
  9953. bool Result = !NonVisualDataModule->Busy;
  9954. if (Result)
  9955. {
  9956. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9957. }
  9958. return Result;
  9959. }
  9960. //---------------------------------------------------------------------------
  9961. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9962. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9963. {
  9964. if (CanOperateOnFoundFiles(ATerminal))
  9965. {
  9966. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished, OnFileOperationFinished);
  9967. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9968. }
  9969. }
  9970. //---------------------------------------------------------------------------
  9971. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9972. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9973. {
  9974. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9975. }
  9976. //---------------------------------------------------------------------------
  9977. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9978. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9979. {
  9980. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9981. }
  9982. //---------------------------------------------------------------------------
  9983. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9984. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9985. {
  9986. if (CanOperateOnFoundFiles(ATerminal))
  9987. {
  9988. for (int Index = 0; Index < FileList->Count; Index++)
  9989. {
  9990. UnicodeString FileName = FileList->Strings[Index];
  9991. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9992. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9993. OnFileOperationFinished(osRemote, FileName, true);
  9994. }
  9995. }
  9996. }
  9997. //---------------------------------------------------------------------------
  9998. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9999. {
  10000. FFileFindTerminal = Terminal;
  10001. ShowFileFindDialog(
  10002. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  10003. DoDownloadFoundFiles, DoEditFoundFiles);
  10004. }
  10005. //---------------------------------------------------------------------------
  10006. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  10007. {
  10008. FTaskbarList = TaskbarList;
  10009. }
  10010. //---------------------------------------------------------------------------
  10011. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  10012. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  10013. {
  10014. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10015. if (Index >= 0)
  10016. {
  10017. if (Button == mbLeft)
  10018. {
  10019. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  10020. // If switching tab (switching session) takes long enough for user
  10021. // to actually release the button, "mouse down" is still raised,
  10022. // but we do not get "mouse up" event, so dragging is not cancelled,
  10023. // prevent that by not beginning dragging in the first place.
  10024. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  10025. if (IsKeyPressed(Key))
  10026. {
  10027. // when user clicks the "+", we get mouse down only after the session
  10028. // is closed, when new session tab is already on X:Y, so dragging
  10029. // starts, prevent that
  10030. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  10031. {
  10032. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10033. if (Terminal != NULL)
  10034. {
  10035. SessionsPageControl->BeginDrag(false);
  10036. }
  10037. }
  10038. }
  10039. }
  10040. else if (Button == mbMiddle)
  10041. {
  10042. // ignore middle-click for "New session tab" and the last local-local tab
  10043. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10044. if ((Session != NULL) && CanCloseSession(Session))
  10045. {
  10046. CloseSessionTab(Index);
  10047. }
  10048. }
  10049. }
  10050. }
  10051. //---------------------------------------------------------------------------
  10052. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10053. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10054. {
  10055. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10056. // do not allow dropping on the "+" tab
  10057. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10058. if ((TargetTerminal != NULL) &&
  10059. (SessionsPageControl->ActivePage->PageIndex != Index))
  10060. {
  10061. Configuration->Usage->Inc(L"SessionTabMoves");
  10062. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10063. // but we want to actually prevent that to avoid flicker
  10064. SessionsPageControl->ActivePage->PageIndex = Index;
  10065. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10066. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10067. }
  10068. }
  10069. //---------------------------------------------------------------------------
  10070. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10071. TObject * Sender, TObject * Source, int X, int Y,
  10072. TDragState /*State*/, bool & Accept)
  10073. {
  10074. Accept = (Sender == Source);
  10075. if (Accept)
  10076. {
  10077. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10078. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10079. // do not allow dragging to the "+" tab
  10080. Accept = (Terminal != NULL);
  10081. }
  10082. }
  10083. //---------------------------------------------------------------------------
  10084. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10085. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10086. {
  10087. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10088. if (Index < 0)
  10089. {
  10090. Effect = DROPEFFECT_NONE;
  10091. }
  10092. else
  10093. {
  10094. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10095. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10096. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10097. {
  10098. Effect = DROPEFFECT_NONE;
  10099. }
  10100. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10101. {
  10102. Effect = DROPEFFECT_COPY;
  10103. }
  10104. }
  10105. }
  10106. //---------------------------------------------------------------------------
  10107. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10108. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10109. {
  10110. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10111. // do not allow dropping on local-local, disconnected and the "+" tab
  10112. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10113. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10114. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10115. {
  10116. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10117. if (!IsFileControl(DropSourceControl, osRemote))
  10118. {
  10119. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10120. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10121. // Why don't we use Terminal->CurrentDirectory directly?
  10122. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10123. // do not force queue, drag drop
  10124. false, true);
  10125. }
  10126. }
  10127. }
  10128. //---------------------------------------------------------------------------
  10129. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10130. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10131. {
  10132. // Downloads are handled in RemoteFileControlDDEnd
  10133. if (!IsFileControl(DropSourceControl, osRemote))
  10134. {
  10135. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10136. Terminal->CurrentDirectory,
  10137. // force queue, drag drop
  10138. true, true);
  10139. }
  10140. }
  10141. //---------------------------------------------------------------------------
  10142. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10143. {
  10144. FShowing = false;
  10145. // Do not save empty workspace
  10146. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10147. {
  10148. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10149. UnicodeString Name = WorkspaceName();
  10150. DoSaveWorkspace(
  10151. Name, DataList.get(),
  10152. !Configuration->DisablePasswordStoring &&
  10153. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10154. WinConfiguration->LastStoredSession = Name;
  10155. }
  10156. AppLog(L"Closing main window");
  10157. }
  10158. //---------------------------------------------------------------------------
  10159. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10160. {
  10161. TManagedTerminal * ManagedTerminal =
  10162. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10163. if (ManagedTerminal != NULL)
  10164. {
  10165. ManagedTerminal->DirectoryLoaded = Now();
  10166. }
  10167. }
  10168. //---------------------------------------------------------------------------
  10169. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10170. TListItem * /*Item*/, bool /*Selected*/)
  10171. {
  10172. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10173. switch (DirView->LastSelectMethod)
  10174. {
  10175. case smKeyboard:
  10176. Configuration->Usage->Inc(L"KeyboardSelections");
  10177. break;
  10178. case smMouse:
  10179. Configuration->Usage->Inc(L"MouseSelections");
  10180. break;
  10181. }
  10182. }
  10183. //---------------------------------------------------------------------------
  10184. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10185. {
  10186. if (Color != 0)
  10187. {
  10188. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10189. }
  10190. else
  10191. {
  10192. return FSessionTabImageIndex;
  10193. }
  10194. }
  10195. //---------------------------------------------------------------------------
  10196. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10197. {
  10198. TPngImageCollectionItem * Item =
  10199. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10200. FSessionColors->AddPng(Item->PngImage);
  10201. return FSessionColors->Count - 1;
  10202. }
  10203. //---------------------------------------------------------------------------
  10204. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10205. {
  10206. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10207. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10208. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10209. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10210. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10211. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10212. }
  10213. //---------------------------------------------------------------------------
  10214. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10215. {
  10216. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10217. }
  10218. //---------------------------------------------------------------------------
  10219. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10220. {
  10221. switch (Side)
  10222. {
  10223. case osLocal:
  10224. return FNewLocalTabTabImageIndex;
  10225. case osRemote:
  10226. case osCurrent:
  10227. return FNewRemoteTabTabImageIndex;
  10228. default:
  10229. DebugFail();
  10230. return -1;
  10231. }
  10232. }
  10233. //---------------------------------------------------------------------------
  10234. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10235. {
  10236. for (int Index = 0; Index < Control->ControlCount; Index++)
  10237. {
  10238. TControl * AControl = Control->Controls[Index];
  10239. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10240. if (WinControl != NULL)
  10241. {
  10242. CollectItemsWithTextDisplayMode(WinControl);
  10243. }
  10244. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10245. if (Toolbar != NULL)
  10246. {
  10247. // we care for top-level items only
  10248. TTBCustomItem * Items = Toolbar->Items;
  10249. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10250. {
  10251. TTBCustomItem * Item = Items->Items[ItemIndex];
  10252. if (((Item->DisplayMode == nbdmImageAndText) ||
  10253. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10254. EligibleForImageDisplayMode(Item))
  10255. {
  10256. FItemsWithTextDisplayMode.insert(Item);
  10257. }
  10258. }
  10259. }
  10260. }
  10261. }
  10262. //---------------------------------------------------------------------------
  10263. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10264. {
  10265. return true;
  10266. }
  10267. //---------------------------------------------------------------------------
  10268. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10269. {
  10270. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10271. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10272. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10273. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10274. bool Result = true;
  10275. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10276. {
  10277. TTBCustomItem * Item = *i;
  10278. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10279. if (Label != NULL)
  10280. {
  10281. // optimization
  10282. if (Label->Visible == SelectiveToolbarText)
  10283. {
  10284. Result = false;
  10285. }
  10286. else
  10287. {
  10288. Label->Visible = SelectiveToolbarText;
  10289. }
  10290. }
  10291. else
  10292. {
  10293. // optimization
  10294. if (Item->DisplayMode == DisplayMode)
  10295. {
  10296. Result = false;
  10297. }
  10298. else
  10299. {
  10300. Item->DisplayMode = DisplayMode;
  10301. }
  10302. }
  10303. ++i;
  10304. }
  10305. UpdateNewTabTab();
  10306. return Result;
  10307. }
  10308. //---------------------------------------------------------------------------
  10309. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10310. {
  10311. DebugFail();
  10312. }
  10313. //---------------------------------------------------------------------------
  10314. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10315. {
  10316. // Among other, a lock level is non zero, while directory is being loaded,
  10317. // even when it happens as a result of dirview navigation,
  10318. // i.e. when TNonVisualDataModule is NOT FBusy.
  10319. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10320. // Among other this prevents a panel auto update to occur while
  10321. // directory is changing.
  10322. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10323. }
  10324. //---------------------------------------------------------------------------
  10325. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10326. {
  10327. // While the window is disabled, we still seem to process menu shortcuts at least,
  10328. // so stop it at least here.
  10329. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10330. bool Result;
  10331. if (Allowed == aaUpdate)
  10332. {
  10333. Result = true;
  10334. }
  10335. else
  10336. {
  10337. Result = !NonVisualDataModule->Busy;
  10338. if (Result && (Allowed == aaShortCut))
  10339. {
  10340. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10341. Action->Update();
  10342. Result = Action->Enabled;
  10343. }
  10344. }
  10345. return Result;
  10346. }
  10347. //---------------------------------------------------------------------------
  10348. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10349. {
  10350. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10351. }
  10352. //---------------------------------------------------------------------------
  10353. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10354. {
  10355. // This is somewhat redundant to LockWindow() call from
  10356. // TTerminalManager::TerminalReadDirectoryProgress.
  10357. // But disabling window is known not to block keyboard shorcuts
  10358. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10359. if (Busy > 0)
  10360. {
  10361. if (NonVisualDataModule->Busy)
  10362. {
  10363. State = false;
  10364. }
  10365. else
  10366. {
  10367. NonVisualDataModule->StartBusy();
  10368. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10369. LockWindow();
  10370. }
  10371. }
  10372. else if (Busy < 0)
  10373. {
  10374. UnlockWindow();
  10375. NonVisualDataModule->EndBusy();
  10376. }
  10377. else
  10378. {
  10379. State = NonVisualDataModule->Busy;
  10380. }
  10381. }
  10382. //---------------------------------------------------------------------------
  10383. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10384. {
  10385. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10386. if (Index >= 0)
  10387. {
  10388. TPopupMenu * PopupMenu = NULL;
  10389. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10390. if (Session != NULL)
  10391. {
  10392. SessionsPageControl->ActivePageIndex = Index;
  10393. if (DebugAlwaysTrue(SessionTabSwitched()))
  10394. {
  10395. // copied from TControl.WMContextMenu
  10396. SendCancelMode(SessionsPageControl);
  10397. // explicit popup instead of using PopupMenu property
  10398. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10399. // while connecting yet not-connected session and hence
  10400. // allowing an access to commands over not-completely connected session
  10401. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10402. }
  10403. }
  10404. else
  10405. {
  10406. if (SupportsLocalBrowser())
  10407. {
  10408. PopupMenu = NonVisualDataModule->NewTabPopup;
  10409. }
  10410. }
  10411. if (PopupMenu != NULL)
  10412. {
  10413. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10414. PopupMenu->PopupComponent = SessionsPageControl;
  10415. PopupMenu->Popup(Point.x, Point.y);
  10416. }
  10417. }
  10418. Handled = true;
  10419. }
  10420. //---------------------------------------------------------------------------
  10421. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10422. {
  10423. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10424. }
  10425. //---------------------------------------------------------------------------
  10426. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10427. {
  10428. Configuration->Usage->Inc(L"PasswordChanges");
  10429. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10430. ChangePasswordData->DisableAuthentationsExceptPassword();
  10431. ChangePasswordData->ChangePassword = true;
  10432. std::unique_ptr<TTerminal> ChangePasswordSession(
  10433. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10434. ChangePasswordSession->AutoReadDirectory = false;
  10435. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10436. {
  10437. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10438. }
  10439. else
  10440. {
  10441. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10442. }
  10443. }
  10444. //---------------------------------------------------------------------------
  10445. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10446. {
  10447. // No nice way to assert SSH2
  10448. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10449. }
  10450. //---------------------------------------------------------------------------
  10451. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10452. {
  10453. TOperationVisualizer OperationVisualizer;
  10454. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10455. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10456. }
  10457. //---------------------------------------------------------------------------
  10458. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10459. {
  10460. TForm::ChangeScale(M, D);
  10461. int APixelsPerInch = GetControlPixelsPerInch(this);
  10462. GlyphsModule->PixelsPerInch = APixelsPerInch;
  10463. }
  10464. //---------------------------------------------------------------------------
  10465. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10466. {
  10467. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10468. }
  10469. //---------------------------------------------------------------------
  10470. class TPublicControl : public TControl
  10471. {
  10472. friend class TCustomScpExplorerForm;
  10473. };
  10474. //---------------------------------------------------------------------------
  10475. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10476. {
  10477. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10478. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10479. }
  10480. //---------------------------------------------------------------------------
  10481. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10482. {
  10483. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10484. OpenBookmark(Side, Bookmark);
  10485. }
  10486. //---------------------------------------------------------------------------
  10487. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10488. {
  10489. DoBookmarkClick(osLocal, Sender);
  10490. }
  10491. //---------------------------------------------------------------------------
  10492. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10493. {
  10494. DoBookmarkClick(osRemote, Sender);
  10495. }
  10496. //---------------------------------------------------------------------------
  10497. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10498. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10499. {
  10500. if (BookmarkList != NULL)
  10501. {
  10502. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10503. if (IsLocalBrowserMode())
  10504. {
  10505. Side = osLocal;
  10506. }
  10507. if (!WinConfiguration->UseLocationProfiles)
  10508. {
  10509. std::unique_ptr<TStringList> Directories(new TStringList());
  10510. Directories->CaseSensitive = (Side == osRemote);
  10511. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10512. {
  10513. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10514. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10515. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10516. {
  10517. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10518. Item->Caption = EscapeHotkey(Directory);
  10519. Item->ShortCut = Bookmark->ShortCut;
  10520. Item->OnClick = OnBookmarkClick;
  10521. Item->Tag = reinterpret_cast<int>(Bookmark);
  10522. Directories->Add(Directory);
  10523. Menu->Add(Item.release());
  10524. }
  10525. }
  10526. }
  10527. else
  10528. {
  10529. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10530. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10531. {
  10532. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10533. if (!Bookmark->Node.IsEmpty())
  10534. {
  10535. Folders->Add(Bookmark->Node);
  10536. }
  10537. }
  10538. for (int Index = 0; Index < Folders->Count; Index++)
  10539. {
  10540. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10541. Item->Caption = Folders->Strings[Index];
  10542. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10543. Folders->Objects[Index] = Item.get();
  10544. Menu->Add(Item.release());
  10545. }
  10546. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10547. {
  10548. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10549. TTBCustomItem * Parent;
  10550. if (!Bookmark->Node.IsEmpty())
  10551. {
  10552. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10553. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10554. }
  10555. else
  10556. {
  10557. Parent = Menu;
  10558. }
  10559. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10560. Item->Caption = Bookmark->Name;
  10561. Item->ShortCut = Bookmark->ShortCut;
  10562. Item->OnClick = OnBookmarkClick;
  10563. Item->Tag = reinterpret_cast<int>(Bookmark);
  10564. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10565. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10566. {
  10567. // No hint for location profiles that are actually mere "bookmarks"
  10568. }
  10569. else
  10570. {
  10571. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10572. UnicodeString LongHint;
  10573. if (!Bookmark->Local.IsEmpty())
  10574. {
  10575. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10576. }
  10577. if (!Bookmark->Remote.IsEmpty())
  10578. {
  10579. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10580. }
  10581. AddToList(Hint, LongHint, L"|");
  10582. Item->Hint = Hint;
  10583. }
  10584. Parent->Add(Item.release());
  10585. }
  10586. }
  10587. AddMenuSeparator(Menu);
  10588. }
  10589. }
  10590. //---------------------------------------------------------------------------
  10591. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10592. {
  10593. Menu->Clear();
  10594. std::unique_ptr<TTBCustomItem> Item;
  10595. Item.reset(new TTBXItem(Owner));
  10596. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10597. Item->Options = Item->Options << tboDefault;
  10598. Menu->Add(Item.release());
  10599. AddMenuSeparator(Menu);
  10600. if (Terminal != NULL)
  10601. {
  10602. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10603. }
  10604. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10605. Item.reset(new TTBXItem(Owner));
  10606. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10607. Menu->Add(Item.release());
  10608. }
  10609. //---------------------------------------------------------------------------
  10610. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10611. {
  10612. bool Result = true;
  10613. bool Remote = !IsSideLocalBrowser(Side);
  10614. try
  10615. {
  10616. UnicodeString APath = Path;
  10617. if (Remote)
  10618. {
  10619. Terminal->ExceptionOnFail = true;
  10620. }
  10621. else
  10622. {
  10623. APath = ExpandEnvironmentVariables(Path);
  10624. }
  10625. try
  10626. {
  10627. DirView(Side)->Path = APath;
  10628. }
  10629. __finally
  10630. {
  10631. if (Remote)
  10632. {
  10633. Terminal->ExceptionOnFail = false;
  10634. }
  10635. }
  10636. }
  10637. catch (Exception & E)
  10638. {
  10639. if (!Remote || Terminal->Active)
  10640. {
  10641. ShowExtendedExceptionEx(Terminal, &E);
  10642. Result = false;
  10643. }
  10644. else
  10645. {
  10646. throw;
  10647. }
  10648. }
  10649. return Result;
  10650. }
  10651. //---------------------------------------------------------------------------
  10652. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10653. {
  10654. // Make sure there some feedback even when loading tiny local folders
  10655. TInstantOperationVisualizer Visualizer;
  10656. DirView(Side)->ReloadDirectory();
  10657. }
  10658. //---------------------------------------------------------------------------
  10659. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10660. {
  10661. if (Index == SessionsPageControl->TabIndex)
  10662. {
  10663. CloseTab();
  10664. }
  10665. else
  10666. {
  10667. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10668. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10669. TTerminalManager * Manager = TTerminalManager::Instance();
  10670. if (!Terminal->Active)
  10671. {
  10672. Manager->FreeTerminal(Terminal);
  10673. }
  10674. else
  10675. {
  10676. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10677. if (CanCloseQueue(Queue))
  10678. {
  10679. Manager->FreeTerminal(Terminal);
  10680. }
  10681. }
  10682. }
  10683. }
  10684. //---------------------------------------------------------------------------
  10685. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10686. {
  10687. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10688. if (Session == NULL)
  10689. {
  10690. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10691. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10692. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10693. //P = SessionsPageControl->ClientToScreen(P);
  10694. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10695. }
  10696. else
  10697. {
  10698. CloseSessionTab(Index);
  10699. }
  10700. }
  10701. //---------------------------------------------------------------------------
  10702. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10703. {
  10704. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10705. {
  10706. TInstantOperationVisualizer Visualizer;
  10707. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10708. // before we create a new data object
  10709. ClipboardClear();
  10710. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10711. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10712. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10713. // Intermediate variable to WORKAROUND a crash in compiler
  10714. TObjectList * ClipboardFakeMonitors =
  10715. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10716. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10717. if (FClipboardDragDropFilesEx.get() == NULL)
  10718. {
  10719. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10720. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10721. }
  10722. FClipboardDragDropFilesEx->FileList->Clear();
  10723. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10724. FClipboardDragDropFilesEx->CopyToClipboard();
  10725. FClipboardTerminal = Terminal;
  10726. // Need full paths, as cwd can be different once files are pasted
  10727. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10728. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10729. {
  10730. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10731. }
  10732. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10733. }
  10734. }
  10735. //---------------------------------------------------------------------------
  10736. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10737. {
  10738. if (OpenClipboard(0))
  10739. {
  10740. AppLog(L"Clearing clipboard");
  10741. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10742. CloseClipboard();
  10743. }
  10744. }
  10745. //---------------------------------------------------------------------------
  10746. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10747. {
  10748. return !FClipboardFakeDirectory.IsEmpty();
  10749. }
  10750. //---------------------------------------------------------------------------
  10751. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10752. {
  10753. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10754. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10755. FClipboardFakeDirectory = UnicodeString();
  10756. FClipboardTerminal = NULL;
  10757. if (FDownloadingFromClipboard)
  10758. {
  10759. // We are called by the monitor, so attempt to release it would deadlock
  10760. FClipboardFakeMonitorsPendingReset = true;
  10761. }
  10762. else
  10763. {
  10764. FClipboardFakeMonitors.reset(NULL);
  10765. }
  10766. }
  10767. //---------------------------------------------------------------------------
  10768. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10769. {
  10770. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10771. {
  10772. ClipboardStop();
  10773. }
  10774. }
  10775. //---------------------------------------------------------------------------
  10776. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10777. {
  10778. TTerminalManager * Manager = TTerminalManager::Instance();
  10779. Manager->ActiveSession = FClipboardTerminal;
  10780. TTransferOperationParam Params;
  10781. Params.TargetDirectory = TargetDirectory;
  10782. Params.DragDrop = DragDrop;
  10783. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10784. }
  10785. //---------------------------------------------------------------------------
  10786. void TCustomScpExplorerForm::PasteFiles()
  10787. {
  10788. // Guard against possible race conditions
  10789. if (!FClipboardPasteTarget.IsEmpty())
  10790. {
  10791. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10792. UnicodeString Target = FClipboardPasteTarget;
  10793. FClipboardPasteTarget = EmptyStr;
  10794. // Can fail as it can be e.g. locked by AV, so we retry that later
  10795. bool Removed = RemoveDir(ApiPath(Target));
  10796. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10797. try
  10798. {
  10799. if (NonVisualDataModule->Busy)
  10800. {
  10801. AppLog(L"Is busy, cannot paste");
  10802. }
  10803. else
  10804. {
  10805. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10806. FClipboardFakeMonitorsPendingReset = false;
  10807. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10808. TAutoFlag Flag(FDownloadingFromClipboard);
  10809. AppLog(L"Downloading to paste target...");
  10810. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10811. AppLog(L"Downloaded to paste target...");
  10812. }
  10813. }
  10814. __finally
  10815. {
  10816. if (!Removed)
  10817. {
  10818. Removed = RemoveDir(ApiPath(Target));
  10819. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10820. }
  10821. }
  10822. }
  10823. }
  10824. //---------------------------------------------------------------------------
  10825. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10826. {
  10827. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10828. // (as it pumps a Windows message queue while being shutted down)
  10829. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10830. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10831. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10832. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10833. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10834. {
  10835. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10836. FClipboardPasteTarget = FileName;
  10837. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10838. // Postponing removing (or actually whole pasting operation) seems to help.
  10839. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10840. }
  10841. }
  10842. //---------------------------------------------------------------------------
  10843. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10844. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10845. {
  10846. TFileMasks::TParams MaskParams;
  10847. MaskParams.Size = Size;
  10848. MaskParams.Modification = Modification;
  10849. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10850. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10851. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10852. if (!Local && Directory)
  10853. {
  10854. FileName = UnixExcludeTrailingBackslash(FileName);
  10855. }
  10856. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10857. {
  10858. bool ImplicitMatch;
  10859. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10860. !ImplicitMatch)
  10861. {
  10862. Color = Iter->Color;
  10863. break;
  10864. }
  10865. }
  10866. }
  10867. //---------------------------------------------------------------------------
  10868. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10869. {
  10870. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10871. if (!DirView->IsEditing())
  10872. {
  10873. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10874. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10875. // while searching
  10876. if (Key == VK_BACK)
  10877. {
  10878. if (FIncrementalSearchState.Searching)
  10879. {
  10880. if (FIncrementalSearchState.Text.Length() <= 1)
  10881. {
  10882. ResetIncrementalSearch();
  10883. }
  10884. else
  10885. {
  10886. UnicodeString NewText = LeftStr(FIncrementalSearchState.Text, FIncrementalSearchState.Text.Length() - 1);
  10887. IncrementalSearch(NewText, false, false);
  10888. }
  10889. Key = 0;
  10890. }
  10891. }
  10892. }
  10893. }
  10894. //---------------------------------------------------------------------------
  10895. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10896. {
  10897. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10898. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10899. {
  10900. // Filter control sequences.
  10901. // When not searching yet, prefer use of the space for toggling file selection
  10902. // (so we cannot incrementally search for a string starting with a space).
  10903. if ((Key > VK_SPACE) ||
  10904. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearchState.Searching))
  10905. {
  10906. IncrementalSearch(FIncrementalSearchState.Text + Key, false, false);
  10907. Key = 0;
  10908. }
  10909. }
  10910. }
  10911. //---------------------------------------------------------------------------
  10912. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10913. {
  10914. if (FIncrementalSearchState.Searching)
  10915. {
  10916. FIncrementalSearchState.Reset();
  10917. DirView(osCurrent)->UpdateStatusBar();
  10918. }
  10919. }
  10920. //---------------------------------------------------------------------------
  10921. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10922. {
  10923. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10924. if (Item == NULL)
  10925. {
  10926. MessageBeep(MB_ICONHAND);
  10927. }
  10928. else
  10929. {
  10930. TCustomDirView * ADirView = DirView(osCurrent);
  10931. {
  10932. TAutoNestingCounter Guard(FIncrementalSearching);
  10933. ADirView->FocusItem(Item);
  10934. if (ADirView->NortonLike == nlOff)
  10935. {
  10936. if ((ADirView->Selected != Item) ||
  10937. (ADirView->SelCount > 1))
  10938. {
  10939. ADirView->ClearSelection();
  10940. ADirView->Selected = Item;
  10941. }
  10942. }
  10943. }
  10944. FIncrementalSearchState.Searching = true;
  10945. FIncrementalSearchState.Text = Text;
  10946. Item->MakeVisible(false);
  10947. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10948. FIncrementalSearchState.HaveNext = (NextItem != NULL) && (NextItem != Item);
  10949. ADirView->UpdateStatusBar();
  10950. }
  10951. }
  10952. //---------------------------------------------------------------------------
  10953. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  10954. {
  10955. int Index = Item->Index;
  10956. if (!Reverse)
  10957. {
  10958. Index++;
  10959. if (Index >= Item->Owner->Count)
  10960. {
  10961. Index = 0;
  10962. }
  10963. }
  10964. else
  10965. {
  10966. Index--;
  10967. if (Index < 0)
  10968. {
  10969. Index = Item->Owner->Count - 1;
  10970. }
  10971. }
  10972. return Item->Owner->Item[Index];
  10973. }
  10974. //---------------------------------------------------------------------------
  10975. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10976. {
  10977. TCustomDirView * ADirView = DirView(osCurrent);
  10978. if (ADirView->Items->Count == 0)
  10979. {
  10980. return NULL;
  10981. }
  10982. else
  10983. {
  10984. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  10985. TListItem * Item = CurrentItem;
  10986. if (SkipCurrent)
  10987. {
  10988. Item = DebugNotNull(GetNextFile(Item, Reverse));
  10989. }
  10990. while (true)
  10991. {
  10992. bool Matches = false;
  10993. switch (WinConfiguration->PanelSearch)
  10994. {
  10995. case isNameStartOnly:
  10996. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  10997. break;
  10998. case isName:
  10999. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  11000. break;
  11001. case isAll:
  11002. int ColCount = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Count : 1;
  11003. int Index = 0;
  11004. while ((Index < ColCount) && !Matches)
  11005. {
  11006. bool Visible = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Visible[Index] : true;
  11007. if (Visible)
  11008. {
  11009. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  11010. }
  11011. Index++;
  11012. }
  11013. break;
  11014. }
  11015. if (Matches)
  11016. {
  11017. return Item;
  11018. }
  11019. Item = GetNextFile(Item, Reverse);
  11020. if (Item == CurrentItem)
  11021. {
  11022. return NULL;
  11023. }
  11024. }
  11025. }
  11026. }
  11027. //---------------------------------------------------------------------------
  11028. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  11029. {
  11030. ResetIncrementalSearch();
  11031. }
  11032. //---------------------------------------------------------------------------
  11033. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  11034. {
  11035. if (Message.CharCode == VK_TAB)
  11036. {
  11037. if (!FIncrementalSearchState.Text.IsEmpty())
  11038. {
  11039. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11040. bool Reverse = Shift.Contains(ssShift);
  11041. IncrementalSearch(FIncrementalSearchState.Text, true, Reverse);
  11042. Message.Result = 1;
  11043. return;
  11044. }
  11045. }
  11046. else if (Message.CharCode == VK_ESCAPE)
  11047. {
  11048. if (FIncrementalSearchState.Searching)
  11049. {
  11050. ResetIncrementalSearch();
  11051. Message.Result = 1;
  11052. return;
  11053. }
  11054. }
  11055. TForm::Dispatch(&Message);
  11056. }
  11057. //---------------------------------------------------------------------------
  11058. void __fastcall TCustomScpExplorerForm::Deactivate()
  11059. {
  11060. TForm::Deactivate();
  11061. // E.g. when switching to an internal editor window
  11062. ResetIncrementalSearch();
  11063. }
  11064. //---------------------------------------------------------------------------
  11065. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11066. {
  11067. // When switching to another application
  11068. ResetIncrementalSearch();
  11069. }
  11070. //---------------------------------------------------------------------------
  11071. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11072. {
  11073. ResetIncrementalSearch();
  11074. }
  11075. //---------------------------------------------------------------------------
  11076. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11077. {
  11078. if (FIncrementalSearching <= 0)
  11079. {
  11080. ResetIncrementalSearch();
  11081. }
  11082. }
  11083. //---------------------------------------------------------------------------
  11084. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11085. {
  11086. CountClicksForWindowPrint(this);
  11087. }
  11088. //---------------------------------------------------------------------------
  11089. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11090. {
  11091. CenterReconnectToolbar();
  11092. }
  11093. //---------------------------------------------------------------------------
  11094. void TCustomScpExplorerForm::DoBrowseFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11095. {
  11096. if (!FileName.IsEmpty())
  11097. {
  11098. DirView->FocusByName(FileName);
  11099. if (DirView->ItemFocused != NULL)
  11100. {
  11101. DirView->ItemFocused->Selected = true;
  11102. }
  11103. }
  11104. }
  11105. //---------------------------------------------------------------------------
  11106. void __fastcall TCustomScpExplorerForm::BrowseFile(const UnicodeString & FileName)
  11107. {
  11108. DoBrowseFile(RemoteDirView, FileName);
  11109. }
  11110. //---------------------------------------------------------------------------
  11111. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11112. {
  11113. if (!FQueueStatusUpdating)
  11114. {
  11115. bool Refresh;
  11116. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11117. {
  11118. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11119. }
  11120. else
  11121. {
  11122. if (FQueueFileList->GetCount() > 0)
  11123. {
  11124. FQueueFileList->Clear();
  11125. Refresh = true;
  11126. }
  11127. }
  11128. int Count = FQueueFileList->GetCount();
  11129. if (QueueFileList->Items->Count != Count)
  11130. {
  11131. DebugAssert(Refresh);
  11132. QueueFileList->Items->Count = Count;
  11133. }
  11134. if (Refresh)
  11135. {
  11136. QueueFileList->Invalidate();
  11137. }
  11138. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11139. }
  11140. }
  11141. //---------------------------------------------------------------------------
  11142. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11143. {
  11144. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11145. }
  11146. //---------------------------------------------------------------------------
  11147. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11148. {
  11149. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11150. // See TSynchronizeChecklistDialog::UpdateTimer
  11151. if (QueueFileList->Items->Count > 0)
  11152. {
  11153. QueueFileList->Items->Item[0]->MakeVisible(false);
  11154. }
  11155. UpdateQueueFileList();
  11156. }
  11157. //---------------------------------------------------------------------------
  11158. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11159. {
  11160. Active = QueueView3->Focused() || QueueFileList->Focused();
  11161. }
  11162. //---------------------------------------------------------------------------
  11163. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11164. {
  11165. QueueLabelUpdateStatus();
  11166. }
  11167. //---------------------------------------------------------------------------
  11168. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11169. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11170. {
  11171. int State = FQueueFileList->GetState(Item->Index);
  11172. if (State == qfsProcessed)
  11173. {
  11174. Sender->Canvas->Font->Color = clGrayText;
  11175. }
  11176. }
  11177. //---------------------------------------------------------------------------
  11178. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11179. {
  11180. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11181. QueueFileList->Column[0]->Width =
  11182. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11183. }
  11184. //---------------------------------------------------------------------------
  11185. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11186. {
  11187. QueueFileListColumnAutoSize();
  11188. }
  11189. //---------------------------------------------------------------------------
  11190. void __fastcall TCustomScpExplorerForm::CloseApp()
  11191. {
  11192. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11193. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11194. // So we clear the flag here.
  11195. DebugAssert(NonVisualDataModule->Busy);
  11196. NonVisualDataModule->EndBusy();
  11197. try
  11198. {
  11199. Close();
  11200. }
  11201. __finally
  11202. {
  11203. NonVisualDataModule->StartBusy();
  11204. }
  11205. }
  11206. //---------------------------------------------------------------------------
  11207. bool __fastcall TCustomScpExplorerForm::IsActiveTerminal(TTerminal * Terminal)
  11208. {
  11209. return (Terminal != NULL) && Terminal->Active;
  11210. }
  11211. //---------------------------------------------------------------------------
  11212. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  11213. {
  11214. return (ManagedSession != NULL);
  11215. }
  11216. //---------------------------------------------------------------------------
  11217. bool __fastcall TCustomScpExplorerForm::HasActiveTerminal()
  11218. {
  11219. return IsActiveTerminal(Terminal);
  11220. }
  11221. //---------------------------------------------------------------------------
  11222. void TCustomScpExplorerForm::LocalLocalCopy(
  11223. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11224. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11225. {
  11226. DebugFail();
  11227. }
  11228. //---------------------------------------------------------------------------
  11229. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11230. {
  11231. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11232. }
  11233. //---------------------------------------------------------------------------
  11234. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11235. {
  11236. // 1) Changing tab list triggers the OnResize.
  11237. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11238. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11239. {
  11240. // UpdateTabsCaptionTruncation should be enough
  11241. SessionListChanged(true);
  11242. }
  11243. }
  11244. //---------------------------------------------------------------------------
  11245. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11246. {
  11247. if (ASession == ManagedSession)
  11248. {
  11249. UpdateSession(ASession);
  11250. }
  11251. TSessionData * Data = ASession->StateData;
  11252. UnicodeString Result;
  11253. if (Side == osLocal)
  11254. {
  11255. Result = Data->LocalDirectory;
  11256. }
  11257. else if (DebugAlwaysTrue(Side == osOther))
  11258. {
  11259. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11260. }
  11261. return Result;
  11262. }
  11263. //---------------------------------------------------------------------------
  11264. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11265. {
  11266. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11267. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11268. if (Title == Result)
  11269. {
  11270. Result = EmptyStr;
  11271. }
  11272. else
  11273. {
  11274. Result += L"\n";
  11275. }
  11276. return Result;
  11277. }
  11278. //---------------------------------------------------------------------------
  11279. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11280. {
  11281. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11282. if (!ASession->Active)
  11283. {
  11284. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11285. }
  11286. else
  11287. {
  11288. Result += GetSessionPath(ASession, osRemote);
  11289. }
  11290. return Result;
  11291. }
  11292. //---------------------------------------------------------------------------
  11293. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11294. {
  11295. return LoadStr(NEW_REMOTE_TAB_HINT);
  11296. }
  11297. //---------------------------------------------------------------------------
  11298. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11299. {
  11300. if (Index >= 0)
  11301. {
  11302. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11303. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11304. if (TabSession == NULL)
  11305. {
  11306. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11307. if (NewTabTabCaption != TabSheet->Caption)
  11308. {
  11309. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11310. }
  11311. }
  11312. else
  11313. {
  11314. TTerminalManager * Manager = TTerminalManager::Instance();
  11315. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11316. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11317. }
  11318. }
  11319. }
  11320. //---------------------------------------------------------------------------
  11321. typedef std::vector<TListItem *> TListItemsVector;
  11322. struct TCalculateSizeOperation
  11323. {
  11324. TCalculateSizeStats Stats;
  11325. TListItemsVector ListItems;
  11326. size_t Index;
  11327. };
  11328. //---------------------------------------------------------------------------
  11329. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11330. {
  11331. TCalculateSizeOperation CalculateSizeOperation;
  11332. Side = GetSide(Side);
  11333. TCustomDirView * ADirView = DirView(Side);
  11334. bool LocalSide = IsSideLocalBrowser(Side);
  11335. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11336. std::unique_ptr<TStrings> FileList(new TStringList());
  11337. for (int Index = 0; Index < AllFileList->Count; Index++)
  11338. {
  11339. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11340. if (ADirView->ItemIsDirectory(Item))
  11341. {
  11342. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11343. CalculateSizeOperation.ListItems.push_back(Item);
  11344. }
  11345. }
  11346. CalculateSizeOperation.Index = 0;
  11347. __int64 Size = 0;
  11348. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation, &CalculateSizeOperation);
  11349. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11350. FOnFileOperationFinished = DirectorySizeCalculated;
  11351. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation, foCalculateSize);
  11352. TCalculatedSizes CalculatedSizes;
  11353. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11354. if (LocalSide)
  11355. {
  11356. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, Side);
  11357. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11358. }
  11359. else
  11360. {
  11361. TCalculateSizeParams Params;
  11362. Params.Stats = &CalculateSizeOperation.Stats;
  11363. Params.UseCache = true;
  11364. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11365. }
  11366. }
  11367. //---------------------------------------------------------------------------
  11368. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool Success)
  11369. {
  11370. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11371. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11372. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11373. // optimization
  11374. bool GotExpectedItem =
  11375. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11376. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11377. int Index = -1;
  11378. if (DebugAlwaysTrue(GotExpectedItem))
  11379. {
  11380. Index = FCalculateSizeOperation->Index;
  11381. FCalculateSizeOperation->Index++;
  11382. }
  11383. else
  11384. {
  11385. TListItemsVector::iterator I =
  11386. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11387. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11388. {
  11389. Index = I - FCalculateSizeOperation->ListItems.begin();
  11390. }
  11391. }
  11392. if (DebugAlwaysTrue(Index >= 0) && Success)
  11393. {
  11394. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11395. ADirView->SetItemCalculatedSize(Item, Size);
  11396. }
  11397. }
  11398. //---------------------------------------------------------------------------
  11399. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11400. {
  11401. Accept = false;
  11402. }
  11403. //---------------------------------------------------------------------------
  11404. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11405. {
  11406. // Send Ctrl+Gray+ to the list view
  11407. TKeyboardState KeyState;
  11408. GetKeyboardState(KeyState);
  11409. TKeyboardState NewKeyState;
  11410. memset(NewKeyState, 0, sizeof(NewKeyState));
  11411. NewKeyState[VK_CONTROL] = 0x81;
  11412. SetKeyboardState(NewKeyState);
  11413. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11414. SetKeyboardState(KeyState);
  11415. }
  11416. //---------------------------------------------------------------------------
  11417. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11418. {
  11419. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11420. }
  11421. //---------------------------------------------------------------------------
  11422. void * TCustomScpExplorerForm::SaveFocus()
  11423. {
  11424. return NULL;
  11425. }
  11426. //---------------------------------------------------------------------------
  11427. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11428. {
  11429. DebugUsedParam(Focus);
  11430. DebugAssert(Focus == NULL);
  11431. }
  11432. //---------------------------------------------------------------------------
  11433. void TCustomScpExplorerForm::IncrementalSearchStart()
  11434. {
  11435. TCustomDirView * ADirView = DirView(osCurrent);
  11436. ADirView->SetFocus();
  11437. if (!FIncrementalSearchState.Searching)
  11438. {
  11439. FIncrementalSearchState.Searching = true;
  11440. FIncrementalSearchState.HaveNext = false;
  11441. DebugAssert(FIncrementalSearchState.Text.IsEmpty());
  11442. ADirView->UpdateStatusBar();
  11443. }
  11444. }
  11445. //---------------------------------------------------------------------------
  11446. void __fastcall TCustomScpExplorerForm::RemoteDirViewThumbnailNeeded(
  11447. TUnixDirView *, TListItem * Item, TRemoteFile * File, const TSize & Size, TBitmap *& Bitmap)
  11448. {
  11449. // though when downloading to temporary folder, encryption should not be a problem
  11450. if (Terminal->IsCapable[fcBackgroundTransfers] &&
  11451. !File->IsDirectory)
  11452. {
  11453. UnicodeString FileName = File->FullFileName;
  11454. TFileMasks::TParams MaskParams;
  11455. MaskParams.Size = File->Size;
  11456. MaskParams.Modification = File->Modification;
  11457. if ((File->Size <= static_cast<__int64>(WinConfiguration->RemoteThumbnailSizeLimit) * 1024) &&
  11458. FRemoteThumbnailMask.Matches(FileName, false, File->IsDirectory, &MaskParams))
  11459. {
  11460. Bitmap = TTerminalManager::Instance()->ThumbnailNeeded(Terminal, Item->Index, File, Size);
  11461. }
  11462. }
  11463. }
  11464. //---------------------------------------------------------------------------
  11465. TThumbnailDownloadQueueItem * TCustomScpExplorerForm::AddThumbnailDownloadQueueItem(TManagedTerminal * ATerminal)
  11466. {
  11467. DebugAssert(ATerminal == Terminal);
  11468. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  11469. TemporaryFileCopyParam(CopyParam);
  11470. CopyParam.TransferMode = tmBinary;
  11471. UnicodeString SourceDir = ATerminal->CurrentDirectory;
  11472. UnicodeString TempDir, RootTempDir;
  11473. TemporaryDirectoryForRemoteFiles(SourceDir, CopyParam, true, TempDir, RootTempDir);
  11474. TTerminalQueue * AQueue = TTerminalManager::Instance()->FindQueueForTerminal(ATerminal);
  11475. DebugAssert((Queue == NULL) || (AQueue == Queue)); // we might get here before queue is set
  11476. TThumbnailDownloadQueueItem * QueueItem =
  11477. new TThumbnailDownloadQueueItem(this, Terminal, SourceDir, TempDir, &CopyParam);
  11478. AddQueueItem(AQueue, QueueItem, ATerminal);
  11479. return QueueItem;
  11480. }
  11481. //---------------------------------------------------------------------------
  11482. enum { qccRemoteItemVisible, qccRemoteItemRedraw };
  11483. typedef std::pair<int, UnicodeString> TRemoteItemVisibleData;
  11484. //---------------------------------------------------------------------------
  11485. void TCustomScpExplorerForm::PostThumbnailVisibleQueueQuery(int Index, const UnicodeString & FileName)
  11486. {
  11487. // The queue might be destroyed before the WM_QUEUE_CALLBACK is processed
  11488. TRemoteItemVisibleData * Data = new TRemoteItemVisibleData();
  11489. Data->first = Index;
  11490. Data->second = FileName;
  11491. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemVisible, reinterpret_cast<WPARAM>(Data));
  11492. }
  11493. //---------------------------------------------------------------------------
  11494. void TCustomScpExplorerForm::PostThumbnailDrawRequest(int Index)
  11495. {
  11496. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemRedraw, Index);
  11497. }
  11498. //---------------------------------------------------------------------------
  11499. void TCustomScpExplorerForm::WMQueueCallback(TMessage & Message)
  11500. {
  11501. int Command = Message.WParam;
  11502. if (Command == qccRemoteItemVisible)
  11503. {
  11504. TRemoteItemVisibleData * Data = reinterpret_cast<TRemoteItemVisibleData *>(Message.LParam);
  11505. int Index = Data->first;
  11506. UnicodeString FileName = Data->second;
  11507. delete Data;
  11508. TGuard Guard(Terminal->ThumbnailsSection.get());
  11509. bool Visible = False;
  11510. if (Terminal->ThumbnailsEnabled &&
  11511. // though we should better also disable thumbnails once we switch to different view style
  11512. (RemoteDirView->DirViewStyle == dvsThumbnail))
  11513. {
  11514. // The message might be processed, while we are already loading a different directory
  11515. if ((Index >= 0) &&
  11516. (Index < RemoteDirView->Items->Count))
  11517. {
  11518. TListItem * Item = RemoteDirView->Items->Item[Index];
  11519. Visible =
  11520. (RemoteDirView->ItemFullFileName(Item) == FileName) &&
  11521. ListView_IsItemVisible(RemoteDirView->Handle, Index);
  11522. }
  11523. }
  11524. Terminal->ThumbnailVisible(Index, FileName, Visible);
  11525. }
  11526. else if (Command == qccRemoteItemRedraw)
  11527. {
  11528. int Index = Message.LParam;
  11529. if ((Index >= 0) &&
  11530. (Index < RemoteDirView->Items->Count))
  11531. {
  11532. RemoteDirView->InvalidateItem(RemoteDirView->Items->Item[Index]);
  11533. }
  11534. }
  11535. }
  11536. //---------------------------------------------------------------------------
  11537. void TCustomScpExplorerForm::InitializeRemoteThumbnailMask()
  11538. {
  11539. UnicodeString DefaultRemoteThumbnailMask = L"*.jpg;*.jpeg;*.gif;*.png;*.svg;*.bmp;*.raw;*.ico;*.heic";
  11540. UnicodeString RemoteThumbnailMask = WinConfiguration->RemoteThumbnailMask;
  11541. if (RemoteThumbnailMask.IsEmpty() ||
  11542. StartsStr(L"+", RemoteThumbnailMask) || StartsStr(L"-", RemoteThumbnailMask) || StartsStr(L"*", RemoteThumbnailMask))
  11543. {
  11544. std::unique_ptr<TStrings> RemoteThumbnailMasks(new TStringList());
  11545. while (!DefaultRemoteThumbnailMask.IsEmpty())
  11546. {
  11547. RemoteThumbnailMasks->Add(CutToChar(DefaultRemoteThumbnailMask, L';', true));
  11548. }
  11549. RemoteThumbnailMasks.reset(ProcessFeatures(RemoteThumbnailMasks.get(), RemoteThumbnailMask));
  11550. RemoteThumbnailMask = EmptyStr;
  11551. for (int Index = 0; Index < RemoteThumbnailMasks->Count; Index++)
  11552. {
  11553. AddToList(RemoteThumbnailMask, RemoteThumbnailMasks->Strings[Index], L";");
  11554. }
  11555. }
  11556. FRemoteThumbnailMask.Masks = RemoteThumbnailMask;
  11557. }
  11558. //---------------------------------------------------------------------------
  11559. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartLoading(TObject *)
  11560. {
  11561. Terminal->StartLoadingDirectory();
  11562. }
  11563. //---------------------------------------------------------------------------
  11564. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartReading(TObject *)
  11565. {
  11566. Terminal->DisableThumbnails();
  11567. }
  11568. //---------------------------------------------------------------------------