CustomScpExplorer.cpp 333 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200
  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 <Bookmarks.h>
  8. #include <Interface.h>
  9. #include <Exceptions.h>
  10. #include <CoreMain.h>
  11. #include <FileSystems.h>
  12. #include <TextsCore.h>
  13. #include <TextsWin.h>
  14. #include <HelpWin.h>
  15. #include <VCLCommon.h>
  16. #include <Progress.h>
  17. #include <SynchronizeProgress.h>
  18. #include <DragExt.h>
  19. #include <WinApi.h>
  20. #include "GUITools.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. //---------------------------------------------------------------------------
  34. #pragma package(smart_init)
  35. #pragma link "CustomDirView"
  36. #pragma link "CustomUnixDirView"
  37. #pragma link "IEListView"
  38. #pragma link "NortonLikeListView"
  39. #pragma link "UnixDirView"
  40. #pragma link "CustomDriveView"
  41. #pragma link "UnixDriveView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "TB2Dock"
  44. #pragma link "TBXStatusBars"
  45. #pragma link "TB2Item"
  46. #pragma link "TB2Toolbar"
  47. #pragma link "ThemePageControl"
  48. #pragma link "PathLabel"
  49. #ifndef NO_RESOURCES
  50. #pragma resource "*.dfm"
  51. #endif
  52. //---------------------------------------------------------------------------
  53. #define SAVE_SELECTION(DIRVIEW) \
  54. UnicodeString FocusFile = L""; \
  55. UnicodeString LastFocusedFile = L""; \
  56. if (DIRVIEW->ItemFocused) LastFocusedFile = DIRVIEW->ItemFocused->Caption; \
  57. { TListItem * ClosestUnselected = DIRVIEW->ClosestUnselected(DIRVIEW->ItemFocused); \
  58. if (ClosestUnselected) FocusFile = ClosestUnselected->Caption; }
  59. #define RESTORE_SELECTION(DIRVIEW) \
  60. if (!LastFocusedFile.IsEmpty() && \
  61. (!DIRVIEW->ItemFocused || (DIRVIEW->ItemFocused->Caption != LastFocusedFile))) \
  62. { \
  63. TListItem *ItemToSelect = DIRVIEW->FindFileItem(FocusFile); \
  64. if (ItemToSelect) \
  65. { \
  66. DIRVIEW->ItemFocused = ItemToSelect; \
  67. DIRVIEW->ItemFocused->MakeVisible(False); \
  68. } \
  69. }
  70. //---------------------------------------------------------------------------
  71. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  72. static const int SessionPanelCount = 4;
  73. //---------------------------------------------------------------------------
  74. class TMutexGuard
  75. {
  76. public:
  77. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  78. int Timeout = 5000)
  79. {
  80. FMutex = NULL;
  81. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  82. if (WaitResult == WAIT_TIMEOUT)
  83. {
  84. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  85. }
  86. else
  87. {
  88. FMutex = AMutex;
  89. }
  90. }
  91. ~TMutexGuard()
  92. {
  93. if (FMutex != NULL)
  94. {
  95. ReleaseMutex(FMutex);
  96. }
  97. }
  98. private:
  99. HANDLE FMutex;
  100. };
  101. //---------------------------------------------------------------------------
  102. class TWindowLock
  103. {
  104. public:
  105. TWindowLock(TCustomScpExplorerForm * Form) :
  106. FForm(Form)
  107. {
  108. FForm->LockWindow();
  109. }
  110. ~TWindowLock()
  111. {
  112. FForm->UnlockWindow();
  113. }
  114. private:
  115. TCustomScpExplorerForm * FForm;
  116. };
  117. //---------------------------------------------------------------------------
  118. class TAutoBatch
  119. {
  120. public:
  121. TAutoBatch(TCustomScpExplorerForm * Form) :
  122. FForm(Form)
  123. {
  124. FForm->BatchStart(FBatchStorage);
  125. }
  126. ~TAutoBatch()
  127. {
  128. FForm->BatchEnd(FBatchStorage);
  129. }
  130. private:
  131. TCustomScpExplorerForm * FForm;
  132. void * FBatchStorage;
  133. };
  134. //---------------------------------------------------------------------------
  135. struct TTransferOperationParam
  136. {
  137. TTransferOperationParam();
  138. UnicodeString TargetDirectory;
  139. bool Temp;
  140. bool DragDrop;
  141. int Options;
  142. TAutoSwitch Queue;
  143. };
  144. //---------------------------------------------------------------------------
  145. TTransferOperationParam::TTransferOperationParam()
  146. {
  147. Temp = false;
  148. DragDrop = false;
  149. Options = 0;
  150. Queue = asAuto;
  151. }
  152. //---------------------------------------------------------------------------
  153. class TTransferPresetNoteData : public TObject
  154. {
  155. public:
  156. UnicodeString Message;
  157. };
  158. //---------------------------------------------------------------------------
  159. class TTerminalNoteData : public TObject
  160. {
  161. public:
  162. TTerminal * Terminal;
  163. };
  164. //---------------------------------------------------------------------------
  165. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  166. FFormRestored(false),
  167. TForm(Owner)
  168. {
  169. FCurrentSide = osRemote;
  170. FEverShown = false;
  171. FDocks = new TList();
  172. RestoreParams();
  173. ConfigurationChanged();
  174. RemoteDirView->Invalidate();
  175. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  176. NonVisualDataModule->ScpExplorer = this;
  177. FAutoOperation = false;
  178. FOnFileOperationFinished = NULL;
  179. FForceExecution = false;
  180. FIgnoreNextDialogChar = 0;
  181. FErrorList = NULL;
  182. FSynchronizeProgressForm = NULL;
  183. FProgressForm = NULL;
  184. FRefreshLocalDirectory = false;
  185. FRefreshRemoteDirectory = false;
  186. FDDExtMapFile = NULL;
  187. // CreateMutexW keeps failing with ERROR_NOACCESS
  188. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  189. DebugAssert(FDDExtMutex != NULL);
  190. FDDTargetControl = NULL;
  191. FDelayedDeletionTimer = NULL;
  192. FDelayedDeletionList = new TStringList();
  193. FDDFileList = NULL;
  194. FPendingTempSpaceWarn = false;
  195. FCapturedLog = NULL;
  196. FDragDropOperation = false;
  197. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  198. FAllowTransferPresetAutoSelect = true;
  199. FCopyParamDefault = L"";
  200. FSynchronizeController = NULL;
  201. FPendingQueueActionItem = NULL;
  202. FLockLevel = 0;
  203. FLockSuspendLevel = 0;
  204. FDisabledOnLockSuspend = false;
  205. FAlternativeDelete = false;
  206. FTrayIcon = new ::TTrayIcon(0);
  207. FTrayIcon->OnClick = TrayIconClick;
  208. FMaxQueueLength = 0;
  209. FLastContextPopupScreenPoint = TPoint(-1, -1);
  210. FTransferResumeList = NULL;
  211. FMoveToQueue = false;
  212. FStandaloneEditing = false;
  213. FOnFeedSynchronizeError = NULL;
  214. FNeedSession = false;
  215. FDoNotIdleCurrentTerminal = 0;
  216. FEditorManager = new TEditorManager();
  217. FEditorManager->OnFileChange = ExecutedFileChanged;
  218. FEditorManager->OnFileReload = ExecutedFileReload;
  219. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  220. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  221. FLocalEditors = new TList();
  222. FQueueStatus = NULL;
  223. FQueueStatusSection = new TCriticalSection();
  224. FQueueStatusInvalidated = false;
  225. FQueueItemInvalidated = false;
  226. FQueueActedItem = NULL;
  227. FQueueController = new TQueueController(QueueView3);
  228. FUserActionTimer = new TTimer(this);
  229. FUserActionTimer->Enabled = false;
  230. FUserActionTimer->Interval = 10;
  231. FUserActionTimer->OnTimer = UserActionTimer;
  232. FNotes = new TStringList();
  233. FNoteTimer = new TTimer(this);
  234. FNoteTimer->Enabled = false;
  235. FNoteTimer->OnTimer = NoteTimer;
  236. FOnNoteClick = NULL;
  237. FOle32Library = LoadLibrary(L"Ole32.dll");
  238. FDragMoveCursor = FOle32Library != NULL ?
  239. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  240. UseSystemSettings(this);
  241. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  242. static_cast<TObject*>(GetComponent(fcTransferList)));
  243. DebugAssert(TransferList != NULL);
  244. FTransferListHoverIndex = -1;
  245. TransferList->OnChange = TransferListChange;
  246. TransferList->OnDrawItem = TransferListDrawItem;
  247. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))));
  248. SetSubmenu(NonVisualDataModule->ColorMenuItem);
  249. UseDesktopFont(SessionsPageControl);
  250. UpdateSessionsPageControlHeight();
  251. UseDesktopFont(RemoteDirView);
  252. UseDesktopFont(RemoteDriveView);
  253. UseDesktopFont(QueueView3);
  254. UseDesktopFont(QueueLabel);
  255. UseDesktopFont(RemoteStatusBar);
  256. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  257. QueueSplitter->ShowHint = true;
  258. RemotePanelSplitter->ShowHint = true;
  259. UpdateImages();
  260. FCustomCommandMenu = CreateTBXPopupMenu(this);
  261. FCustomCommandLocalFileList = NULL;
  262. FCustomCommandRemoteFileList = NULL;
  263. FSessionColors = new TPngImageList(this);
  264. FSessionColors->ColorDepth = cd32Bit;
  265. AddFixedSessionImages();
  266. SessionsPageControl->Images = FSessionColors;
  267. QueueLabel->FocusControl = QueueView3;
  268. UpdateQueueLabel();
  269. FRemoteDirViewWasFocused = true;
  270. CreateHiddenWindow();
  271. StartUpdates();
  272. }
  273. //---------------------------------------------------------------------------
  274. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  275. {
  276. // this has to be one of the very first things to do
  277. StopUpdateThread();
  278. delete FCustomCommandLocalFileList;
  279. delete FCustomCommandRemoteFileList;
  280. delete FCustomCommandMenu;
  281. delete FTrayIcon;
  282. FTrayIcon = NULL;
  283. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  284. delete FEditorManager;
  285. ForceCloseLocalEditors();
  286. delete FLocalEditors;
  287. HideFileFindDialog();
  288. if (FDelayedDeletionTimer)
  289. {
  290. DoDelayedDeletion(NULL);
  291. SAFE_DESTROY(FDelayedDeletionTimer);
  292. }
  293. SAFE_DESTROY(FDelayedDeletionList);
  294. // sometimes we do not get DDEnd so the list is not released
  295. SAFE_DESTROY(FDDFileList);
  296. DebugAssert(FSynchronizeController == NULL);
  297. CloseHandle(FDDExtMutex);
  298. FDDExtMutex = NULL;
  299. FreeLibrary(FOle32Library);
  300. FOle32Library = NULL;
  301. FDragMoveCursor = NULL;
  302. DebugAssert(!FErrorList);
  303. if (FEverShown)
  304. {
  305. // when window is never shown (like when running command-line operation),
  306. // particularly window site is not restored correctly (BoundsRect value set
  307. // in RestoreForm gets lost during handle allocation), so we do not want
  308. // it to be stored
  309. StoreParams();
  310. }
  311. Terminal = NULL;
  312. Queue = NULL;
  313. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  314. NonVisualDataModule->ScpExplorer = NULL;
  315. delete FQueueController;
  316. FQueueController = NULL;
  317. delete FQueueStatusSection;
  318. FQueueStatusSection = NULL;
  319. delete FQueueStatus;
  320. FQueueStatus = NULL;
  321. delete FUserActionTimer;
  322. FUserActionTimer = NULL;
  323. delete FNoteTimer;
  324. delete FNotes;
  325. delete FNoteData;
  326. SAFE_DESTROY(FDocks);
  327. SessionsPageControl->Images = NULL;
  328. // only after clearing Terminal (after DoTerminalListChanged => ... => AddSessionColor is called)
  329. SAFE_DESTROY(FSessionColors);
  330. SAFE_DESTROY(FSessionsDragDropFilesEx);
  331. SAFE_DESTROY(FHistoryMenu[0][0]);
  332. SAFE_DESTROY(FHistoryMenu[0][1]);
  333. SAFE_DESTROY(FHistoryMenu[1][0]);
  334. SAFE_DESTROY(FHistoryMenu[1][1]);
  335. if (FHiddenWindow != NULL)
  336. {
  337. DestroyWindow(FHiddenWindow);
  338. FHiddenWindow = NULL;
  339. }
  340. }
  341. //---------------------------------------------------------------------------
  342. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  343. {
  344. std::unique_ptr<TSessionData> Data;
  345. if (!Session.IsEmpty())
  346. {
  347. bool DefaultsOnly;
  348. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  349. }
  350. TTerminalManager * Manager = TTerminalManager::Instance();
  351. for (int Index = 0; Index < Manager->Count; Index++)
  352. {
  353. TTerminal * Terminal = Manager->Terminals[Index];
  354. if (Session.IsEmpty() ||
  355. Terminal->SessionData->IsSameSite(Data.get()))
  356. {
  357. if (Path.IsEmpty())
  358. {
  359. Terminal->ClearCaches();
  360. }
  361. else
  362. {
  363. Terminal->DirectoryModified(Path, true);
  364. }
  365. }
  366. }
  367. // We should flag a pending refresh for the background terminals or busy foreground terminals
  368. if ((Terminal != NULL) && Terminal->Active &&
  369. CanCommandLineFromAnotherInstance() &&
  370. (Session.IsEmpty() || Terminal->SessionData->IsSameSite(Data.get())) &&
  371. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  372. {
  373. Terminal->ReloadDirectory();
  374. }
  375. }
  376. //---------------------------------------------------------------------------
  377. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  378. {
  379. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  380. size_t MessageSize = sizeof(TCopyDataMessage);
  381. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  382. if (Result)
  383. {
  384. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  385. Result = (Message.Version == TCopyDataMessage::Version1);
  386. if (Result)
  387. {
  388. switch (Message.Command)
  389. {
  390. case TCopyDataMessage::CommandCanCommandLine:
  391. Result = CanCommandLineFromAnotherInstance();
  392. break;
  393. case TCopyDataMessage::CommandCommandLine:
  394. {
  395. UnicodeString CommandLine(Message.CommandLine);
  396. Result = CommandLineFromAnotherInstance(CommandLine);
  397. }
  398. break;
  399. case TCopyDataMessage::RefreshPanel:
  400. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  401. break;
  402. case TCopyDataMessage::MainWindowCheck:
  403. Result = true;
  404. break;
  405. default:
  406. Result = false;
  407. break;
  408. }
  409. }
  410. }
  411. Message.Result = Result ? 1 : 0;
  412. }
  413. //---------------------------------------------------------------------------
  414. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  415. {
  416. WNDCLASS WindowClass = {0};
  417. WindowClass.lpfnWndProc = DefWindowProc;
  418. WindowClass.hInstance = HInstance;
  419. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  420. FHiddenWindow = NULL;
  421. if (RegisterClass(&WindowClass))
  422. {
  423. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  424. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  425. }
  426. }
  427. //---------------------------------------------------------------------------
  428. bool __fastcall TCustomScpExplorerForm::CanConsole()
  429. {
  430. return (Terminal != NULL) && (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  431. }
  432. //---------------------------------------------------------------------------
  433. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  434. {
  435. bool Result = Visible && !NonVisualDataModule->Busy;
  436. return Result;
  437. }
  438. //---------------------------------------------------------------------------
  439. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  440. const UnicodeString & CommandLine)
  441. {
  442. TProgramParams Params(CommandLine);
  443. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  444. if (Result)
  445. {
  446. NonVisualDataModule->StartBusy();
  447. try
  448. {
  449. // this action is initiated from another process,
  450. // so it's likely that our window is not visible,
  451. // and user won't see what is going on
  452. Application->BringToFront();
  453. // reload sessions as we may be asked to open a session
  454. // just stored by another instance
  455. StoredSessions->Reload();
  456. UnicodeString SessionName = Params.Param[1];
  457. std::unique_ptr<TObjectList> DataList(new TObjectList());
  458. UnicodeString DownloadFile; // unused
  459. try
  460. {
  461. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this);
  462. }
  463. catch (EAbort &)
  464. {
  465. // Happens when opening session in PuTTY and in other situations,
  466. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  467. // to process the command-line on its own (or to pass it to yet another instance)
  468. }
  469. if (DataList->Count > 0)
  470. {
  471. TTerminalManager * Manager = TTerminalManager::Instance();
  472. Manager->ActiveTerminal = Manager->NewTerminals(DataList.get());
  473. }
  474. }
  475. __finally
  476. {
  477. NonVisualDataModule->EndBusy();
  478. }
  479. }
  480. return Result;
  481. }
  482. //---------------------------------------------------------------------------
  483. void __fastcall TCustomScpExplorerForm::SetTerminal(TTerminal * value)
  484. {
  485. if (FTerminal != value)
  486. {
  487. TerminalChanging();
  488. DoSetTerminal(value, false);
  489. }
  490. }
  491. //---------------------------------------------------------------------------
  492. void __fastcall TCustomScpExplorerForm::DoSetTerminal(TTerminal * value, bool Replace)
  493. {
  494. FTerminal = value;
  495. bool PrevAllowTransferPresetAutoSelect = FAllowTransferPresetAutoSelect;
  496. FAllowTransferPresetAutoSelect = false;
  497. try
  498. {
  499. TerminalChanged(Replace);
  500. }
  501. __finally
  502. {
  503. FAllowTransferPresetAutoSelect = PrevAllowTransferPresetAutoSelect;
  504. }
  505. if (Terminal != NULL)
  506. {
  507. TransferPresetAutoSelect();
  508. }
  509. }
  510. //---------------------------------------------------------------------------
  511. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TTerminal * value)
  512. {
  513. DoSetTerminal(value, true);
  514. }
  515. //---------------------------------------------------------------------------
  516. void __fastcall TCustomScpExplorerForm::TerminalChanging()
  517. {
  518. if (FTerminal != NULL)
  519. {
  520. UpdateTerminal(Terminal);
  521. }
  522. }
  523. //---------------------------------------------------------------------------
  524. void __fastcall TCustomScpExplorerForm::TerminalChanged(bool Replaced)
  525. {
  526. if (Replaced)
  527. {
  528. RemoteDirView->ReplaceTerminal(Terminal);
  529. }
  530. else
  531. {
  532. RemoteDirView->Terminal = Terminal;
  533. }
  534. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  535. TManagedTerminal * ManagedTerminal = NULL;
  536. if (Terminal != NULL)
  537. {
  538. if (Terminal->Active)
  539. {
  540. Terminal->RefreshDirectory();
  541. }
  542. ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  543. DebugAssert(ManagedTerminal != NULL);
  544. if (WinConfiguration->PreservePanelState)
  545. {
  546. if (ManagedTerminal->RemoteExplorerState != NULL)
  547. {
  548. RemoteDirView->RestoreState(ManagedTerminal->RemoteExplorerState);
  549. }
  550. else
  551. {
  552. RemoteDirView->ClearState();
  553. }
  554. }
  555. if (!Replaced)
  556. {
  557. InitStatusBar();
  558. }
  559. }
  560. DoTerminalListChanged();
  561. if (ManagedTerminal != NULL)
  562. {
  563. // this has to be set only after the tab is switched from DoTerminalListChanged,
  564. // otherwise we are changing color of wrong tab
  565. SessionColor = (TColor)ManagedTerminal->StateData->Color;
  566. }
  567. UpdateTransferList();
  568. // Update panels Enable state before refreshing the labels
  569. UpdateControls();
  570. }
  571. //---------------------------------------------------------------------------
  572. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  573. {
  574. if (Queue != value)
  575. {
  576. if (FQueue != NULL)
  577. {
  578. FQueue->OnListUpdate = NULL;
  579. FQueue->OnQueueItemUpdate = NULL;
  580. }
  581. FQueue = value;
  582. if (FQueue != NULL)
  583. {
  584. DebugAssert(FQueue->OnListUpdate == NULL);
  585. FQueue->OnListUpdate = QueueListUpdate;
  586. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  587. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  588. }
  589. QueueChanged();
  590. }
  591. }
  592. //---------------------------------------------------------------------------
  593. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  594. TListItem * Item)
  595. {
  596. if (FQueueActedItem == Item)
  597. {
  598. FQueueActedItem = NULL;
  599. if ((QueueView3->PopupMenu != NULL) &&
  600. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  601. {
  602. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  603. ReleaseCapture();
  604. }
  605. }
  606. if (Item->Data == FPendingQueueActionItem)
  607. {
  608. FPendingQueueActionItem = NULL;
  609. }
  610. }
  611. //---------------------------------------------------------------------------
  612. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  613. {
  614. {
  615. TGuard Guard(FQueueStatusSection);
  616. FQueueStatusInvalidated = false;
  617. if (FQueue != NULL)
  618. {
  619. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  620. }
  621. }
  622. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  623. {
  624. FMaxQueueLength = FQueueStatus->Count;
  625. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  626. }
  627. FQueueController->UpdateQueueStatus(FQueueStatus);
  628. SetQueueProgress();
  629. UpdateQueueView();
  630. bool IsEmpty = (FQueueStatus == NULL) || (FQueueStatus->Count == 0);
  631. if (IsEmpty && (Terminal != NULL))
  632. {
  633. TOnceDoneOperation OnceDoneOperation =
  634. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  635. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  636. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  637. {
  638. FQueue->Enabled = false;
  639. }
  640. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  641. {
  642. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  643. }
  644. }
  645. }
  646. //---------------------------------------------------------------------------
  647. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  648. {
  649. UnicodeString Result;
  650. if (FQueueStatus != NULL)
  651. {
  652. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  653. {
  654. TFileOperationProgressType * ProgressData =
  655. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  656. if ((ProgressData != NULL) && ProgressData->InProgress)
  657. {
  658. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  659. }
  660. }
  661. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  662. {
  663. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  664. }
  665. }
  666. return Result;
  667. }
  668. //---------------------------------------------------------------------------
  669. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  670. {
  671. ComponentVisible[fcQueueView] =
  672. (WinConfiguration->QueueView.Show == qvShow) ||
  673. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  674. (FQueueStatus != NULL) && (FQueueStatus->Count > 0));
  675. }
  676. //---------------------------------------------------------------------------
  677. void __fastcall TCustomScpExplorerForm::QueueChanged()
  678. {
  679. if (FQueueStatus != NULL)
  680. {
  681. delete FQueueStatus;
  682. FQueueStatus = NULL;
  683. }
  684. UpdateQueueStatus(true);
  685. }
  686. //---------------------------------------------------------------------------
  687. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  688. {
  689. if (FQueue == Queue)
  690. {
  691. FQueueStatusInvalidated = true;
  692. }
  693. }
  694. //---------------------------------------------------------------------------
  695. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  696. TQueueItem * Item)
  697. {
  698. if (FQueue == Queue)
  699. {
  700. TGuard Guard(FQueueStatusSection);
  701. // this may be running in parallel with QueueChanged
  702. if (FQueueStatus != NULL)
  703. {
  704. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  705. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  706. {
  707. FRefreshLocalDirectory = (QueueItem == NULL) ||
  708. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  709. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  710. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  711. }
  712. if (QueueItem != NULL)
  713. {
  714. QueueItem->UserData = (void*)true;
  715. FQueueItemInvalidated = true;
  716. }
  717. }
  718. }
  719. }
  720. //---------------------------------------------------------------------------
  721. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  722. {
  723. // during standalone editing, we have no way to see/control queue,
  724. // so we have to always popup prompts automatically
  725. return FStandaloneEditing || GUIConfiguration->QueueAutoPopup;
  726. }
  727. //---------------------------------------------------------------------------
  728. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  729. {
  730. if (FQueueStatus != NULL)
  731. {
  732. bool QueueAutoPopup = IsQueueAutoPopup();
  733. bool NeedRefresh = FQueueController->NeedRefresh();
  734. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  735. FQueueItemInvalidated = false;
  736. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  737. bool Updated = false;
  738. TQueueItemProxy * QueueItem;
  739. bool WasUserAction;
  740. for (int Index = 0; Index < Limit; Index++)
  741. {
  742. bool Update = false;
  743. QueueItem = FQueueStatus->Items[Index];
  744. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  745. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  746. (FPendingQueueActionItem == NULL))
  747. {
  748. FPendingQueueActionItem = QueueItem;
  749. FUserActionTimer->Enabled = true;
  750. }
  751. if ((bool)QueueItem->UserData)
  752. {
  753. QueueItem->UserData = (void*)false;
  754. QueueItem->Update();
  755. Updated = true;
  756. Update = true;
  757. }
  758. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  759. {
  760. Update = true;
  761. }
  762. if (Update)
  763. {
  764. FQueueController->RefreshQueueItem(QueueItem);
  765. }
  766. }
  767. if (Updated)
  768. {
  769. NonVisualDataModule->UpdateNonVisibleActions();
  770. SetQueueProgress();
  771. }
  772. }
  773. }
  774. //---------------------------------------------------------------------------
  775. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  776. {
  777. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  778. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  779. }
  780. //---------------------------------------------------------------------------
  781. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  782. {
  783. if (ProgressData->Operation != foCalculateSize)
  784. {
  785. int OverallProgress;
  786. // FProgressForm is null when this is called from SetQueueProgress
  787. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  788. {
  789. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  790. }
  791. else
  792. {
  793. OverallProgress = ProgressData->OverallProgress();
  794. }
  795. // implies TBPF_NORMAL
  796. FTaskbarList->SetProgressValue(GetMainForm()->Handle, OverallProgress, 100);
  797. }
  798. else
  799. {
  800. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  801. }
  802. }
  803. //---------------------------------------------------------------------------
  804. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  805. {
  806. TTerminalManager::Instance()->QueueStatusUpdated();
  807. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  808. {
  809. if ((FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0))
  810. {
  811. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  812. {
  813. TFileOperationProgressType * ProgressData = NULL;
  814. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  815. {
  816. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  817. }
  818. if ((ProgressData != NULL) &&
  819. ProgressData->InProgress)
  820. {
  821. SetTaskbarListProgressValue(ProgressData);
  822. }
  823. else
  824. {
  825. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  826. }
  827. }
  828. else
  829. {
  830. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  831. }
  832. }
  833. else
  834. {
  835. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  836. }
  837. }
  838. UpdateQueueLabel();
  839. }
  840. //---------------------------------------------------------------------------
  841. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  842. {
  843. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  844. if (FQueueStatus != NULL)
  845. {
  846. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  847. if (ActiveAndPendingPrimaryCount > 0)
  848. {
  849. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  850. }
  851. }
  852. QueueLabel->Caption = Caption;
  853. }
  854. //---------------------------------------------------------------------------
  855. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  856. {
  857. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  858. static_cast<TComponent*>(GetComponent(fcTransferList)));
  859. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  860. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  861. TransferList->Strings->BeginUpdate();
  862. try
  863. {
  864. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  865. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  866. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  867. if (FTransferDropDownHint.IsEmpty())
  868. {
  869. FTransferDropDownHint = TransferDropDown->Hint;
  870. }
  871. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  872. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  873. TransferDropDown->Text = StripHotkey(Name);
  874. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  875. (FTransferDropDownHint, StripHotkey(Name),
  876. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  877. FLAGMASK(((Terminal != NULL) && Terminal->Active), Terminal->UsableCopyParamAttrs(0).General))));
  878. // update the label, otherwise when it is updated only on the first draw
  879. // of the list, it is drawn "bold" for some reason
  880. FTransferListHoverIndex = TransferList->ItemIndex;
  881. UpdateTransferLabel();
  882. }
  883. __finally
  884. {
  885. TransferList->Strings->EndUpdate();
  886. }
  887. }
  888. //---------------------------------------------------------------------------
  889. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  890. {
  891. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  892. DebugAssert(Toolbar != NULL);
  893. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  894. }
  895. //---------------------------------------------------------------------------
  896. void __fastcall TCustomScpExplorerForm::UpdateActions()
  897. {
  898. TForm::UpdateActions();
  899. if (ComponentVisible[fcCustomCommandsBand])
  900. {
  901. UpdateCustomCommandsToolbar();
  902. }
  903. }
  904. //---------------------------------------------------------------------------
  905. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  906. {
  907. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  908. }
  909. //---------------------------------------------------------------------------
  910. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  911. {
  912. DebugAssert(Configuration && RemoteDirView);
  913. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  914. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  915. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  916. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  917. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  918. if (RemoteDirView->RowSelect != WinConfiguration->FullRowSelect)
  919. {
  920. RemoteDirView->RowSelect = WinConfiguration->FullRowSelect;
  921. // selection is not redrawn automatically when RowSelect changes
  922. RemoteDirView->Invalidate();
  923. }
  924. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  925. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  926. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  927. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  928. UpdateSessionsPageControlHeight();
  929. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  930. UpdateToolbarDisplayMode();
  931. UpdateTransferList();
  932. if (Terminal != NULL)
  933. {
  934. TransferPresetAutoSelect();
  935. }
  936. UpdateQueueView();
  937. UpdateControls();
  938. // this can be called even before constuctor finishes.
  939. if (FEditorManager != NULL)
  940. {
  941. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  942. }
  943. // this can be called even before constuctor finishes.
  944. if (FLocalEditors != NULL)
  945. {
  946. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  947. {
  948. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  949. }
  950. }
  951. if (ComponentVisible[fcCustomCommandsBand])
  952. {
  953. UpdateCustomCommandsToolbar();
  954. }
  955. // show only when keeping queue items forever,
  956. // otherwise, its enough to have in in the context menu
  957. QueueDeleteAllDoneQueueToolbarItem->Visible =
  958. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  959. if (FFileColorsCurrent != WinConfiguration->FileColors)
  960. {
  961. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  962. FFileColorsCurrent = WinConfiguration->FileColors;
  963. FileColorsChanged();
  964. }
  965. }
  966. //---------------------------------------------------------------------------
  967. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  968. {
  969. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  970. DirView->Invalidate();
  971. }
  972. //---------------------------------------------------------------------------
  973. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  974. {
  975. DoFileColorsChanged(RemoteDirView);
  976. }
  977. //---------------------------------------------------------------------------
  978. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  979. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  980. void * /*Arg*/)
  981. {
  982. if (Token != NULL)
  983. {
  984. TForm * Editor = dynamic_cast<TForm*>(Token);
  985. DebugAssert(Editor != NULL);
  986. ReconfigureEditorForm(Editor);
  987. }
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  991. {
  992. WinConfiguration->DDTransferConfirmation = asOn;
  993. }
  994. //---------------------------------------------------------------------------
  995. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  996. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  997. {
  998. // noop
  999. }
  1000. //---------------------------------------------------------------------------
  1001. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1002. TTransferDirection Direction, TTransferType Type, bool Temp,
  1003. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1004. bool Confirm, bool DragDrop, int Options)
  1005. {
  1006. bool Result = true;
  1007. DebugAssert(Terminal && Terminal->Active);
  1008. // these parameters are known in advance
  1009. int Params =
  1010. FLAGMASK(Type == ttMove, cpDelete);
  1011. bool ToTemp = (Temp && (Direction == tdToLocal));
  1012. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1013. {
  1014. bool DisableNewerOnly =
  1015. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1016. ToTemp;
  1017. Options |=
  1018. FLAGMASK(ToTemp, coTemp) |
  1019. FLAGMASK(!Terminal->IsCapable[fsBackgroundTransfers], coDisableQueue) |
  1020. coDoNotShowAgain;
  1021. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1022. int CopyParamAttrs = (Direction == tdToRemote ?
  1023. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1024. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1025. int OutputOptions =
  1026. FLAGMASK(DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto),
  1027. cooDoNotShowAgain);
  1028. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1029. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1030. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1031. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions);
  1032. if (Result)
  1033. {
  1034. if (FLAGSET(OutputOptions, cooDoNotShowAgain))
  1035. {
  1036. if (DragDrop)
  1037. {
  1038. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1039. {
  1040. PopupTrayBalloon(NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation,
  1041. NULL, 0, EnableDDTransferConfirmation, NULL);
  1042. }
  1043. WinConfiguration->DDTransferConfirmation = asOff;
  1044. }
  1045. else
  1046. {
  1047. WinConfiguration->ConfirmTransferring = false;
  1048. }
  1049. }
  1050. else
  1051. {
  1052. // User explicitly unchecked "do not show again",
  1053. // so show him the dialog the next time
  1054. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1055. {
  1056. WinConfiguration->DDTransferConfirmation = asOn;
  1057. }
  1058. }
  1059. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1060. }
  1061. }
  1062. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fsBackgroundTransfers])
  1063. {
  1064. Configuration->Usage->Inc(L"TransfersOnBackground");
  1065. // these parameter are known only after transfer dialog
  1066. Params |=
  1067. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1068. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1069. Result = false;
  1070. ClearTransferSourceSelection(Direction);
  1071. }
  1072. return Result;
  1073. }
  1074. //---------------------------------------------------------------------------
  1075. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1076. {
  1077. if (FOnFileOperationFinished != NULL)
  1078. {
  1079. FOnFileOperationFinished(UnicodeString(), true);
  1080. }
  1081. else
  1082. {
  1083. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1084. if (HasDirView[Side])
  1085. {
  1086. DirView(Side)->SelectAll(smNone);
  1087. }
  1088. }
  1089. }
  1090. //---------------------------------------------------------------------------
  1091. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1092. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1093. const UnicodeString TargetDirectory, const TGUICopyParamType & CopyParam,
  1094. int Params)
  1095. {
  1096. DebugAssert(Queue != NULL);
  1097. bool SingleFile = false;
  1098. if (FileList->Count == 1)
  1099. {
  1100. if (Direction == tdToRemote)
  1101. {
  1102. UnicodeString FileName = FileList->Strings[0];
  1103. SingleFile = FileExists(ApiPath(FileName));
  1104. }
  1105. else
  1106. {
  1107. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1108. SingleFile = !File->IsDirectory;
  1109. }
  1110. }
  1111. TQueueItem * QueueItem;
  1112. if (Direction == tdToRemote)
  1113. {
  1114. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1115. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1116. }
  1117. else
  1118. {
  1119. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1120. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1121. }
  1122. AddQueueItem(Queue, QueueItem, Terminal);
  1123. }
  1124. //---------------------------------------------------------------------------
  1125. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TTerminal * Terminal)
  1126. {
  1127. if (Queue->IsEmpty)
  1128. {
  1129. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  1130. ManagedTerminal->QueueOperationStart = Now();
  1131. }
  1132. Queue->AddItem(QueueItem);
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1136. {
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1140. {
  1141. DebugAssert(FDocks != NULL);
  1142. for (int Index = 0; Index < ComponentCount; Index++)
  1143. {
  1144. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1145. if ((Dock != NULL) && (Dock->Tag == 0))
  1146. {
  1147. FDocks->Add(Dock);
  1148. }
  1149. }
  1150. CollectItemsWithTextDisplayMode(this);
  1151. ConfigurationChanged();
  1152. QueuePanel->Height =
  1153. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1154. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1155. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1156. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1157. }
  1158. //---------------------------------------------------------------------------
  1159. void __fastcall TCustomScpExplorerForm::StoreParams()
  1160. {
  1161. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1162. WinConfiguration->QueueView.HeightPixelsPerInch = GetControlPixelsPerInch(this);
  1163. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1164. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1165. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1166. }
  1167. //---------------------------------------------------------------------------
  1168. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1169. {
  1170. if (!FFormRestored)
  1171. {
  1172. FFormRestored = true;
  1173. RestoreFormParams();
  1174. }
  1175. TForm::CreateParams(Params);
  1176. }
  1177. //---------------------------------------------------------------------------
  1178. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1179. {
  1180. DebugAssert(FDocks != NULL);
  1181. for (int Index = 0; Index < FDocks->Count; Index++)
  1182. {
  1183. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1184. }
  1185. }
  1186. //---------------------------------------------------------------------------
  1187. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1188. {
  1189. SetDockAllowDrag(true);
  1190. while (!ButtonsStr.IsEmpty())
  1191. {
  1192. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1193. UnicodeString Name = CutToChar(S, L'=', true);
  1194. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1195. {
  1196. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1197. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1198. {
  1199. while (!S.IsEmpty())
  1200. {
  1201. UnicodeString S2 = CutToChar(S, L',', true);
  1202. UnicodeString Name = CutToChar(S2, L':', true);
  1203. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1204. {
  1205. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1206. if (SameText(GetToolbarItemName(Item), Name))
  1207. {
  1208. // forward compatibility
  1209. UnicodeString S3 = CutToChar(S2, L':', true);
  1210. bool Visible = StrToIntDef(S3, 0);
  1211. Item->Visible = Visible;
  1212. }
  1213. }
  1214. }
  1215. }
  1216. }
  1217. }
  1218. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1219. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1220. }
  1221. //---------------------------------------------------------------------------
  1222. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1223. {
  1224. UnicodeString Result;
  1225. SetDockAllowDrag(true);
  1226. Result = ::GetToolbarsLayoutStr(this);
  1227. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1228. return Result;
  1229. }
  1230. //---------------------------------------------------------------------------
  1231. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1232. {
  1233. UnicodeString Result;
  1234. if (Item->Action != NULL)
  1235. {
  1236. Result = Item->Action->Name;
  1237. Result = RemoveSuffix(Result, L"Action");
  1238. }
  1239. else
  1240. {
  1241. Result = Item->Name;
  1242. Result = RemoveSuffix(Result, L"SubmenuItem");
  1243. Result = RemoveSuffix(Result, L"Item");
  1244. }
  1245. return Result;
  1246. }
  1247. //---------------------------------------------------------------------------
  1248. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1249. {
  1250. UnicodeString Result;
  1251. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1252. {
  1253. UnicodeString ToolbarStr;
  1254. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1255. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1256. {
  1257. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1258. {
  1259. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1260. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1261. // Once we introduce any buttons that aer hidden by default, we would have to remember their initial state
  1262. // and save the changes here only.
  1263. if (!Item->Visible)
  1264. {
  1265. UnicodeString Name = GetToolbarItemName(Item);
  1266. DebugAssert(Name.Pos(L"TBX") == 0);
  1267. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1268. }
  1269. }
  1270. }
  1271. if (!ToolbarStr.IsEmpty())
  1272. {
  1273. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1274. }
  1275. }
  1276. return Result;
  1277. }
  1278. //---------------------------------------------------------------------------
  1279. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1280. {
  1281. DebugAssert(FProgressForm == NULL);
  1282. FProgressForm =
  1283. new TProgressForm(Application, (FTransferResumeList != NULL), Terminal->IsCapable[fsSkipTransfer], SynchronizeProgress);
  1284. FProgressForm->DeleteLocalToRecycleBin =
  1285. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1286. FProgressForm->DeleteRemoteToRecycleBin =
  1287. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1288. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1289. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1290. LockWindow();
  1291. if (FTaskbarList != NULL)
  1292. {
  1293. // Actually, do not know what hides the progress once the operation finishes
  1294. SetTaskbarListProgressState(TBPF_NORMAL);
  1295. }
  1296. }
  1297. //---------------------------------------------------------------------------
  1298. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1299. {
  1300. UnlockWindow();
  1301. SAFE_DESTROY(FProgressForm);
  1302. SetQueueProgress();
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1306. TFileOperationProgressType & ProgressData)
  1307. {
  1308. // Download to temporary local directory
  1309. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1310. {
  1311. bool Continue = true;
  1312. FPendingTempSpaceWarn = false;
  1313. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1314. if (!Continue)
  1315. {
  1316. Abort();
  1317. }
  1318. }
  1319. // operation is being executed and we still didn't show up progress form
  1320. if (ProgressData.InProgress && !FProgressForm)
  1321. {
  1322. CreateProgressForm(NULL);
  1323. // When main window is hidden, synchronisation form does not exist (we do not get here during synchronization - only comparing),
  1324. // we suppose "/upload" or URL download mode
  1325. if (!Visible && (ProgressData.Operation != foCalculateSize) &&
  1326. (ProgressData.Operation != foCalculateChecksum) &&
  1327. // Hack to prevent renames from DoSynchronizeMove (synchronize checklist) closing the connection
  1328. (ProgressData.Operation != foRemoteMove) &&
  1329. (FSynchronizeProgressForm == NULL) &&
  1330. !FStandaloneEditing)
  1331. {
  1332. FProgressForm->OnceDoneOperation = odoDisconnect;
  1333. }
  1334. }
  1335. // operation is finished (or terminated), so we hide progress form
  1336. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1337. {
  1338. DestroyProgressForm();
  1339. if (ProgressData.Operation == foCalculateSize)
  1340. {
  1341. // When calculating size before transfer, the abort caused by
  1342. // cancel flag set due to "MoveToQueue" below,
  1343. // is not propagated back to us in ExecuteFileOperation,
  1344. // as it is silently swallowed.
  1345. // So we explicitly (re)throw it here.
  1346. if (FMoveToQueue)
  1347. {
  1348. Abort();
  1349. }
  1350. }
  1351. else
  1352. {
  1353. if ((ProgressData.Cancel == csContinue) &&
  1354. !FAutoOperation)
  1355. {
  1356. OperationComplete(ProgressData.StartTime);
  1357. }
  1358. }
  1359. }
  1360. if (FProgressForm &&
  1361. // Can happen only during synchronization, when ending one of the operations
  1362. ProgressData.InProgress)
  1363. {
  1364. FProgressForm->SetProgressData(ProgressData);
  1365. if (FTaskbarList != NULL)
  1366. {
  1367. DebugAssert(ProgressData.InProgress);
  1368. SetTaskbarListProgressValue(&ProgressData);
  1369. }
  1370. if (FProgressForm->Cancel > csContinue)
  1371. {
  1372. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1373. if (FProgressForm->Cancel == csCancelFile)
  1374. {
  1375. FProgressForm->ClearCancel();
  1376. }
  1377. // cancel cancels even the move
  1378. FMoveToQueue = false;
  1379. }
  1380. else if (FProgressForm->MoveToQueue)
  1381. {
  1382. FMoveToQueue = true;
  1383. ProgressData.SetCancelAtLeast(csCancel);
  1384. }
  1385. if ((FTransferResumeList != NULL) &&
  1386. ProgressData.InProgress &&
  1387. ((ProgressData.Operation == foCopy) || (ProgressData.Operation == foMove)) &&
  1388. !ProgressData.FullFileName.IsEmpty())
  1389. {
  1390. if ((FTransferResumeList->Count == 0) ||
  1391. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1392. {
  1393. // note that we do not recognize directories from files here
  1394. FTransferResumeList->Add(ProgressData.FullFileName);
  1395. }
  1396. }
  1397. }
  1398. }
  1399. //---------------------------------------------------------------------------
  1400. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1401. const TDateTime & StartTime)
  1402. {
  1403. if (GUIConfiguration->BeepOnFinish &&
  1404. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1405. {
  1406. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1407. DWORD Sound;
  1408. if (!ExtractFileExt(BeepSound).IsEmpty())
  1409. {
  1410. Sound = SND_FILENAME;
  1411. }
  1412. else
  1413. {
  1414. Sound = SND_ALIAS;
  1415. }
  1416. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1417. }
  1418. }
  1419. //---------------------------------------------------------------------------
  1420. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1421. TFileOperationProgressType & ProgressData)
  1422. {
  1423. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1424. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1425. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1426. FileOperationProgress(ProgressData);
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1430. {
  1431. UnicodeString Result;
  1432. if (FProgressForm != NULL)
  1433. {
  1434. Result = FProgressForm->ProgressStr();
  1435. }
  1436. return Result;
  1437. }
  1438. //---------------------------------------------------------------------------
  1439. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1440. bool DragDrop)
  1441. {
  1442. return (!DragDrop && (DropSourceControl == NULL)) ||
  1443. (DropSourceControl == RemoteDirView);
  1444. }
  1445. //---------------------------------------------------------------------------
  1446. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1447. TFileOperation Operation, TOperationSide Side,
  1448. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1449. TOnceDoneOperation & OnceDoneOperation)
  1450. {
  1451. if (!FAutoOperation)
  1452. {
  1453. // no selection on "/upload", form servers only as event handler
  1454. // (it is not displayed)
  1455. if (PanelOperation(Side, FDragDropOperation) &&
  1456. Visible && (Operation != foCalculateSize) &&
  1457. (Operation != foGetProperties) && (Operation != foCalculateChecksum))
  1458. {
  1459. if (FOnFileOperationFinished != NULL)
  1460. {
  1461. FOnFileOperationFinished(FileName, Success);
  1462. }
  1463. else
  1464. {
  1465. TCustomDirView * DView = DirView(Side);
  1466. UnicodeString FileNameOnly = ExtractFileName(FileName, (Side == osRemote));
  1467. TListItem *Item = DView->FindFileItem(FileNameOnly);
  1468. // this can happen when local drive is unplugged in the middle of the operation
  1469. if (Item != NULL)
  1470. {
  1471. if (Success) Item->Selected = false;
  1472. DView->MakeProgressVisible(Item);
  1473. }
  1474. }
  1475. }
  1476. if ((Operation == foCopy) || (Operation == foMove))
  1477. {
  1478. if (Side == osLocal)
  1479. {
  1480. Configuration->Usage->Inc(L"UploadedFiles");
  1481. }
  1482. else
  1483. {
  1484. Configuration->Usage->Inc(L"DownloadedFiles");
  1485. }
  1486. }
  1487. }
  1488. if (Success && (FSynchronizeController != NULL))
  1489. {
  1490. if (Operation == foCopy)
  1491. {
  1492. DebugAssert(Side == osLocal);
  1493. FSynchronizeController->LogOperation(soUpload, FileName);
  1494. }
  1495. else if (Operation == foDelete)
  1496. {
  1497. DebugAssert(Side == osRemote);
  1498. FSynchronizeController->LogOperation(soDelete, FileName);
  1499. }
  1500. }
  1501. if (FProgressForm)
  1502. {
  1503. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1504. }
  1505. }
  1506. //---------------------------------------------------------------------------
  1507. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1508. TFileOperation Operation, TOperationSide Side,
  1509. bool Temp, const UnicodeString & FileName, Boolean Success,
  1510. TOnceDoneOperation & OnceDoneOperation)
  1511. {
  1512. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1513. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1514. OnceDoneOperation);
  1515. }
  1516. //---------------------------------------------------------------------------
  1517. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1518. {
  1519. DebugAssert(GetSide(Side) == osRemote);
  1520. DebugUsedParam(Side);
  1521. return RemoteDirView;
  1522. }
  1523. //---------------------------------------------------------------------------
  1524. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1525. {
  1526. DebugAssert(GetSide(Side) == osRemote);
  1527. DebugUsedParam(Side);
  1528. return (Terminal != NULL);
  1529. }
  1530. //---------------------------------------------------------------------------
  1531. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1532. TOperationSide Side, int FilesOnly)
  1533. {
  1534. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1535. }
  1536. //---------------------------------------------------------------------------
  1537. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1538. TOperationSide Side, int FilesOnly)
  1539. {
  1540. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1541. }
  1542. //---------------------------------------------------------------------------
  1543. struct THistoryItemData
  1544. {
  1545. short int Side;
  1546. short int Index;
  1547. };
  1548. //---------------------------------------------------------------------------
  1549. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1550. {
  1551. DirView(Side)->HistoryGo(Index);
  1552. }
  1553. //---------------------------------------------------------------------------
  1554. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1555. {
  1556. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1557. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1558. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1562. bool Back)
  1563. {
  1564. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1565. {
  1566. TCustomDirView * DView = DirView(Side);
  1567. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1568. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1569. if (ICount > 10)
  1570. {
  1571. ICount = 10;
  1572. }
  1573. Menu->Items->Clear();
  1574. THistoryItemData Data;
  1575. Data.Side = Side;
  1576. for (short int i = 1; i <= ICount; i++)
  1577. {
  1578. TTBCustomItem * Item = new TTBXItem(Menu);
  1579. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1580. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, (Side == osRemote));
  1581. Item->Hint = DView->HistoryPath[Data.Index];
  1582. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1583. Item->Tag = *reinterpret_cast<int*>(&Data);
  1584. Item->OnClick = HistoryItemClick;
  1585. Menu->Items->Add(Item);
  1586. }
  1587. }
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1591. TOperationSide Side, bool Back)
  1592. {
  1593. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1594. {
  1595. // workaround
  1596. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1597. // operator new allocates memory in Pascal code, but calls inline
  1598. // contructor in C++, leading in problems, the function does
  1599. // both in Pascal code
  1600. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1601. UpdateHistoryMenu(Side, Back);
  1602. }
  1603. return FHistoryMenu[Side == osLocal][Back];
  1604. }
  1605. //---------------------------------------------------------------------------
  1606. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1607. TCustomDirView *Sender)
  1608. {
  1609. TOperationSide Side = (Sender == DirView(osRemote) ? osRemote : osLocal);
  1610. UpdateHistoryMenu(Side, true);
  1611. UpdateHistoryMenu(Side, false);
  1612. }
  1613. //---------------------------------------------------------------------------
  1614. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1615. {
  1616. // remote custom commands can be executed only if the server supports shell commands
  1617. // or have secondary shell
  1618. return (FTerminal != NULL) && (FTerminal->IsCapable[fcSecondaryShell] || FTerminal->IsCapable[fcShellAnyCommand]);
  1619. }
  1620. //---------------------------------------------------------------------------
  1621. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1622. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1623. {
  1624. int Result;
  1625. TFileCustomCommand RemoteCustomCommand;
  1626. TLocalCustomCommand LocalCustomCommand;
  1627. TFileCustomCommand * NonInteractiveCustomCommand =
  1628. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1629. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1630. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1631. if (FLAGCLEAR(Command.Params, ccLocal))
  1632. {
  1633. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1634. // custom command that does not operate with files can be executed anytime ...
  1635. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1636. {
  1637. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1638. {
  1639. // ... but do not show such command in remote file menu (TODO)
  1640. Result = AllowedState;
  1641. }
  1642. else
  1643. {
  1644. Result = -1;
  1645. }
  1646. }
  1647. else
  1648. {
  1649. if ((ListType == ccltAll) || (ListType == ccltFile))
  1650. {
  1651. Result = ((FCurrentSide == osRemote) && DirView(osRemote)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1652. }
  1653. else
  1654. {
  1655. Result = -1;
  1656. }
  1657. }
  1658. }
  1659. else
  1660. {
  1661. // custom command that does not operate with files can be executed anytime
  1662. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1663. {
  1664. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1665. }
  1666. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1667. {
  1668. if ((ListType == ccltAll) || (ListType == ccltFile))
  1669. {
  1670. // special case is "diff"-style command that can be executed over any side,
  1671. // if we have both sides
  1672. Result =
  1673. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1674. // directly (instead of EnableSelectedOperation) to pass
  1675. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1676. ((HasDirView[osLocal] && DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1677. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1678. }
  1679. else if (ListType == ccltBoth)
  1680. {
  1681. Result = 1;
  1682. }
  1683. else
  1684. {
  1685. Result = -1;
  1686. }
  1687. }
  1688. else
  1689. {
  1690. if ((ListType == ccltAll) || (ListType == ccltFile))
  1691. {
  1692. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1693. }
  1694. else
  1695. {
  1696. Result = -1;
  1697. }
  1698. }
  1699. }
  1700. return Result;
  1701. }
  1702. //---------------------------------------------------------------------------
  1703. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1704. TStrings * FileList, const TCustomCommandType & ACommand,
  1705. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1706. {
  1707. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1708. {
  1709. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1710. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1711. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1712. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1713. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1714. bool Capture =
  1715. FLAGSET(ACommand.Params, ccShowResults) ||
  1716. FLAGSET(ACommand.Params, ccCopyResults) ||
  1717. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1718. TCaptureOutputEvent OutputEvent = NULL;
  1719. DebugAssert(FCapturedLog == NULL);
  1720. if (Capture)
  1721. {
  1722. FCapturedLog = new TStringList();
  1723. OutputEvent = TerminalCaptureLog;
  1724. }
  1725. try
  1726. {
  1727. if (!RemoteCustomCommand.IsFileCommand(Command))
  1728. {
  1729. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1730. OutputEvent);
  1731. }
  1732. else
  1733. {
  1734. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1735. }
  1736. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1737. {
  1738. if (FLAGSET(ACommand.Params, ccCopyResults))
  1739. {
  1740. CopyToClipboard(FCapturedLog);
  1741. }
  1742. if (FLAGSET(ACommand.Params, ccShowResults))
  1743. {
  1744. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1745. }
  1746. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1747. {
  1748. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1749. }
  1750. }
  1751. }
  1752. __finally
  1753. {
  1754. SAFE_DESTROY(FCapturedLog);
  1755. }
  1756. }
  1757. }
  1758. //---------------------------------------------------------------------------
  1759. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1760. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1761. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1762. {
  1763. TStrings * LocalFileList = NULL;
  1764. TStrings * RemoteFileList = NULL;
  1765. TStrings * RemoteFileListFull = NULL;
  1766. try
  1767. {
  1768. if (LocalFileCommand)
  1769. {
  1770. if (ALocalFileList == NULL)
  1771. {
  1772. DebugAssert(HasDirView[osLocal]);
  1773. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1774. // directly (instead of EnableSelectedOperation) to pass
  1775. // false to FocusedFileOnlyWhenFocused
  1776. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1777. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1778. }
  1779. else
  1780. {
  1781. LocalFileList = ALocalFileList;
  1782. }
  1783. if (FileListCommand)
  1784. {
  1785. if (LocalFileList->Count != 1)
  1786. {
  1787. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  1788. }
  1789. }
  1790. else
  1791. {
  1792. if ((LocalFileList->Count != 1) &&
  1793. (FileList->Count != 1) &&
  1794. (LocalFileList->Count != FileList->Count))
  1795. {
  1796. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  1797. }
  1798. }
  1799. }
  1800. UnicodeString RootTempDir;
  1801. UnicodeString TempDir;
  1802. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  1803. if (!RemoteFiles)
  1804. {
  1805. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  1806. }
  1807. try
  1808. {
  1809. TDateTimes RemoteFileTimes;
  1810. if (RemoteFiles)
  1811. {
  1812. RemoteFileList = FileList;
  1813. }
  1814. else
  1815. {
  1816. RemoteFileList = new TStringList();
  1817. TMakeLocalFileListParams MakeFileListParam;
  1818. MakeFileListParam.FileList = RemoteFileList;
  1819. MakeFileListParam.FileTimes = &RemoteFileTimes;
  1820. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  1821. MakeFileListParam.Recursive =
  1822. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  1823. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  1824. if (!MakeFileListParam.Recursive)
  1825. {
  1826. RemoteFileTimes.clear();
  1827. RemoteFileListFull = new TStringList();
  1828. MakeFileListParam.FileList = RemoteFileListFull;
  1829. MakeFileListParam.Recursive = true;
  1830. MakeFileListParam.IncludeDirs = false;
  1831. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  1832. }
  1833. else
  1834. {
  1835. RemoteFileListFull = RemoteFileList;
  1836. }
  1837. }
  1838. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  1839. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  1840. if (!NonBlocking)
  1841. {
  1842. int Count;
  1843. if (FileListCommand)
  1844. {
  1845. Count = 1;
  1846. }
  1847. else if (LocalFileCommand)
  1848. {
  1849. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  1850. }
  1851. else
  1852. {
  1853. Count = RemoteFileList->Count;
  1854. }
  1855. Progress.Start(foCustomCommand, osRemote, Count);
  1856. DebugAssert(FProgressForm != NULL);
  1857. FProgressForm->ReadOnly = true;
  1858. }
  1859. try
  1860. {
  1861. if (FileListCommand)
  1862. {
  1863. UnicodeString LocalFile;
  1864. // MakeFileList does not delimit filenames
  1865. UnicodeString FileList = MakeFileList(RemoteFileList);
  1866. if (LocalFileCommand)
  1867. {
  1868. DebugAssert(LocalFileList->Count == 1);
  1869. LocalFile = LocalFileList->Strings[0];
  1870. }
  1871. TLocalCustomCommand CustomCommand(Data,
  1872. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  1873. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  1874. if (NonBlocking)
  1875. {
  1876. DebugAssert(!POutput);
  1877. ExecuteShellChecked(ShellCommand);
  1878. }
  1879. else
  1880. {
  1881. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  1882. }
  1883. }
  1884. else if (LocalFileCommand)
  1885. {
  1886. if (LocalFileList->Count == 1)
  1887. {
  1888. UnicodeString LocalFile = LocalFileList->Strings[0];
  1889. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  1890. {
  1891. UnicodeString FileName = RemoteFileList->Strings[Index];
  1892. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  1893. Progress.SetFile(FileNameForProgress);
  1894. TLocalCustomCommand CustomCommand(Data,
  1895. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  1896. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1897. TOnceDoneOperation OnceDoneOperation;
  1898. // Do not unselect anything, as it won't work with two panels anyway
  1899. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1900. }
  1901. }
  1902. else if (RemoteFileList->Count == 1)
  1903. {
  1904. UnicodeString FileName = RemoteFileList->Strings[0];
  1905. for (int Index = 0; Index < LocalFileList->Count; Index++)
  1906. {
  1907. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  1908. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  1909. Progress.SetFile(LocalFileNameOnly);
  1910. TLocalCustomCommand CustomCommand(
  1911. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1912. FileName, LocalFileName, L"");
  1913. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1914. TOnceDoneOperation OnceDoneOperation;
  1915. // Do not unselect anything, as it won't work with two panels anyway
  1916. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1917. }
  1918. }
  1919. else
  1920. {
  1921. if (LocalFileList->Count != RemoteFileList->Count)
  1922. {
  1923. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  1924. }
  1925. for (int Index = 0; Index < LocalFileList->Count; Index++)
  1926. {
  1927. UnicodeString FileName = RemoteFileList->Strings[Index];
  1928. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  1929. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  1930. Progress.SetFile(LocalFileNameOnly); // sic
  1931. TLocalCustomCommand CustomCommand(
  1932. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1933. FileName, LocalFileName, L"");
  1934. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1935. TOnceDoneOperation OnceDoneOperation;
  1936. // Do not unselect anything, as it won't work with two panels anyway
  1937. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1938. }
  1939. }
  1940. }
  1941. else
  1942. {
  1943. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  1944. {
  1945. UnicodeString FileName = RemoteFileList->Strings[Index];
  1946. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  1947. Progress.SetFile(FileNameForProgress);
  1948. TLocalCustomCommand CustomCommand(Data,
  1949. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1950. FileName, L"", L"");
  1951. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1952. TOnceDoneOperation OnceDoneOperation;
  1953. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  1954. }
  1955. }
  1956. }
  1957. __finally
  1958. {
  1959. if (!NonBlocking)
  1960. {
  1961. Progress.Stop();
  1962. }
  1963. }
  1964. DebugAssert(!FAutoOperation);
  1965. if (!RemoteFiles)
  1966. {
  1967. TempDir = IncludeTrailingBackslash(TempDir);
  1968. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  1969. {
  1970. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  1971. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  1972. // Skip directories, process only nested files.
  1973. // The check is redundant as FileAge fails for directories anyway.
  1974. !DirectoryExists(FileName))
  1975. {
  1976. UnicodeString RemoteDir =
  1977. UnixExtractFileDir(
  1978. UnixIncludeTrailingBackslash(FTerminal->CurrentDirectory) +
  1979. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  1980. TDateTime NewTime;
  1981. if (FileAge(FileName, NewTime) &&
  1982. (NewTime != RemoteFileTimes[Index]))
  1983. {
  1984. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  1985. TemporaryFileCopyParam(CopyParam);
  1986. CopyParam.FileMask = L"";
  1987. FAutoOperation = true;
  1988. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  1989. TemporaryFilesList->Add(FileName);
  1990. FTerminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  1991. }
  1992. }
  1993. }
  1994. }
  1995. }
  1996. __finally
  1997. {
  1998. FAutoOperation = false;
  1999. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2000. {
  2001. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  2002. }
  2003. }
  2004. }
  2005. __finally
  2006. {
  2007. if (RemoteFileList != FileList)
  2008. {
  2009. delete RemoteFileList;
  2010. }
  2011. if (LocalFileList != ALocalFileList)
  2012. {
  2013. delete LocalFileList;
  2014. }
  2015. if (RemoteFileListFull != RemoteFileList)
  2016. {
  2017. delete RemoteFileListFull;
  2018. }
  2019. }
  2020. }
  2021. //---------------------------------------------------------------------------
  2022. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2023. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2024. bool FileListCommand, UnicodeString * POutput)
  2025. {
  2026. std::unique_ptr<TStrings> SelectedFileList(DirView(osLocal)->CreateFileList(false, true, NULL));
  2027. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2028. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2029. {
  2030. UnicodeString FileName = SelectedFileList->Strings[Index];
  2031. if (DirectoryExists(FileName))
  2032. {
  2033. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2034. {
  2035. LocalFileList->Add(FileName);
  2036. }
  2037. if (FLAGSET(ACommand.Params, ccRecursive))
  2038. {
  2039. TMakeLocalFileListParams MakeFileListParam;
  2040. MakeFileListParam.FileList = LocalFileList.get();
  2041. MakeFileListParam.FileTimes = NULL;
  2042. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2043. MakeFileListParam.Recursive = true;
  2044. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2045. }
  2046. }
  2047. else
  2048. {
  2049. LocalFileList->Add(FileName);
  2050. }
  2051. }
  2052. if (FileListCommand)
  2053. {
  2054. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2055. TLocalCustomCommand CustomCommand(
  2056. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2057. L"", L"", FileList);
  2058. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2059. }
  2060. else
  2061. {
  2062. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2063. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2064. DebugAssert(FProgressForm != NULL);
  2065. FProgressForm->ReadOnly = true;
  2066. try
  2067. {
  2068. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2069. {
  2070. UnicodeString FileName = LocalFileList->Strings[Index];
  2071. Progress.SetFile(FileName);
  2072. TLocalCustomCommand CustomCommand(
  2073. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2074. FileName, L"", L"");
  2075. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2076. TOnceDoneOperation OnceDoneOperation;
  2077. Progress.Finish(FileName, true, OnceDoneOperation);
  2078. }
  2079. }
  2080. __finally
  2081. {
  2082. Progress.Stop();
  2083. }
  2084. }
  2085. }
  2086. //---------------------------------------------------------------------------
  2087. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2088. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2089. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2090. {
  2091. TLocalCustomCommand LocalCustomCommand(Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory());
  2092. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2093. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2094. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2095. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2096. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2097. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2098. std::unique_ptr<UnicodeString> POutput;
  2099. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2100. FLAGSET(ACommand.Params, ccCopyResults))
  2101. {
  2102. POutput.reset(new UnicodeString());
  2103. }
  2104. if (!LocalCustomCommand.IsFileCommand(Command))
  2105. {
  2106. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2107. }
  2108. // remote files?
  2109. else if ((FCurrentSide == osRemote) || LocalFileCommand)
  2110. {
  2111. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2112. }
  2113. // local files
  2114. else
  2115. {
  2116. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2117. }
  2118. if (POutput.get() != NULL)
  2119. {
  2120. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2121. int P = POutput->Pos(sLineBreak);
  2122. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2123. {
  2124. POutput->SetLength(P - 1);
  2125. }
  2126. // Copy even empty output to clipboard
  2127. if (FLAGSET(ACommand.Params, ccCopyResults))
  2128. {
  2129. CopyToClipboard(*POutput);
  2130. }
  2131. // But do not show an empty message box.
  2132. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2133. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2134. !POutput->IsEmpty())
  2135. {
  2136. TClipboardHandler ClipboardHandler;
  2137. ClipboardHandler.Text = *POutput;
  2138. TMessageParams Params;
  2139. TQueryButtonAlias Aliases[1];
  2140. Aliases[0].Button = qaRetry;
  2141. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2142. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2143. Params.Aliases = Aliases;
  2144. Params.AliasesCount = LENOF(Aliases);
  2145. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2146. }
  2147. }
  2148. }
  2149. //---------------------------------------------------------------------------
  2150. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2151. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2152. {
  2153. TCustomCommandData Data(Terminal);
  2154. UnicodeString Site = Terminal->SessionData->SessionKey;
  2155. UnicodeString HelpKeyword = ACommand.HomePage;
  2156. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2157. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2158. {
  2159. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2160. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2161. {
  2162. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, Terminal->CurrentDirectory));
  2163. }
  2164. else
  2165. {
  2166. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory()));
  2167. }
  2168. if (!DoCustomCommandOptionsDialog(
  2169. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2170. {
  2171. Abort();
  2172. }
  2173. }
  2174. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2175. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2176. {
  2177. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2178. }
  2179. else
  2180. {
  2181. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2182. }
  2183. }
  2184. //---------------------------------------------------------------------------
  2185. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2186. const TCustomCommandType & Command)
  2187. {
  2188. DebugAssert(FCustomCommandLocalFileList != NULL);
  2189. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2190. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2191. TStrings * LocalFileList = new TStringList();
  2192. TStrings * RemoteFileList = new TStringList();
  2193. try
  2194. {
  2195. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2196. {
  2197. LocalFileList->Clear();
  2198. LocalFileList->AddObject(
  2199. FCustomCommandLocalFileList->Strings[Index],
  2200. FCustomCommandLocalFileList->Objects[Index]);
  2201. RemoteFileList->Clear();
  2202. RemoteFileList->AddObject(
  2203. FCustomCommandRemoteFileList->Strings[Index],
  2204. FCustomCommandRemoteFileList->Objects[Index]);
  2205. CustomCommand(RemoteFileList, Command, LocalFileList);
  2206. }
  2207. }
  2208. __finally
  2209. {
  2210. delete LocalFileList;
  2211. delete RemoteFileList;
  2212. }
  2213. }
  2214. //---------------------------------------------------------------------------
  2215. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2216. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2217. {
  2218. delete FCustomCommandLocalFileList;
  2219. delete FCustomCommandRemoteFileList;
  2220. // takeover ownership,
  2221. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2222. FCustomCommandLocalFileList = LocalFileList;
  2223. FCustomCommandRemoteFileList = RemoteFileList;
  2224. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2225. if (Button != NULL)
  2226. {
  2227. FCustomCommandMenu->Items->Clear();
  2228. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth);
  2229. MenuPopup(FCustomCommandMenu, Button);
  2230. }
  2231. else
  2232. {
  2233. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2234. }
  2235. }
  2236. //---------------------------------------------------------------------------
  2237. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2238. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2239. {
  2240. DebugAssert(FCapturedLog != NULL);
  2241. if ((OutputType == cotOutput) || (OutputType == cotError))
  2242. {
  2243. FCapturedLog->Add(AddedLine);
  2244. }
  2245. }
  2246. //---------------------------------------------------------------------------
  2247. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2248. TOperationSide Side)
  2249. {
  2250. return (Side == osRemote) &&
  2251. ((Control == RemoteDirView) || (Control == RemoteDriveView));
  2252. }
  2253. //---------------------------------------------------------------------------
  2254. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2255. TOperationSide Side, TTBXCustomItem * Item, TDoubleClickAction DoubleClickAction)
  2256. {
  2257. TTBItemOptions O;
  2258. O = Item->Options;
  2259. TCustomDirView * DView = DirView(Side);
  2260. if ((DView->ItemFocused != NULL) &&
  2261. (WinConfiguration->DoubleClickAction == DoubleClickAction) &&
  2262. // when resolving links is disabled, default action is to enter the directory,
  2263. // no matter what DoubleClickAction is configured to
  2264. ((Side != osRemote) || Terminal->ResolvingSymlinks || Terminal->IsEncryptingFiles()) &&
  2265. // Can only Edit files, but can Open/Copy even directories
  2266. ((DoubleClickAction != dcaEdit) ||
  2267. !DView->ItemIsDirectory(DView->ItemFocused)))
  2268. {
  2269. Item->Options = O << tboDefault;
  2270. }
  2271. else
  2272. {
  2273. Item->Options = O >> tboDefault;
  2274. }
  2275. }
  2276. //---------------------------------------------------------------------------
  2277. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2278. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2279. {
  2280. TCustomDirView * DView = DirView(Side);
  2281. TListItem * Item = DView->ItemFocused;
  2282. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2283. EnableFocusedOperation[Side])
  2284. {
  2285. TPoint ClientPoint;
  2286. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2287. TPoint(0, 0) : MousePos;
  2288. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2289. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2290. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2291. }
  2292. }
  2293. //---------------------------------------------------------------------------
  2294. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2295. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2296. {
  2297. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, dcaOpen);
  2298. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, dcaEdit);
  2299. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, dcaCopy);
  2300. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2301. Handled = true;
  2302. }
  2303. //---------------------------------------------------------------------------
  2304. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2305. {
  2306. }
  2307. //---------------------------------------------------------------------------
  2308. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2309. {
  2310. DebugAssert(FErrorList == NULL);
  2311. if (WinConfiguration->ContinueOnError)
  2312. {
  2313. FErrorList = new TStringList();
  2314. Configuration->Usage->Inc(L"ContinuationsOnError");
  2315. }
  2316. NonVisualDataModule->StartBusy();
  2317. }
  2318. //---------------------------------------------------------------------------
  2319. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2320. {
  2321. NonVisualDataModule->EndBusy();
  2322. if (FErrorList)
  2323. {
  2324. HandleErrorList(FErrorList);
  2325. }
  2326. }
  2327. //---------------------------------------------------------------------------
  2328. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2329. const TCopyParamType & CopyParam)
  2330. {
  2331. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2332. {
  2333. Configuration->Usage->Inc(L"FileMaskUses");
  2334. }
  2335. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2336. {
  2337. Configuration->Usage->Inc(L"OperationMaskUses");
  2338. }
  2339. }
  2340. //---------------------------------------------------------------------------
  2341. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2342. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2343. {
  2344. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2345. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2346. TTransferOperationParam DefaultParam;
  2347. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2348. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2349. switch (Param.Queue)
  2350. {
  2351. case asOn:
  2352. CopyParam.Queue = true;
  2353. break;
  2354. case asOff:
  2355. CopyParam.Queue = false;
  2356. break;
  2357. case asAuto:
  2358. default:
  2359. // keep default
  2360. break;
  2361. }
  2362. bool Result =
  2363. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2364. if (Result)
  2365. {
  2366. DebugAssert(Terminal);
  2367. bool SelectionRestored = false;
  2368. TCustomDirView * DView = NULL;
  2369. if (HasDirView[Side])
  2370. {
  2371. DView = DirView(Side);
  2372. DView->SaveSelection();
  2373. DView->SaveSelectedNames();
  2374. }
  2375. UpdateCopyParamCounters(CopyParam);
  2376. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2377. DebugAssert(FTransferResumeList == NULL);
  2378. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2379. FMoveToQueue = false;
  2380. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2381. try
  2382. {
  2383. TStrings * PermanentFileList;
  2384. std::unique_ptr<TStrings> PermanentFileListOwner;
  2385. try
  2386. {
  2387. if (Side == osLocal)
  2388. {
  2389. PermanentFileList = FileList;
  2390. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2391. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2392. if (Operation == foMove)
  2393. {
  2394. ReloadLocalDirectory();
  2395. if (DView != NULL)
  2396. {
  2397. DView->RestoreSelection();
  2398. }
  2399. SelectionRestored = true;
  2400. }
  2401. }
  2402. else
  2403. {
  2404. // Clone the file list as it may refer to current directory files,
  2405. // which get destroyed, when the source directory is reloaded after foMove operation.
  2406. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2407. // But for a hotfix, we are not going to do such a big change.
  2408. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2409. PermanentFileList = PermanentFileListOwner.get();
  2410. try
  2411. {
  2412. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2413. }
  2414. __finally
  2415. {
  2416. if (Operation == foMove)
  2417. {
  2418. if (DView != NULL)
  2419. {
  2420. DView->RestoreSelection();
  2421. }
  2422. SelectionRestored = true;
  2423. }
  2424. ReloadLocalDirectory(Param.TargetDirectory);
  2425. }
  2426. }
  2427. }
  2428. catch (EAbort &)
  2429. {
  2430. if (FMoveToQueue)
  2431. {
  2432. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2433. DebugAssert(CopyParam.TransferSkipList == NULL);
  2434. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2435. if (TransferResumeList->Count > 0)
  2436. {
  2437. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2438. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2439. }
  2440. CopyParam.TransferSkipList = TransferResumeList.release();
  2441. // not really needed, just to keep it consistent with TransferResumeList
  2442. FTransferResumeList = NULL;
  2443. FMoveToQueue = false;
  2444. Configuration->Usage->Inc("MovesToBackground");
  2445. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2446. ClearTransferSourceSelection(Direction);
  2447. }
  2448. throw;
  2449. }
  2450. }
  2451. __finally
  2452. {
  2453. if (!SelectionRestored && (DView != NULL))
  2454. {
  2455. DView->DiscardSavedSelection();
  2456. }
  2457. FTransferResumeList = NULL;
  2458. }
  2459. }
  2460. return Result;
  2461. }
  2462. //---------------------------------------------------------------------------
  2463. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2464. TOperationSide Side, TStrings * FileList, void * Param)
  2465. {
  2466. DebugAssert(FileList->Count);
  2467. // We deliberately do not toggle alternative flag (Param), but use OR,
  2468. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2469. // shortcut of CurrentDeleteAlternativeAction
  2470. bool Alternative =
  2471. bool(Param) || UseAlternativeFunction();
  2472. bool Recycle;
  2473. if (Side == osLocal)
  2474. {
  2475. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2476. }
  2477. else
  2478. {
  2479. Recycle =
  2480. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2481. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2482. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2483. }
  2484. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2485. if (!Result)
  2486. {
  2487. UnicodeString Query;
  2488. if (FileList->Count == 1)
  2489. {
  2490. if (Side == osLocal)
  2491. {
  2492. Query = ExtractFileName(FileList->Strings[0]);
  2493. }
  2494. else
  2495. {
  2496. Query = UnixExtractFileName(FileList->Strings[0]);
  2497. }
  2498. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2499. }
  2500. else
  2501. {
  2502. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2503. }
  2504. TMessageParams Params(mpNeverAskAgainCheck);
  2505. Params.ImageName = L"Delete file";
  2506. unsigned int Answer =
  2507. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2508. if (Answer == qaNeverAskAgain)
  2509. {
  2510. Result = true;
  2511. if (Recycle)
  2512. {
  2513. WinConfiguration->ConfirmRecycling = false;
  2514. }
  2515. else
  2516. {
  2517. WinConfiguration->ConfirmDeleting = false;
  2518. }
  2519. }
  2520. else
  2521. {
  2522. Result = (Answer == qaOK);
  2523. }
  2524. }
  2525. if (Result)
  2526. {
  2527. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2528. }
  2529. return Result;
  2530. }
  2531. //---------------------------------------------------------------------------
  2532. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2533. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2534. {
  2535. TAutoBatch AutoBatch(this);
  2536. bool Result;
  2537. if ((Operation == foCopy) || (Operation == foMove))
  2538. {
  2539. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2540. }
  2541. else if (Operation == foRename)
  2542. {
  2543. DebugAssert(DirView(Side)->ItemFocused);
  2544. DirView(Side)->ItemFocused->EditCaption();
  2545. Result = true;
  2546. }
  2547. else if (Operation == foDelete)
  2548. {
  2549. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2550. }
  2551. else if (Operation == foSetProperties)
  2552. {
  2553. RemoteDirView->SaveSelectedNames();
  2554. Result = SetProperties(Side, FileList);
  2555. }
  2556. else if (Operation == foCustomCommand)
  2557. {
  2558. DebugAssert(Param);
  2559. DebugAssert(Side == osRemote);
  2560. RemoteDirView->SaveSelectedNames();
  2561. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2562. CustomCommand(FileList, *Command, NULL);
  2563. Result = true;
  2564. }
  2565. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2566. {
  2567. DebugAssert(Side == osRemote);
  2568. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2569. (Operation == foRemoteMove), reinterpret_cast<TTerminal *>(Param));
  2570. }
  2571. else if (Operation == foLock)
  2572. {
  2573. DebugAssert(Side == osRemote);
  2574. LockFiles(FileList, true);
  2575. Result = true;
  2576. }
  2577. else if (Operation == foUnlock)
  2578. {
  2579. DebugAssert(Side == osRemote);
  2580. LockFiles(FileList, false);
  2581. Result = true;
  2582. }
  2583. else
  2584. {
  2585. DebugFail();
  2586. }
  2587. return Result;
  2588. }
  2589. //---------------------------------------------------------------------------
  2590. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2591. {
  2592. if (Side == osCurrent)
  2593. {
  2594. Side = FCurrentSide;
  2595. }
  2596. return Side;
  2597. }
  2598. //---------------------------------------------------------------------------
  2599. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2600. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2601. {
  2602. Side = GetSide(Side);
  2603. bool Result;
  2604. TStrings * FileList = DirView(Side)->CreateFileList(OnFocused, (Side == osLocal), NULL);
  2605. try
  2606. {
  2607. Result = ExecuteFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2608. }
  2609. __finally
  2610. {
  2611. delete FileList;
  2612. }
  2613. return Result;
  2614. }
  2615. //---------------------------------------------------------------------------
  2616. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2617. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2618. bool NoConfirmation, void * Param)
  2619. {
  2620. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2621. {
  2622. if ((Operation == foCopy) || (Operation == foMove))
  2623. {
  2624. if (GetSide(Side) == osLocal)
  2625. {
  2626. Configuration->Usage->Inc(L"UploadsCommand");
  2627. }
  2628. else
  2629. {
  2630. Configuration->Usage->Inc(L"DownloadsCommand");
  2631. }
  2632. }
  2633. }
  2634. }
  2635. //---------------------------------------------------------------------------
  2636. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2637. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2638. {
  2639. TTransferOperationParam Param;
  2640. if ((WinConfiguration->Interface != ifCommander) ||
  2641. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2642. {
  2643. Flags &= ~cocShortCutHint;
  2644. }
  2645. TCustomDirView * DView = DirView(Side);
  2646. Param.Options =
  2647. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2648. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2649. if (FLAGSET(Flags, cocQueue))
  2650. {
  2651. Param.Queue = asOn;
  2652. }
  2653. else if (FLAGSET(Flags, cocNonQueue))
  2654. {
  2655. Param.Queue = asOff;
  2656. }
  2657. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2658. }
  2659. //---------------------------------------------------------------------------
  2660. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2661. {
  2662. try
  2663. {
  2664. if (ErrorList->Count)
  2665. {
  2666. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2667. if (MessageDialog(Message, qtError,
  2668. qaOK | qaCancel, HELP_NONE) == qaOK)
  2669. {
  2670. unsigned int Answer;
  2671. int Index = 0;
  2672. do
  2673. {
  2674. DebugAssert(Index >= 0 && Index < ErrorList->Count);
  2675. TQueryButtonAlias Aliases[2];
  2676. Aliases[0].Button = qaYes;
  2677. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2678. Aliases[1].Button = qaNo;
  2679. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2680. TMessageParams Params;
  2681. Params.Aliases = Aliases;
  2682. Params.AliasesCount = LENOF(Aliases);
  2683. Answer = MoreMessageDialog(
  2684. FMTLOAD(ERROR_LIST_NUMBER, (Index+1, ErrorList->Count, ErrorList->Strings[Index])),
  2685. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2686. (Index ? qaYes : 0) | (Index < ErrorList->Count - 1 ? qaNo : 0) |
  2687. qaOK, HELP_NONE, &Params);
  2688. if (Answer == qaNo)
  2689. {
  2690. Index++;
  2691. }
  2692. if (Answer == qaYes)
  2693. {
  2694. Index--;
  2695. }
  2696. }
  2697. while (Answer != qaOK);
  2698. }
  2699. }
  2700. }
  2701. __finally
  2702. {
  2703. TStrings * List = ErrorList;
  2704. ErrorList = NULL;
  2705. for (int i = 0; i < List->Count; i++)
  2706. {
  2707. delete List->Objects[i];
  2708. }
  2709. delete List;
  2710. }
  2711. }
  2712. //---------------------------------------------------------------------------
  2713. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  2714. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  2715. {
  2716. // needed for checking filemasks, as there's no directory object
  2717. // associated with the file object
  2718. File->FullFileName = FullFileName;
  2719. TFileMasks::TParams MaskParams;
  2720. MaskParams.Size = File->Size;
  2721. MaskParams.Modification = File->Modification;
  2722. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  2723. }
  2724. //---------------------------------------------------------------------------
  2725. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  2726. {
  2727. DebugAssert(!WinConfiguration->DisableOpenEdit);
  2728. Side = GetSide(Side);
  2729. TCustomDirView * DView = DirView(Side);
  2730. TListItem * FocusedItem = DView->ItemFocused;
  2731. UnicodeString Name;
  2732. if ((FocusedItem != NULL) && !DView->ItemIsParentDirectory(FocusedItem))
  2733. {
  2734. Name = DView->ItemFileName(FocusedItem);
  2735. }
  2736. else
  2737. {
  2738. Name = LoadStr(NEW_FILE);
  2739. }
  2740. UnicodeString Names = Name;
  2741. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  2742. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  2743. HELP_EDIT_NEW, History.get(), true))
  2744. {
  2745. while (!Names.IsEmpty())
  2746. {
  2747. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  2748. CustomWinConfiguration->History[L"EditFile"] = History.get();
  2749. UnicodeString TargetFileName;
  2750. UnicodeString LocalFileName;
  2751. UnicodeString RootTempDir;
  2752. UnicodeString TempDir;
  2753. UnicodeString RemoteDirectory;
  2754. bool ExistingFile = false;
  2755. if (Side == osRemote)
  2756. {
  2757. Name = AbsolutePath(FTerminal->CurrentDirectory, Name);
  2758. TRemoteFile * File = NULL;
  2759. if (FTerminal->FileExists(Name, &File))
  2760. {
  2761. try
  2762. {
  2763. ExecuteRemoteFile(Name, File, efDefaultEditor);
  2764. ExistingFile = true;
  2765. }
  2766. __finally
  2767. {
  2768. delete File;
  2769. }
  2770. }
  2771. if (!ExistingFile)
  2772. {
  2773. RemoteDirectory = UnixExtractFilePath(Name);
  2774. TemporaryDirectoryForRemoteFiles(
  2775. RemoteDirectory, GUIConfiguration->CurrentCopyParam, TempDir, RootTempDir);
  2776. TargetFileName = UnixExtractFileName(Name);
  2777. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2778. LocalFileName = TempDir +
  2779. // We probably do not want to trim the VMS version here
  2780. FTerminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  2781. }
  2782. }
  2783. else
  2784. {
  2785. if (ExtractFilePath(Name).IsEmpty())
  2786. {
  2787. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  2788. }
  2789. else
  2790. {
  2791. LocalFileName = ExpandFileName(Name);
  2792. }
  2793. TargetFileName = ExtractFileName(Name);
  2794. }
  2795. if (!ExistingFile)
  2796. {
  2797. if (!FileExists(ApiPath(LocalFileName)))
  2798. {
  2799. int File = FileCreate(ApiPath(LocalFileName));
  2800. if (File < 0)
  2801. {
  2802. if (!RootTempDir.IsEmpty())
  2803. {
  2804. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  2805. }
  2806. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  2807. }
  2808. else
  2809. {
  2810. FileClose(File);
  2811. }
  2812. }
  2813. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  2814. const TEditorData * ExternalEditor = NULL;
  2815. TFileMasks::TParams MaskParams; // size not known
  2816. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  2817. false, MaskParams);
  2818. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  2819. ExternalEditor, RootTempDir, RemoteDirectory);
  2820. }
  2821. }
  2822. }
  2823. }
  2824. //---------------------------------------------------------------------------
  2825. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  2826. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  2827. {
  2828. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  2829. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  2830. DebugAssert(ExecuteFileBy != efDefaultEditor);
  2831. return
  2832. ((ExecuteFileBy == efInternalEditor)) ||
  2833. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  2834. }
  2835. //---------------------------------------------------------------------------
  2836. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  2837. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  2838. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  2839. UnicodeString RemoteDirectory)
  2840. {
  2841. DebugAssert(!WinConfiguration->DisableOpenEdit);
  2842. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  2843. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  2844. DebugAssert(ExecuteFileBy != efDefaultEditor);
  2845. Side = GetSide(Side);
  2846. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  2847. if (Side == osRemote)
  2848. {
  2849. Data->Terminal = Terminal;
  2850. Data->Queue = Queue;
  2851. Data->SessionData = CloneCurrentSessionData();
  2852. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  2853. Data->RemoteDirectory = RemoteDirectory;
  2854. Data->SessionName = Terminal->SessionData->SessionName;
  2855. Data->LocalRootDirectory = LocalRootDirectory;
  2856. Data->OriginalFileName = OriginalFileName;
  2857. Data->Command = L""; // will be changed later for external editor
  2858. }
  2859. if (ExecuteFileBy == efInternalEditor)
  2860. {
  2861. if (Side == osRemote)
  2862. {
  2863. UnicodeString Caption = UnixIncludeTrailingBackslash(RemoteDirectory) + OriginalFileName +
  2864. L" - " + Terminal->SessionData->SessionName;
  2865. TForm * Editor;
  2866. try
  2867. {
  2868. TNotifyEvent OnFileChanged = NULL;
  2869. TNotifyEvent OnSaveAll = NULL;
  2870. TAnyModifiedEvent OnAnyModified = NULL;
  2871. // Edited files are uploaded in background queue, what we do not support with encrypted files
  2872. if (Terminal->IsCapable[fsBackgroundTransfers])
  2873. {
  2874. OnFileChanged = FEditorManager->FileChanged;
  2875. OnSaveAll = SaveAllInternalEditors;
  2876. OnAnyModified = AnyInternalEditorModified;
  2877. }
  2878. Editor = ShowEditorForm(FileName, this, OnFileChanged,
  2879. FEditorManager->FileReload, FEditorManager->FileClosed,
  2880. OnSaveAll, OnAnyModified,
  2881. Caption, FStandaloneEditing, SessionColor, Terminal->SessionData->InternalEditorEncoding);
  2882. }
  2883. catch(...)
  2884. {
  2885. if (!LocalRootDirectory.IsEmpty())
  2886. {
  2887. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory), false);
  2888. }
  2889. throw;
  2890. }
  2891. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  2892. }
  2893. else
  2894. {
  2895. DebugAssert(!FStandaloneEditing);
  2896. TForm * Editor =
  2897. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  2898. SaveAllInternalEditors, AnyInternalEditorModified,
  2899. L"", false, SessionColor, -1);
  2900. FLocalEditors->Add(Editor);
  2901. }
  2902. }
  2903. else
  2904. {
  2905. HANDLE Process;
  2906. if (ExecuteFileBy == efExternalEditor)
  2907. {
  2908. UnicodeString Program, Params, Dir;
  2909. Data->Command = ExternalEditor->ExternalEditor;
  2910. ReformatFileNameCommand(Data->Command);
  2911. SplitCommand(Data->Command, Program, Params, Dir);
  2912. Params = ExpandFileNameCommand(Params, FileName);
  2913. Program = ExpandEnvironmentVariables(Program);
  2914. if (!ExecuteShell(Program, Params, Process))
  2915. {
  2916. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  2917. }
  2918. }
  2919. else
  2920. {
  2921. DebugAssert(Side == osRemote);
  2922. if (!ExecuteShell(FileName, L"", Process))
  2923. {
  2924. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  2925. }
  2926. }
  2927. if ((Side == osLocal) ||
  2928. ((ExecuteFileBy == efShell) &&
  2929. !WinConfiguration->Editor.SDIShellEditor) ||
  2930. ((ExecuteFileBy == efExternalEditor) &&
  2931. !ExternalEditor->SDIExternalEditor))
  2932. {
  2933. // no need for handle
  2934. if (Process != NULL)
  2935. {
  2936. DebugCheck(CloseHandle(Process));
  2937. }
  2938. Process = INVALID_HANDLE_VALUE;
  2939. }
  2940. else
  2941. {
  2942. if (Process == NULL)
  2943. {
  2944. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  2945. }
  2946. }
  2947. if (Side == osRemote)
  2948. {
  2949. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  2950. }
  2951. }
  2952. }
  2953. //---------------------------------------------------------------------------
  2954. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  2955. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  2956. void * /*Arg*/)
  2957. {
  2958. if (Token != NULL)
  2959. {
  2960. EditorFormFileSave(static_cast<TForm *>(Token));
  2961. }
  2962. }
  2963. //---------------------------------------------------------------------------
  2964. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  2965. {
  2966. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  2967. {
  2968. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  2969. }
  2970. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  2971. }
  2972. //---------------------------------------------------------------------------
  2973. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  2974. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  2975. void * Arg)
  2976. {
  2977. if ((Token != NULL) &&
  2978. IsEditorFormModified(static_cast<TForm *>(Token)))
  2979. {
  2980. *static_cast<bool *>(Arg) = true;
  2981. }
  2982. }
  2983. //---------------------------------------------------------------------------
  2984. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  2985. TObject * /*Sender*/, bool & Modified)
  2986. {
  2987. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  2988. {
  2989. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  2990. {
  2991. Modified = true;
  2992. }
  2993. }
  2994. if (!Modified)
  2995. {
  2996. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  2997. }
  2998. }
  2999. //---------------------------------------------------------------------------
  3000. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3001. {
  3002. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3003. }
  3004. //---------------------------------------------------------------------------
  3005. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3006. UnicodeString RemoteDirectory, TCopyParamType CopyParam,
  3007. UnicodeString & Result, UnicodeString & RootDirectory)
  3008. {
  3009. if (!WinConfiguration->TemporaryDirectoryDeterministic)
  3010. {
  3011. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3012. Result = RootDirectory;
  3013. }
  3014. else
  3015. {
  3016. RootDirectory = L"";
  3017. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3018. Result = IncludeTrailingBackslash(Result);
  3019. }
  3020. if (WinConfiguration->TemporaryDirectoryAppendSession)
  3021. {
  3022. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3023. }
  3024. if (WinConfiguration->TemporaryDirectoryAppendPath)
  3025. {
  3026. if (!RemoteDirectory.IsEmpty() && (RemoteDirectory[1] == L'/'))
  3027. {
  3028. RemoteDirectory.Delete(1, 1);
  3029. }
  3030. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(RemoteDirectory)));
  3031. }
  3032. if (!ForceDirectories(ApiPath(Result)))
  3033. {
  3034. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3035. }
  3036. }
  3037. //---------------------------------------------------------------------------
  3038. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3039. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3040. bool AllFiles, bool GetTargetNames, bool AutoOperation)
  3041. {
  3042. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3043. if (ForceText)
  3044. {
  3045. CopyParam.TransferMode = tmAscii;
  3046. }
  3047. TemporaryFileCopyParam(CopyParam);
  3048. if (AllFiles)
  3049. {
  3050. CopyParam.IncludeFileMask = TFileMasks();
  3051. }
  3052. if (TempDir.IsEmpty())
  3053. {
  3054. TemporaryDirectoryForRemoteFiles(FTerminal->CurrentDirectory, CopyParam, TempDir, RootTempDir);
  3055. }
  3056. DebugAssert(!FAutoOperation);
  3057. FAutoOperation = AutoOperation;
  3058. Terminal->ExceptionOnFail = true;
  3059. try
  3060. {
  3061. try
  3062. {
  3063. // turn off confirmations, as for MDI editors we may possibly download
  3064. // the same file over
  3065. Terminal->CopyToLocal(
  3066. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3067. if (GetTargetNames)
  3068. {
  3069. for (int i = 0; i < FileList->Count; i++)
  3070. {
  3071. FileList->Strings[i] =
  3072. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3073. }
  3074. }
  3075. }
  3076. catch(...)
  3077. {
  3078. if (!RootTempDir.IsEmpty())
  3079. {
  3080. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3081. }
  3082. throw;
  3083. }
  3084. }
  3085. __finally
  3086. {
  3087. FAutoOperation = false;
  3088. Terminal->ExceptionOnFail = false;
  3089. }
  3090. }
  3091. //---------------------------------------------------------------------------
  3092. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3093. {
  3094. // Do not waste time checking for default editor list the next time,
  3095. // or testing if default editor is not notepad.
  3096. bool TryNextTime = false;
  3097. UnicodeString UsageState;
  3098. if (!WinConfiguration->EditorList->IsDefaultList())
  3099. {
  3100. UsageState = "H";
  3101. }
  3102. else
  3103. {
  3104. UnicodeString Executable;
  3105. UnicodeString ExecutableDescription;
  3106. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3107. {
  3108. UnicodeString Message =
  3109. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3110. unsigned int Answer =
  3111. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3112. if (Answer != qaOK)
  3113. {
  3114. UsageState = "R";
  3115. }
  3116. else
  3117. {
  3118. UsageState = "A";
  3119. TEditorData EditorData;
  3120. EditorData.Editor = edExternal;
  3121. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3122. EditorData.DecideExternalEditorText();
  3123. TEditorList EditorList;
  3124. EditorList = *WinConfiguration->EditorList;
  3125. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3126. WinConfiguration->EditorList = &EditorList;
  3127. }
  3128. }
  3129. }
  3130. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3131. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3132. }
  3133. //---------------------------------------------------------------------------
  3134. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3135. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3136. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3137. {
  3138. if (ExecuteFileBy == efDefaultEditor)
  3139. {
  3140. if (!WinConfiguration->OfferedEditorAutoConfig)
  3141. {
  3142. EditorAutoConfig();
  3143. }
  3144. const TEditorPreferences * Editor =
  3145. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3146. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3147. {
  3148. ExecuteFileBy = efInternalEditor;
  3149. ExternalEditor = NULL;
  3150. }
  3151. else if (Editor->Data->Editor == edOpen)
  3152. {
  3153. ExecuteFileBy = efShell;
  3154. ExternalEditor = NULL;
  3155. }
  3156. else
  3157. {
  3158. ExecuteFileBy = efExternalEditor;
  3159. ExternalEditor = Editor->Data;
  3160. }
  3161. }
  3162. }
  3163. //---------------------------------------------------------------------------
  3164. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3165. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3166. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3167. {
  3168. UnicodeString OriginalFileName;
  3169. UnicodeString LocalRootDirectory;
  3170. UnicodeString RemoteDirectory;
  3171. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3172. (Side == osLocal), MaskParams);
  3173. UnicodeString Counter;
  3174. UnicodeString LocalFileName;
  3175. bool Handled = false;
  3176. if (Side == osRemote)
  3177. {
  3178. // We need to trim VMS version here, so that we use name without version
  3179. // when uploading back to create a new version of the file
  3180. OriginalFileName = FTerminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3181. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3182. TObject * Token = NULL;
  3183. UnicodeString LocalDirectory;
  3184. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3185. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3186. LocalDirectory))
  3187. {
  3188. if (Token != NULL)
  3189. {
  3190. TForm * Form = dynamic_cast<TForm *>(Token);
  3191. if (Form->WindowState == wsMinimized)
  3192. {
  3193. ShowWindow(Form->Handle, SW_RESTORE);
  3194. }
  3195. else
  3196. {
  3197. Form->SetFocus();
  3198. }
  3199. Handled = true;
  3200. }
  3201. else
  3202. {
  3203. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3204. }
  3205. }
  3206. if (!Handled)
  3207. {
  3208. TStringList * FileList1 = new TStringList();
  3209. try
  3210. {
  3211. FileList1->AddObject(FullFileName, Object);
  3212. TemporarilyDownloadFiles(FileList1,
  3213. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3214. LocalRootDirectory, LocalDirectory, true, true, true);
  3215. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3216. }
  3217. __finally
  3218. {
  3219. delete FileList1;
  3220. }
  3221. switch (ExecuteFileBy)
  3222. {
  3223. case efShell:
  3224. Counter = "RemoteFilesExecuted";
  3225. break;
  3226. case efInternalEditor:
  3227. Counter = "RemoteFilesOpenedInInternalEditor";
  3228. break;
  3229. case efExternalEditor:
  3230. Counter = "RemoteFilesOpenedInExternalEditor";
  3231. break;
  3232. default:
  3233. DebugFail();
  3234. }
  3235. }
  3236. }
  3237. else
  3238. {
  3239. LocalFileName = FullFileName;
  3240. OriginalFileName = ExtractFileName(FullFileName);
  3241. switch (ExecuteFileBy)
  3242. {
  3243. case efShell:
  3244. Counter = "LocalFilesExecuted";
  3245. break;
  3246. case efInternalEditor:
  3247. Counter = "LocalFilesOpenedInInternalEditor";
  3248. break;
  3249. case efExternalEditor:
  3250. Counter = "LocalFilesOpenedInExternalEditor";
  3251. break;
  3252. default:
  3253. DebugFail();
  3254. }
  3255. }
  3256. if (!Handled)
  3257. {
  3258. Configuration->Usage->Inc(Counter);
  3259. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3260. ExternalEditor, LocalRootDirectory, RemoteDirectory);
  3261. }
  3262. }
  3263. //---------------------------------------------------------------------------
  3264. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3265. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3266. bool AllSelected, bool OnFocused)
  3267. {
  3268. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3269. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3270. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3271. Side = GetSide(Side);
  3272. TCustomDirView * DView = DirView(Side);
  3273. TStrings * FileList = AllSelected ?
  3274. DView->CreateFileList(OnFocused, Side == osLocal) :
  3275. DView->CreateFocusedFileList(Side == osLocal);
  3276. try
  3277. {
  3278. DebugAssert(AllSelected || (FileList->Count == 1));
  3279. for (int i = 0; i < FileList->Count; i++)
  3280. {
  3281. UnicodeString ListFileName = FileList->Strings[i];
  3282. UnicodeString FileNameOnly = (Side == osRemote) ?
  3283. UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3284. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3285. if (!DView->ItemIsDirectory(Item))
  3286. {
  3287. UnicodeString FullFileName;
  3288. if (Side == osRemote)
  3289. {
  3290. FullFileName = RemoteDirView->Path + ListFileName;
  3291. }
  3292. else
  3293. {
  3294. FullFileName = ListFileName;
  3295. }
  3296. TFileMasks::TParams MaskParams;
  3297. MaskParams.Size = DView->ItemFileSize(Item);
  3298. TDateTimePrecision Precision;
  3299. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3300. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName,
  3301. FileList->Objects[i], MaskParams);
  3302. }
  3303. }
  3304. }
  3305. __finally
  3306. {
  3307. delete FileList;
  3308. }
  3309. }
  3310. //---------------------------------------------------------------------------
  3311. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3312. {
  3313. // do not forget to add additional options to TemporarilyDownloadFiles, and AS
  3314. CopyParam.FileNameCase = ncNoChange;
  3315. CopyParam.PreserveRights = false;
  3316. CopyParam.PreserveReadOnly = false;
  3317. CopyParam.ReplaceInvalidChars = true;
  3318. CopyParam.IncludeFileMask = TFileMasks();
  3319. CopyParam.NewerOnly = false;
  3320. CopyParam.FileMask = L"";
  3321. }
  3322. //---------------------------------------------------------------------------
  3323. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(const UnicodeString FileName,
  3324. TEditedFileData * Data, HANDLE UploadCompleteEvent)
  3325. {
  3326. TTerminalManager * Manager = TTerminalManager::Instance();
  3327. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3328. {
  3329. if (!NonVisualDataModule->Busy)
  3330. {
  3331. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3332. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3333. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3334. if (Data->Terminal == NULL)
  3335. {
  3336. TTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3337. if (SameSiteTerminal != NULL)
  3338. {
  3339. UnicodeString Message =
  3340. FMTLOAD(EDIT_SESSION_REATTACH,
  3341. (FileNameOnly, Data->SessionName, FileNameOnly));
  3342. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3343. {
  3344. Data->Terminal = Terminal;
  3345. Data->Queue = Manager->FindQueueForTerminal(Terminal);
  3346. Data->SessionName = Terminal->SessionData->SessionName;
  3347. // We might also overwrite session data
  3348. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3349. }
  3350. else
  3351. {
  3352. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3353. Abort();
  3354. }
  3355. }
  3356. }
  3357. // foreground session should reconnect itself
  3358. else if (Terminal != Data->Terminal)
  3359. {
  3360. UnicodeString Message =
  3361. MainInstructions(
  3362. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3363. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3364. {
  3365. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3366. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3367. }
  3368. else
  3369. {
  3370. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3371. Abort();
  3372. }
  3373. }
  3374. }
  3375. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3376. {
  3377. Configuration->Usage->Inc(L"EditInactiveSession");
  3378. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3379. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3380. (ExtractFileName(FileName), Data->SessionName)));
  3381. }
  3382. }
  3383. TStrings * FileList = new TStringList();
  3384. try
  3385. {
  3386. FileList->Add(FileName);
  3387. // consider using the same settings (preset) as when the file was downloaded
  3388. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3389. TemporaryFileCopyParam(CopyParam);
  3390. if (Data->ForceText)
  3391. {
  3392. CopyParam.TransferMode = tmAscii;
  3393. }
  3394. // so i do not need to worry if masking algorithm works in all cases
  3395. // ("" means "copy file name", no masking is actually done)
  3396. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3397. {
  3398. CopyParam.FileMask = L"";
  3399. }
  3400. else
  3401. {
  3402. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3403. }
  3404. DebugAssert(Data->Queue != NULL);
  3405. int Params = cpNoConfirmation | cpTemporary;
  3406. TQueueItem * QueueItem = new TUploadQueueItem(Data->Terminal, FileList,
  3407. Data->RemoteDirectory, &CopyParam, Params, true, false);
  3408. QueueItem->CompleteEvent = UploadCompleteEvent;
  3409. AddQueueItem(Data->Queue, QueueItem, Data->Terminal);
  3410. }
  3411. __finally
  3412. {
  3413. delete FileList;
  3414. }
  3415. }
  3416. //---------------------------------------------------------------------------
  3417. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3418. const UnicodeString FileName, const TEditedFileData * Data)
  3419. {
  3420. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3421. DebugAssert(!NonVisualDataModule->Busy);
  3422. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3423. {
  3424. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3425. (ExtractFileName(FileName), Data->SessionName)));
  3426. }
  3427. TTerminal * PrevTerminal = TTerminalManager::Instance()->ActiveTerminal;
  3428. TTerminalManager::Instance()->ActiveTerminal = Data->Terminal;
  3429. NonVisualDataModule->StartBusy();
  3430. try
  3431. {
  3432. std::unique_ptr<TRemoteFile> File;
  3433. UnicodeString RemoteFileName =
  3434. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3435. FTerminal->ExceptionOnFail = true;
  3436. try
  3437. {
  3438. TRemoteFile * AFile = NULL;
  3439. FTerminal->ReadFile(RemoteFileName, AFile);
  3440. File.reset(AFile);
  3441. if (!File->HaveFullFileName)
  3442. {
  3443. File->FullFileName = RemoteFileName;
  3444. }
  3445. }
  3446. __finally
  3447. {
  3448. FTerminal->ExceptionOnFail = false;
  3449. }
  3450. std::unique_ptr<TStrings> FileList(new TStringList());
  3451. FileList->AddObject(RemoteFileName, File.get());
  3452. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3453. UnicodeString TempDir = ExtractFilePath(FileName);
  3454. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir,
  3455. TempDir, true, true, true);
  3456. // sanity check, the target file name should be still the same
  3457. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3458. }
  3459. __finally
  3460. {
  3461. NonVisualDataModule->EndBusy();
  3462. // it actually may not exist anymore...
  3463. TTerminalManager::Instance()->ActiveTerminal = PrevTerminal;
  3464. }
  3465. }
  3466. //---------------------------------------------------------------------------
  3467. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3468. const TEditedFileData * Data, bool & KeepOpen)
  3469. {
  3470. // Command is set for external editors only (not for "shell" open).
  3471. if (!Data->Command.IsEmpty())
  3472. {
  3473. bool AnyFound = false;
  3474. bool AnyMDI = false;
  3475. bool AnyNonMDI = false;
  3476. bool AnyDetect = false;
  3477. TEditorList * EditorList = new TEditorList();
  3478. try
  3479. {
  3480. *EditorList = *WinConfiguration->EditorList;
  3481. for (int i = 0; i < EditorList->Count; i++)
  3482. {
  3483. const TEditorPreferences * Editor = EditorList->Editors[i];
  3484. if ((Editor->Data->Editor == edExternal) &&
  3485. (Editor->Data->ExternalEditor == Data->Command))
  3486. {
  3487. AnyFound = true;
  3488. if (Editor->Data->SDIExternalEditor)
  3489. {
  3490. AnyNonMDI = true;
  3491. if (Editor->Data->DetectMDIExternalEditor)
  3492. {
  3493. AnyDetect = true;
  3494. }
  3495. }
  3496. else
  3497. {
  3498. AnyMDI = true;
  3499. }
  3500. }
  3501. }
  3502. bool EnableMDI = false;
  3503. bool DisableDetect = false;
  3504. if (AnyMDI)
  3505. {
  3506. KeepOpen = true;
  3507. if (AnyNonMDI)
  3508. {
  3509. // there is at least one instance of the editor with MDI support enabled,
  3510. // and one with disabled, enable it for all instances
  3511. EnableMDI = true;
  3512. }
  3513. }
  3514. else if (AnyFound && !AnyDetect)
  3515. {
  3516. // at least once instance found but all have MDI autodetection disabled
  3517. // => close the file (default action)
  3518. }
  3519. else
  3520. {
  3521. // no instance of the editor has MDI support enabled
  3522. TMessageParams Params;
  3523. if (AnyFound)
  3524. {
  3525. // there is at least one instance of the editor
  3526. Params.Params |= mpNeverAskAgainCheck;
  3527. }
  3528. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3529. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3530. switch (Answer)
  3531. {
  3532. case qaNeverAskAgain:
  3533. DisableDetect = true;
  3534. break;
  3535. case qaNo:
  3536. EnableMDI = true;
  3537. KeepOpen = true;
  3538. break;
  3539. }
  3540. }
  3541. if (AnyFound && (EnableMDI || DisableDetect))
  3542. {
  3543. bool Changed = false;
  3544. for (int i = 0; i < EditorList->Count; i++)
  3545. {
  3546. const TEditorPreferences * Editor = EditorList->Editors[i];
  3547. if ((Editor->Data->Editor == edExternal) &&
  3548. (Editor->Data->ExternalEditor == Data->Command) &&
  3549. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3550. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3551. {
  3552. Changed = true;
  3553. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3554. if (EnableMDI)
  3555. {
  3556. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3557. }
  3558. if (DisableDetect)
  3559. {
  3560. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3561. }
  3562. EditorList->Change(i, UpdatedEditor);
  3563. }
  3564. }
  3565. if (Changed)
  3566. {
  3567. WinConfiguration->EditorList = EditorList;
  3568. }
  3569. }
  3570. }
  3571. __finally
  3572. {
  3573. delete EditorList;
  3574. }
  3575. }
  3576. else
  3577. {
  3578. // "open" case
  3579. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  3580. qaOK, HELP_APP_EARLY_CLOSED);
  3581. }
  3582. }
  3583. //---------------------------------------------------------------------------
  3584. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  3585. {
  3586. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  3587. }
  3588. //---------------------------------------------------------------------------
  3589. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  3590. {
  3591. SideEnter(osRemote);
  3592. }
  3593. //---------------------------------------------------------------------------
  3594. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  3595. {
  3596. MakeNextInTabOrder(RemoteDirView, RemoteDriveView);
  3597. SideEnter(osRemote);
  3598. }
  3599. //---------------------------------------------------------------------------
  3600. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  3601. {
  3602. FCurrentSide = Side;
  3603. if (Visible)
  3604. {
  3605. UpdateControls();
  3606. }
  3607. }
  3608. //---------------------------------------------------------------------------
  3609. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  3610. TStrings * FileList, bool Alternative)
  3611. {
  3612. TCustomDirView * DView = DirView(Side);
  3613. DView->SaveSelection();
  3614. DView->SaveSelectedNames();
  3615. DebugAssert(!FAlternativeDelete);
  3616. FAlternativeDelete = Alternative;
  3617. try
  3618. {
  3619. if (Side == osRemote)
  3620. {
  3621. DebugAssert(Terminal != NULL);
  3622. Terminal->DeleteFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  3623. }
  3624. else
  3625. {
  3626. try
  3627. {
  3628. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  3629. }
  3630. __finally
  3631. {
  3632. ReloadLocalDirectory();
  3633. }
  3634. }
  3635. FAlternativeDelete = false;
  3636. }
  3637. catch(...)
  3638. {
  3639. FAlternativeDelete = false;
  3640. DView->DiscardSavedSelection();
  3641. throw;
  3642. }
  3643. DView->RestoreSelection();
  3644. }
  3645. //---------------------------------------------------------------------------
  3646. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  3647. {
  3648. DebugAssert(Terminal);
  3649. RemoteDirView->SaveSelection();
  3650. RemoteDirView->SaveSelectedNames();
  3651. try
  3652. {
  3653. if (Lock)
  3654. {
  3655. Terminal->LockFiles(FileList);
  3656. }
  3657. else
  3658. {
  3659. Terminal->UnlockFiles(FileList);
  3660. }
  3661. }
  3662. catch(...)
  3663. {
  3664. RemoteDirView->DiscardSavedSelection();
  3665. throw;
  3666. }
  3667. RemoteDirView->RestoreSelection();
  3668. }
  3669. //---------------------------------------------------------------------------
  3670. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TTerminal *& Session,
  3671. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  3672. bool NoConfirmation, bool Move)
  3673. {
  3674. DebugAssert(Terminal != NULL);
  3675. // update Terminal->StateData->RemoteDirectory
  3676. UpdateTerminal(Terminal);
  3677. if (Session == NULL)
  3678. {
  3679. Session = TTerminalManager::Instance()->ActiveTerminal;
  3680. }
  3681. if (Session == TTerminalManager::Instance()->ActiveTerminal)
  3682. {
  3683. if (RemoteDriveView->DropTarget != NULL)
  3684. {
  3685. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  3686. }
  3687. else if (RemoteDirView->DropTarget != NULL)
  3688. {
  3689. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  3690. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  3691. }
  3692. else
  3693. {
  3694. Target = RemoteDirView->Path;
  3695. }
  3696. }
  3697. else
  3698. {
  3699. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(Session));
  3700. Target = ManagedTerminal->StateData->RemoteDirectory;
  3701. }
  3702. Target = UnixIncludeTrailingBackslash(Target);
  3703. if (FileList->Count == 1)
  3704. {
  3705. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  3706. }
  3707. else
  3708. {
  3709. FileMask = AnyMask;
  3710. }
  3711. DirectCopy = FTerminal->IsCapable[fcRemoteCopy] || FTerminal->IsCapable[fcSecondaryShell];
  3712. bool Result = true;
  3713. if (!NoConfirmation)
  3714. {
  3715. bool Multi = (FileList->Count > 1);
  3716. if (Move)
  3717. {
  3718. Result = DoRemoteMoveDialog(Multi, Target, FileMask);
  3719. }
  3720. else
  3721. {
  3722. TStrings * Sessions = TTerminalManager::Instance()->TerminalList;
  3723. TStrings * Directories = new TStringList;
  3724. try
  3725. {
  3726. for (int Index = 0; Index < Sessions->Count; Index++)
  3727. {
  3728. TManagedTerminal * Terminal =
  3729. dynamic_cast<TManagedTerminal *>(Sessions->Objects[Index]);
  3730. Directories->Add(Terminal->StateData->RemoteDirectory);
  3731. }
  3732. TDirectRemoteCopy AllowDirectCopy;
  3733. if (FTerminal->IsCapable[fcRemoteCopy] || FTerminal->CommandSessionOpened)
  3734. {
  3735. DebugAssert(DirectCopy);
  3736. AllowDirectCopy = drcAllow;
  3737. }
  3738. else if (FTerminal->IsCapable[fcSecondaryShell])
  3739. {
  3740. DebugAssert(DirectCopy);
  3741. AllowDirectCopy = drcConfirmCommandSession;
  3742. }
  3743. else
  3744. {
  3745. DebugAssert(!DirectCopy);
  3746. AllowDirectCopy = drcDisallow;
  3747. }
  3748. void * ASession = Session;
  3749. Result = DoRemoteCopyDialog(Sessions, Directories, AllowDirectCopy,
  3750. Multi, ASession, Target, FileMask, DirectCopy, TTerminalManager::Instance()->ActiveTerminal);
  3751. Session = static_cast<TTerminal *>(ASession);
  3752. }
  3753. __finally
  3754. {
  3755. delete Directories;
  3756. }
  3757. }
  3758. }
  3759. return Result;
  3760. }
  3761. //---------------------------------------------------------------------------
  3762. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  3763. TStrings * FileList, bool NoConfirmation, bool Move, TTerminal * Session)
  3764. {
  3765. bool DirectCopy;
  3766. UnicodeString Target, FileMask;
  3767. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  3768. if (Result)
  3769. {
  3770. if (!Move && !DirectCopy)
  3771. {
  3772. Configuration->Usage->Inc("RemoteCopyTemp");
  3773. UnicodeString RootTempDir;
  3774. UnicodeString TempDir;
  3775. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, false);
  3776. TStrings * TemporaryFilesList = new TStringList();
  3777. try
  3778. {
  3779. TMakeLocalFileListParams MakeFileListParam;
  3780. MakeFileListParam.FileList = TemporaryFilesList;
  3781. MakeFileListParam.FileTimes = NULL;
  3782. MakeFileListParam.IncludeDirs = true;
  3783. MakeFileListParam.Recursive = false;
  3784. ProcessLocalDirectory(TempDir, FTerminal->MakeLocalFileList, &MakeFileListParam);
  3785. TTerminalManager::Instance()->ActiveTerminal = Session;
  3786. if (TemporaryFilesList->Count > 0)
  3787. {
  3788. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3789. CopyParam.FileMask = FileMask;
  3790. DebugAssert(!FAutoOperation);
  3791. FAutoOperation = true;
  3792. FTerminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  3793. }
  3794. }
  3795. __finally
  3796. {
  3797. delete TemporaryFilesList;
  3798. FAutoOperation = false;
  3799. if (!RootTempDir.IsEmpty())
  3800. {
  3801. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3802. }
  3803. }
  3804. }
  3805. else
  3806. {
  3807. RemoteDirView->SaveSelection();
  3808. RemoteDirView->SaveSelectedNames();
  3809. try
  3810. {
  3811. if (Move)
  3812. {
  3813. Configuration->Usage->Inc("RemoteMove");
  3814. Terminal->MoveFiles(FileList, Target, FileMask);
  3815. }
  3816. else
  3817. {
  3818. Configuration->Usage->Inc("RemoteCopyDirect");
  3819. DebugAssert(DirectCopy);
  3820. DebugAssert(Session == FTerminal);
  3821. if (FTerminal->IsCapable[fcRemoteCopy] ||
  3822. FTerminal->CommandSessionOpened ||
  3823. CommandSessionFallback())
  3824. {
  3825. Terminal->CopyFiles(FileList, Target, FileMask);
  3826. }
  3827. }
  3828. }
  3829. catch(...)
  3830. {
  3831. RemoteDirView->DiscardSavedSelection();
  3832. throw;
  3833. }
  3834. RemoteDirView->RestoreSelection();
  3835. }
  3836. }
  3837. return Result;
  3838. }
  3839. //---------------------------------------------------------------------------
  3840. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  3841. const UnicodeString & Path, TRemoteProperties & Properties)
  3842. {
  3843. Properties.Valid = Properties.Valid << vpEncrypt;
  3844. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  3845. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  3846. }
  3847. //---------------------------------------------------------------------------
  3848. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  3849. {
  3850. Side = GetSide(Side);
  3851. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  3852. TRemoteProperties * AProperties = (Side == osRemote ? &Properties : NULL);
  3853. UnicodeString Name = LoadStr(NEW_FOLDER);
  3854. int AllowedChanges =
  3855. FLAGMASK((Side == osRemote) && Terminal->IsCapable[fcModeChanging], cpMode);
  3856. bool SaveSettings = false;
  3857. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  3858. {
  3859. TWindowLock Lock(this);
  3860. if (Side == osRemote)
  3861. {
  3862. if (SaveSettings)
  3863. {
  3864. GUIConfiguration->NewDirectoryProperties = Properties;
  3865. }
  3866. CreateRemoteDirectory(Name, Properties);
  3867. }
  3868. else
  3869. {
  3870. DirView(Side)->CreateDirectory(Name);
  3871. }
  3872. }
  3873. }
  3874. //---------------------------------------------------------------------------
  3875. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  3876. {
  3877. TWindowLock Lock(this);
  3878. DirView(Side)->ExecuteHomeDirectory();
  3879. }
  3880. //---------------------------------------------------------------------------
  3881. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  3882. {
  3883. DoOpenDirectoryDialog(odBrowse, Side);
  3884. }
  3885. //---------------------------------------------------------------------------
  3886. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  3887. {
  3888. UnicodeString Path = Bookmark->GetSideDirectory(Side);
  3889. bool Result = !Path.IsEmpty();
  3890. if (Result)
  3891. {
  3892. // While we might get here when the session is closed (from location profiles),
  3893. // it's not a problem as the Path setter is noop then
  3894. DirView(Side)->Path = Path;
  3895. }
  3896. return Result;
  3897. }
  3898. //---------------------------------------------------------------------------
  3899. void __fastcall TCustomScpExplorerForm::CalculateSize(
  3900. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  3901. bool & Close)
  3902. {
  3903. // terminal can be already closed (e.g. dropped connection)
  3904. if (Terminal != NULL)
  3905. {
  3906. try
  3907. {
  3908. Terminal->CalculateFilesSize(FileList, Size, 0, NULL, true, Stats);
  3909. }
  3910. catch(...)
  3911. {
  3912. if (!Terminal->Active)
  3913. {
  3914. Close = true;
  3915. }
  3916. throw;
  3917. }
  3918. }
  3919. }
  3920. //---------------------------------------------------------------------------
  3921. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  3922. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  3923. bool & Close)
  3924. {
  3925. // terminal can be already closed (e.g. dropped connection)
  3926. if (Terminal != NULL)
  3927. {
  3928. Configuration->Usage->Inc(L"ChecksumCalculated");
  3929. try
  3930. {
  3931. Terminal->CalculateFilesChecksum(Alg, FileList, NULL, OnCalculatedChecksum);
  3932. }
  3933. catch(...)
  3934. {
  3935. if (!Terminal->Active)
  3936. {
  3937. Close = true;
  3938. }
  3939. throw;
  3940. }
  3941. }
  3942. }
  3943. //---------------------------------------------------------------------------
  3944. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  3945. {
  3946. bool Result;
  3947. if (Side == osRemote)
  3948. {
  3949. TRemoteTokenList * GroupList = NULL;
  3950. TRemoteTokenList * UserList = NULL;
  3951. try
  3952. {
  3953. TRemoteProperties CurrentProperties;
  3954. if (Terminal->LoadFilesProperties(FileList))
  3955. {
  3956. RemoteDirView->Invalidate();
  3957. }
  3958. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  3959. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  3960. if (CapableGroupChanging || CapableOwnerChanging)
  3961. {
  3962. if (CapableGroupChanging)
  3963. {
  3964. GroupList = Terminal->Groups->Duplicate();
  3965. }
  3966. if (CapableOwnerChanging)
  3967. {
  3968. UserList = Terminal->Users->Duplicate();
  3969. }
  3970. TRemoteDirectory * Files = Terminal->Files;
  3971. int Count = Files->Count;
  3972. if (Count > 100)
  3973. {
  3974. Count = 100;
  3975. }
  3976. for (int Index = 0; Index < Count; Index++)
  3977. {
  3978. TRemoteFile * File = Files->Files[Index];
  3979. if (CapableGroupChanging)
  3980. {
  3981. GroupList->AddUnique(File->Group);
  3982. }
  3983. if (CapableOwnerChanging)
  3984. {
  3985. UserList->AddUnique(File->Owner);
  3986. }
  3987. }
  3988. // if we haven't collected tokens for all files in current directory,
  3989. // make sure we collect them at least for all selected files.
  3990. // (note that so far the files in FileList has to be from current direcotry)
  3991. if (Count < Files->Count)
  3992. {
  3993. for (int Index = 0; Index < FileList->Count; Index++)
  3994. {
  3995. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  3996. if (CapableGroupChanging)
  3997. {
  3998. GroupList->AddUnique(File->Group);
  3999. }
  4000. if (CapableOwnerChanging)
  4001. {
  4002. UserList->AddUnique(File->Owner);
  4003. }
  4004. }
  4005. }
  4006. }
  4007. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4008. int Flags = 0;
  4009. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4010. if (CapableOwnerChanging) Flags |= cpOwner;
  4011. if (CapableGroupChanging) Flags |= cpGroup;
  4012. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4013. if (Terminal->IsCapable[fcCalculatingChecksum])
  4014. {
  4015. CalculateChecksumEvent = CalculateChecksum;
  4016. }
  4017. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4018. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4019. TRemoteProperties NewProperties = CurrentProperties;
  4020. Result =
  4021. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4022. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4023. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4024. CalculateSize, CalculateChecksumEvent);
  4025. if (Result)
  4026. {
  4027. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4028. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4029. }
  4030. }
  4031. __finally
  4032. {
  4033. delete GroupList;
  4034. delete UserList;
  4035. }
  4036. }
  4037. else
  4038. {
  4039. DirView(Side)->DisplayPropertiesMenu();
  4040. Result = true;
  4041. }
  4042. return Result;
  4043. }
  4044. //---------------------------------------------------------------------------
  4045. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4046. {
  4047. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4048. {
  4049. FIgnoreNextDialogChar = Key;
  4050. }
  4051. Key = 0;
  4052. }
  4053. //---------------------------------------------------------------------------
  4054. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4055. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4056. {
  4057. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4058. if (Command != NULL)
  4059. {
  4060. KeyProcessed(Key, Shift);
  4061. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4062. {
  4063. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4064. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4065. false, false, const_cast<TCustomCommandType *>(Command));
  4066. }
  4067. }
  4068. }
  4069. //---------------------------------------------------------------------------
  4070. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4071. {
  4072. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4073. {
  4074. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4075. }
  4076. if (!DirView(osCurrent)->IsEditing())
  4077. {
  4078. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4079. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4080. {
  4081. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4082. if (((Action->ShortCut == KeyShortCut) ||
  4083. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4084. AllowedAction(Action, aaShortCut))
  4085. {
  4086. // Has to be called before the action as the dialog char is already in queue.
  4087. // So when the action consumes message queue, we already need to have the
  4088. // FIgnoreNextDialogChar set
  4089. KeyProcessed(Key, Shift);
  4090. // Reset reference to previous component (when menu/toolbar was clicked).
  4091. // Needed to detect that action was invoked by keyboard shortcut
  4092. // in TNonVisualDataModule::ExplorerActionsExecute
  4093. Action->ActionComponent = NULL;
  4094. Action->Execute();
  4095. return;
  4096. }
  4097. }
  4098. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4099. {
  4100. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4101. {
  4102. KeyProcessed(Key, Shift);
  4103. TTerminalManager::Instance()->ActiveTerminalIndex = i;
  4104. return;
  4105. }
  4106. }
  4107. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4108. {
  4109. KeyProcessed(Key, Shift);
  4110. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4111. }
  4112. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4113. if (IsCustomShortCut(CustomShortCut))
  4114. {
  4115. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4116. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4117. if (WinConfiguration->SharedBookmarks != NULL)
  4118. {
  4119. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4120. if ((Bookmark != NULL) &&
  4121. OpenBookmark(FCurrentSide, Bookmark))
  4122. {
  4123. KeyProcessed(Key, Shift);
  4124. }
  4125. }
  4126. }
  4127. }
  4128. TForm::KeyDown(Key, Shift);
  4129. }
  4130. //---------------------------------------------------------------------------
  4131. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4132. {
  4133. DebugAssert(Terminal != NULL);
  4134. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  4135. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  4136. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4137. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4138. bool SecurityEnabled = !SessionInfo.SecurityProtocolName.IsEmpty();
  4139. SessionStatusBar->Panels->Items[Offset + 0]->Enabled = SecurityEnabled;
  4140. // expanded from ?: to avoid memory leaks
  4141. if (SecurityEnabled)
  4142. {
  4143. SessionStatusBar->Panels->Items[Offset + 0]->Hint =
  4144. FMTLOAD(STATUS_SECURE, (SessionInfo.SecurityProtocolName));
  4145. }
  4146. else
  4147. {
  4148. SessionStatusBar->Panels->Items[Offset + 0]->Hint = LoadStr(STATUS_INSECURE);
  4149. }
  4150. if (FileSystemInfo.ProtocolName.IsEmpty())
  4151. {
  4152. SessionStatusBar->Panels->Items[Offset + 1]->Caption = SessionInfo.ProtocolName;
  4153. }
  4154. else
  4155. {
  4156. SessionStatusBar->Panels->Items[Offset + 1]->Caption = FileSystemInfo.ProtocolName;
  4157. }
  4158. SessionStatusBar->Panels->Items[Offset + 1]->Hint = LoadStr(STATUS_PROTOCOL_HINT);
  4159. SessionStatusBar->Panels->Items[Offset + 2]->Enabled =
  4160. (!SessionInfo.CSCompression.IsEmpty() || !SessionInfo.SCCompression.IsEmpty());
  4161. UnicodeString CSCompressionStr = DefaultStr(SessionInfo.CSCompression, LoadStr(NO_STR));
  4162. UnicodeString SCCompressionStr = DefaultStr(SessionInfo.SCCompression, LoadStr(NO_STR));
  4163. UnicodeString CompressionStr = CSCompressionStr;
  4164. if (CSCompressionStr != SCCompressionStr)
  4165. {
  4166. CompressionStr += UnicodeString(L"/") + SCCompressionStr;
  4167. }
  4168. SessionStatusBar->Panels->Items[Offset + 2]->Hint = FMTLOAD(STATUS_COMPRESSION_HINT, (CompressionStr));
  4169. SessionStatusBar->Panels->Items[Offset + 3]->Hint = LoadStr(STATUS_DURATION_HINT);
  4170. UpdateStatusBar();
  4171. }
  4172. //---------------------------------------------------------------------------
  4173. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4174. {
  4175. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4176. DebugAssert(SessionStatusBar != NULL);
  4177. if (!Terminal || !Terminal->Active || Terminal->Status < ssOpened)
  4178. {
  4179. // note: (Terminal->Status < sshReady) currently never happens here,
  4180. // so STATUS_CONNECTING is never used
  4181. SessionStatusBar->SimplePanel = true;
  4182. SessionStatusBar->SimpleText = LoadStr(
  4183. !Terminal || !Terminal->Active ? STATUS_NOT_CONNECTED : STATUS_CONNECTING);
  4184. }
  4185. else
  4186. {
  4187. DebugAssert(Terminal);
  4188. SessionStatusBar->SimplePanel = false;
  4189. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  4190. if (!FNote.IsEmpty())
  4191. {
  4192. SessionStatusBar->Panels->Items[0]->Caption = FNote;
  4193. }
  4194. else
  4195. {
  4196. UpdateStatusPanelText(SessionStatusBar->Panels->Items[0]);
  4197. }
  4198. SessionStatusBar->Panels->Items[0]->Hint = FNoteHints;
  4199. SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1]->Caption =
  4200. FormatDateTimeSpan(Configuration->TimeFormat, Now() - SessionInfo.LoginTime);
  4201. }
  4202. }
  4203. //---------------------------------------------------------------------------
  4204. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4205. {
  4206. Panel->Caption = L"";
  4207. }
  4208. //---------------------------------------------------------------------------
  4209. void __fastcall TCustomScpExplorerForm::Idle()
  4210. {
  4211. if (FShowing || FStandaloneEditing)
  4212. {
  4213. FEditorManager->Check();
  4214. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4215. // that needs to know if queue view is visible (and it may be closed after queue update)
  4216. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4217. }
  4218. if (FShowing)
  4219. {
  4220. if (!NonVisualDataModule->Busy &&
  4221. // Menu is opened or drag&drop is going on
  4222. (Mouse->Capture == NULL))
  4223. {
  4224. if (FRefreshRemoteDirectory)
  4225. {
  4226. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4227. {
  4228. Terminal->RefreshDirectory();
  4229. }
  4230. FRefreshRemoteDirectory = false;
  4231. }
  4232. if (FRefreshLocalDirectory)
  4233. {
  4234. ReloadLocalDirectory();
  4235. FRefreshLocalDirectory = false;
  4236. }
  4237. if (WinConfiguration->RefreshRemotePanel)
  4238. {
  4239. TManagedTerminal * ManagedTerminal =
  4240. dynamic_cast<TManagedTerminal *>(Terminal);
  4241. if ((ManagedTerminal != NULL) && (Terminal->Status == ssOpened) &&
  4242. (Now() - ManagedTerminal->DirectoryLoaded >
  4243. WinConfiguration->RefreshRemotePanelInterval))
  4244. {
  4245. RemoteDirView->ReloadDirectory();
  4246. }
  4247. }
  4248. }
  4249. }
  4250. if (FShowing || FStandaloneEditing)
  4251. {
  4252. if (FQueueStatusInvalidated)
  4253. {
  4254. UpdateQueueStatus(false);
  4255. }
  4256. RefreshQueueItems();
  4257. }
  4258. if (FShowing)
  4259. {
  4260. UpdateStatusBar();
  4261. }
  4262. FIgnoreNextDialogChar = 0;
  4263. }
  4264. //---------------------------------------------------------------------------
  4265. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4266. {
  4267. try
  4268. {
  4269. FUserActionTimer->Enabled = false;
  4270. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4271. {
  4272. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4273. {
  4274. FPendingQueueActionItem->ProcessUserAction();
  4275. }
  4276. }
  4277. }
  4278. __finally
  4279. {
  4280. FPendingQueueActionItem = NULL;
  4281. }
  4282. }
  4283. //---------------------------------------------------------------------------
  4284. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4285. {
  4286. if (WinConfiguration->MinimizeToTray)
  4287. {
  4288. UpdateTrayIcon();
  4289. FTrayIcon->Visible = true;
  4290. if (Visible)
  4291. {
  4292. ShowWindow(Handle, SW_HIDE);
  4293. }
  4294. }
  4295. }
  4296. //---------------------------------------------------------------------------
  4297. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4298. {
  4299. // WORKAROUND
  4300. // When restoring maximized window from minimization,
  4301. // rarely some controls do not align properly.
  4302. // Two instances seen (both for Commander):
  4303. // - When restoring, window is temporarily narrower (not maximized),
  4304. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4305. // Once maximized already, top dock shinks back, but the session PageControl,
  4306. // do not align up, leaving space between TopDock and PageControl.
  4307. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4308. for (int Index = 0; Index < ControlCount; Index++)
  4309. {
  4310. RealignControl(Controls[Index]);
  4311. }
  4312. if (FTrayIcon->Visible)
  4313. {
  4314. FTrayIcon->Visible = false;
  4315. if (Visible)
  4316. {
  4317. ShowWindow(Handle, SW_SHOW);
  4318. }
  4319. }
  4320. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4321. {
  4322. FNeedSession = false;
  4323. NonVisualDataModule->StartBusy();
  4324. try
  4325. {
  4326. NeedSession(false);
  4327. }
  4328. __finally
  4329. {
  4330. NonVisualDataModule->EndBusy();
  4331. }
  4332. }
  4333. }
  4334. //---------------------------------------------------------------------------
  4335. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4336. {
  4337. FTrayIcon->Hint = GetMainForm()->Caption;
  4338. }
  4339. //---------------------------------------------------------------------------
  4340. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4341. {
  4342. UpdateTrayIcon();
  4343. }
  4344. //---------------------------------------------------------------------------
  4345. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4346. {
  4347. // workaround
  4348. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4349. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4350. // But WM_ACTIVATEAPP message can be received even when
  4351. // the main window is minimized to the tray and internal editor window is focused
  4352. // (after another application was previously active)
  4353. if (::IsIconic(Handle))
  4354. {
  4355. if (!IsAppIconic())
  4356. {
  4357. SetAppIconic(true);
  4358. }
  4359. }
  4360. ::ApplicationRestore();
  4361. Application->BringToFront();
  4362. }
  4363. //---------------------------------------------------------------------------
  4364. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4365. {
  4366. RestoreApp();
  4367. }
  4368. //---------------------------------------------------------------------------
  4369. void __fastcall TCustomScpExplorerForm::NewSession(bool FromSite, const UnicodeString & SessionUrl)
  4370. {
  4371. if (OpenInNewWindow())
  4372. {
  4373. // todo: Pass FromSite
  4374. ExecuteNewInstance(SessionUrl);
  4375. }
  4376. else
  4377. {
  4378. TTerminalManager::Instance()->NewSession(FromSite, SessionUrl);
  4379. }
  4380. }
  4381. //---------------------------------------------------------------------------
  4382. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4383. {
  4384. UnicodeString SessionName = StoredSessions->HiddenPrefix + Terminal->SessionData->SessionName;
  4385. // current working directories become defaults here, what is not right
  4386. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4387. StoredSessions->NewSession(SessionName, SessionData.get());
  4388. // modified only, explicit
  4389. StoredSessions->Save(false, true);
  4390. // encode session name because of slashes in hierarchical sessions
  4391. return EncodeUrlString(SessionName);
  4392. }
  4393. //---------------------------------------------------------------------------
  4394. void __fastcall TCustomScpExplorerForm::DuplicateSession()
  4395. {
  4396. if (OpenInNewWindow())
  4397. {
  4398. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4399. }
  4400. else
  4401. {
  4402. // current working directories become defaults here, what is not right
  4403. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4404. TTerminalManager * Manager = TTerminalManager::Instance();
  4405. TTerminal * Terminal = Manager->NewTerminal(SessionData.get());
  4406. Manager->ActiveTerminal = Terminal;
  4407. }
  4408. }
  4409. //---------------------------------------------------------------------------
  4410. void __fastcall TCustomScpExplorerForm::RenameSession()
  4411. {
  4412. UnicodeString Name = Terminal->SessionData->Name;
  4413. if (InputDialog(LoadStr(RENAME_SESSION_TITLE), LoadStr(RENAME_SESSION_PROMPT), Name, HELP_SESSION_RENAME))
  4414. {
  4415. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  4416. TSessionData::ValidateName(Name);
  4417. // This is inconsistent with how color (for example) is handled.
  4418. Terminal->SessionData->Name = Name;
  4419. UpdateControls();
  4420. // Add/Remove distinguishing paths from sessions of the same name.
  4421. DoTerminalListChanged();
  4422. }
  4423. }
  4424. //---------------------------------------------------------------------------
  4425. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  4426. {
  4427. DebugAssert(Queue != NULL);
  4428. bool Result = Queue->IsEmpty;
  4429. if (!Result)
  4430. {
  4431. SetFocus();
  4432. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  4433. }
  4434. return Result;
  4435. }
  4436. //---------------------------------------------------------------------------
  4437. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  4438. {
  4439. return CanCloseQueue(FQueue);
  4440. }
  4441. //---------------------------------------------------------------------------
  4442. void __fastcall TCustomScpExplorerForm::CloseSession()
  4443. {
  4444. if (CanCloseQueue())
  4445. {
  4446. TTerminalManager::Instance()->FreeActiveTerminal();
  4447. }
  4448. }
  4449. //---------------------------------------------------------------------------
  4450. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  4451. {
  4452. if (OpenInNewWindow())
  4453. {
  4454. // encode session name because of slashes in hierarchical sessions
  4455. ExecuteNewInstance(EncodeUrlString(Data->Name));
  4456. }
  4457. else
  4458. {
  4459. TTerminalManager * Manager = TTerminalManager::Instance();
  4460. TTerminal * Terminal = Manager->NewTerminal(Data);
  4461. Manager->ActiveTerminal = Terminal;
  4462. }
  4463. }
  4464. //---------------------------------------------------------------------------
  4465. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  4466. {
  4467. if (OpenInNewWindow())
  4468. {
  4469. ExecuteNewInstance(Name);
  4470. }
  4471. else
  4472. {
  4473. TTerminalManager * Manager = TTerminalManager::Instance();
  4474. std::unique_ptr<TObjectList> DataList(new TObjectList());
  4475. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  4476. Manager->ActiveTerminal = Manager->NewTerminals(DataList.get());
  4477. }
  4478. }
  4479. //---------------------------------------------------------------------------
  4480. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  4481. bool &CanClose)
  4482. {
  4483. if (Terminal != NULL)
  4484. {
  4485. if (Terminal->Active && WinConfiguration->ConfirmClosingSession)
  4486. {
  4487. unsigned int Result;
  4488. TMessageParams Params(mpNeverAskAgainCheck);
  4489. UnicodeString Message;
  4490. int Answers = qaOK | qaCancel;
  4491. if (TTerminalManager::Instance()->Count > 1)
  4492. {
  4493. if (!WinConfiguration->AutoSaveWorkspace)
  4494. {
  4495. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE2);
  4496. Answers = qaYes | qaNo | qaCancel;
  4497. }
  4498. else
  4499. {
  4500. Message = MainInstructions(LoadStr(CLOSE_SESSIONS));
  4501. }
  4502. }
  4503. else
  4504. {
  4505. Message = MainInstructions(FMTLOAD(CLOSE_SESSION, (Terminal->SessionData->SessionName)));
  4506. }
  4507. if (WinConfiguration->AutoSaveWorkspace)
  4508. {
  4509. Message =
  4510. FORMAT("%s\n\n%s", (Message,
  4511. FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()))));
  4512. }
  4513. SetFocus();
  4514. Result = MessageDialog(Message, qtConfirmation,
  4515. Answers, HELP_NONE, &Params);
  4516. if (Result == qaNeverAskAgain)
  4517. {
  4518. WinConfiguration->ConfirmClosingSession = false;
  4519. }
  4520. if (Result == qaNo)
  4521. {
  4522. CanClose = SaveWorkspace(true);
  4523. // note that the workspace will be saved redundatly again from FormClose
  4524. }
  4525. else
  4526. {
  4527. CanClose =
  4528. (Result == qaOK) ||
  4529. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  4530. (Result == qaNeverAskAgain);
  4531. }
  4532. }
  4533. if (CanClose)
  4534. {
  4535. CanClose = CanCloseQueue();
  4536. }
  4537. }
  4538. if (CanClose)
  4539. {
  4540. CanClose =
  4541. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  4542. FEditorManager->CloseExternalFilesWithoutProcess();
  4543. if (CanClose)
  4544. {
  4545. while (CanClose && (FLocalEditors->Count > 0))
  4546. {
  4547. int PrevCount = FLocalEditors->Count;
  4548. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  4549. CanClose = (FLocalEditors->Count < PrevCount);
  4550. }
  4551. if (CanClose)
  4552. {
  4553. CanClose = FEditorManager->Empty(true);
  4554. if (!CanClose)
  4555. {
  4556. SetFocus();
  4557. CanClose =
  4558. (MessageDialog(
  4559. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  4560. }
  4561. }
  4562. }
  4563. }
  4564. }
  4565. //---------------------------------------------------------------------------
  4566. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  4567. {
  4568. TForm * Form = dynamic_cast<TForm *>(Sender);
  4569. DebugAssert(Form != NULL);
  4570. Form->Close();
  4571. }
  4572. //---------------------------------------------------------------------------
  4573. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  4574. {
  4575. TForm * Form = dynamic_cast<TForm *>(Sender);
  4576. delete Form;
  4577. }
  4578. //---------------------------------------------------------------------------
  4579. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  4580. {
  4581. while (FLocalEditors->Count > 0)
  4582. {
  4583. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  4584. }
  4585. }
  4586. //---------------------------------------------------------------------------
  4587. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  4588. TObject *Sender)
  4589. {
  4590. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  4591. try
  4592. {
  4593. SetProperties(osRemote, FileList);
  4594. }
  4595. __finally
  4596. {
  4597. delete FileList;
  4598. }
  4599. }
  4600. //---------------------------------------------------------------------------
  4601. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  4602. {
  4603. if (value)
  4604. {
  4605. if (Component == fcCustomCommandsBand)
  4606. {
  4607. UpdateCustomCommandsToolbar();
  4608. }
  4609. }
  4610. }
  4611. //---------------------------------------------------------------------------
  4612. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  4613. {
  4614. TControl * Control = GetComponent(Component);
  4615. DebugAssert(Control);
  4616. bool Changed = (Control->Visible != value);
  4617. if (Changed)
  4618. {
  4619. ComponentShowing(Component, value);
  4620. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  4621. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  4622. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  4623. if (value)
  4624. {
  4625. int RemainingHeight = Control->Parent->ClientHeight;
  4626. int RemainingWidth = Control->Parent->ClientWidth;
  4627. for (int i = 0; i < Control->Parent->ControlCount; i++)
  4628. {
  4629. TControl * ChildControl = Control->Parent->Controls[i];
  4630. if (ChildControl->Visible)
  4631. {
  4632. switch (ChildControl->Align)
  4633. {
  4634. case alTop:
  4635. case alBottom:
  4636. RemainingHeight -= ChildControl->Height;
  4637. break;
  4638. case alLeft:
  4639. case alRight:
  4640. RemainingWidth -= ChildControl->Width;
  4641. break;
  4642. }
  4643. }
  4644. }
  4645. int Reserve = ScaleByTextHeight(this, 32);
  4646. // queue in explorer, trees in commander
  4647. if (Control->Height > RemainingHeight - Reserve)
  4648. {
  4649. Control->Height = RemainingHeight / 2;
  4650. }
  4651. if (Control->Width > RemainingWidth - Reserve)
  4652. {
  4653. Control->Width = RemainingWidth / 2;
  4654. }
  4655. }
  4656. Control->Visible = value;
  4657. if (WasFocused && Visible)
  4658. {
  4659. DirView(osCurrent)->SetFocus();
  4660. }
  4661. FixControlsPlacement();
  4662. }
  4663. }
  4664. //---------------------------------------------------------------------------
  4665. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  4666. {
  4667. TControl * Control = GetComponent(Component);
  4668. if (Control == NULL)
  4669. {
  4670. return false;
  4671. }
  4672. else
  4673. {
  4674. return Control->Visible;
  4675. }
  4676. }
  4677. //---------------------------------------------------------------------------
  4678. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  4679. {
  4680. bool Result;
  4681. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  4682. {
  4683. Result = !IsUWP();
  4684. }
  4685. else
  4686. {
  4687. Result = true;
  4688. }
  4689. return Result;
  4690. }
  4691. //---------------------------------------------------------------------------
  4692. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  4693. {
  4694. if (RemoteDirView->ItemFocused != NULL)
  4695. {
  4696. RemoteDirView->ItemFocused->MakeVisible(false);
  4697. }
  4698. QueueSplitter->Visible = QueuePanel->Visible;
  4699. RemotePanelSplitter->Visible = RemoteDriveView->Visible;
  4700. }
  4701. //---------------------------------------------------------------------------
  4702. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  4703. {
  4704. switch (Component) {
  4705. case fcStatusBar: return RemoteStatusBar;
  4706. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  4707. case fcQueueView: return QueuePanel;
  4708. case fcQueueToolbar: return QueueDock;
  4709. case fcRemoteTree: return RemoteDriveView;
  4710. case fcSessionsTabs: return SessionsPageControl;
  4711. default: return NULL;
  4712. }
  4713. }
  4714. //---------------------------------------------------------------------------
  4715. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  4716. TObject *Sender, TListColumn *Column, TPoint &Point)
  4717. {
  4718. DebugAssert(NonVisualDataModule && Column && Sender);
  4719. NonVisualDataModule->ListColumn = Column;
  4720. TPopupMenu * DirViewColumnMenu;
  4721. if (Sender == RemoteDirView)
  4722. {
  4723. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  4724. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible =
  4725. (Column->Index == uvName);
  4726. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible =
  4727. (Column->Index == uvSize);
  4728. }
  4729. else
  4730. {
  4731. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  4732. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible =
  4733. (Column->Index == dvName);
  4734. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible =
  4735. (Column->Index == dvSize);
  4736. }
  4737. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  4738. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  4739. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  4740. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  4741. }
  4742. //---------------------------------------------------------------------------
  4743. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  4744. TObject *Sender, TListItem *Item, bool &AllowExec)
  4745. {
  4746. DoDirViewExecFile(Sender, Item, AllowExec);
  4747. }
  4748. //---------------------------------------------------------------------------
  4749. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  4750. TListItem * Item, bool & AllowExec)
  4751. {
  4752. DebugAssert(Sender && Item && Configuration);
  4753. DebugAssert(AllowExec);
  4754. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  4755. bool Remote = (ADirView == DirView(osRemote));
  4756. bool ResolvedSymlinks = !Remote || Terminal->ResolvingSymlinks;
  4757. TOperationSide Side = (Remote ? osRemote : osLocal);
  4758. // Anything special is done on double click only (not on "open" indicated by FForceExecution),
  4759. // on files only (not directories)
  4760. // and only when symlinks are resolved (apply to remote panel only)
  4761. if (!ADirView->ItemIsDirectory(Item) &&
  4762. (ResolvedSymlinks || FForceExecution || Terminal->IsEncryptingFiles()))
  4763. {
  4764. if ((WinConfiguration->DoubleClickAction != dcaOpen) &&
  4765. !FForceExecution &&
  4766. (ResolvedSymlinks || Terminal->IsEncryptingFiles()))
  4767. {
  4768. if (WinConfiguration->DoubleClickAction == dcaCopy)
  4769. {
  4770. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  4771. UnlockWindow();
  4772. try
  4773. {
  4774. ExecuteFileOperation(
  4775. foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  4776. }
  4777. __finally
  4778. {
  4779. LockWindow();
  4780. }
  4781. AllowExec = false;
  4782. }
  4783. else if (WinConfiguration->DoubleClickAction == dcaEdit)
  4784. {
  4785. if (!Remote || !WinConfiguration->DisableOpenEdit)
  4786. {
  4787. ExecuteFile(Side, efDefaultEditor);
  4788. AllowExec = false;
  4789. }
  4790. }
  4791. else
  4792. {
  4793. DebugFail();
  4794. }
  4795. }
  4796. // if we have not done anything special, fall back to default behavior
  4797. if (AllowExec)
  4798. {
  4799. if (Remote && !WinConfiguration->DisableOpenEdit)
  4800. {
  4801. ExecuteFile(osRemote, efShell);
  4802. AllowExec = false;
  4803. }
  4804. }
  4805. }
  4806. }
  4807. //---------------------------------------------------------------------------
  4808. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  4809. {
  4810. return ((Side == osRemote) || (Side == osCurrent));
  4811. }
  4812. //---------------------------------------------------------------------------
  4813. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  4814. {
  4815. DebugFail();
  4816. }
  4817. //---------------------------------------------------------------------------
  4818. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  4819. {
  4820. DebugFail();
  4821. }
  4822. //---------------------------------------------------------------------------
  4823. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  4824. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, bool UseDefaults)
  4825. {
  4826. TSynchronizeParamType Params;
  4827. Params.LocalDirectory = LocalDirectory;
  4828. Params.RemoteDirectory = RemoteDirectory;
  4829. int UnusedParams =
  4830. (GUIConfiguration->SynchronizeParams &
  4831. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize));
  4832. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  4833. Params.Options = GUIConfiguration->SynchronizeOptions;
  4834. bool SaveSettings = false;
  4835. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  4836. &DoSynchronizeTooManyDirectories);
  4837. DebugAssert(FSynchronizeController == NULL);
  4838. FSynchronizeController = &Controller;
  4839. bool Result;
  4840. try
  4841. {
  4842. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4843. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  4844. int Options =
  4845. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  4846. DebugAssert(FOnFeedSynchronizeError == NULL);
  4847. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  4848. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  4849. FOnFeedSynchronizeError, SynchronizeInNewWindow, UseDefaults);
  4850. if (Result)
  4851. {
  4852. if (SaveSettings)
  4853. {
  4854. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  4855. GUIConfiguration->SynchronizeOptions = Params.Options;
  4856. }
  4857. else
  4858. {
  4859. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  4860. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  4861. FLAGSET(Params.Options, soSynchronize))
  4862. {
  4863. GUIConfiguration->SynchronizeOptions =
  4864. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  4865. soSynchronize;
  4866. }
  4867. }
  4868. LocalDirectory = Params.LocalDirectory;
  4869. RemoteDirectory = Params.RemoteDirectory;
  4870. }
  4871. }
  4872. __finally
  4873. {
  4874. FSynchronizeController = NULL;
  4875. DebugAssert(FOnFeedSynchronizeError == NULL);
  4876. FOnFeedSynchronizeError = NULL;
  4877. }
  4878. return Result;
  4879. }
  4880. //---------------------------------------------------------------------------
  4881. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  4882. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  4883. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  4884. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  4885. TSynchronizeOptions * Options, bool Full)
  4886. {
  4887. // Keep-up-to-date mode
  4888. if (Terminal->Status == ssOpened)
  4889. {
  4890. try
  4891. {
  4892. int PParams = Params.Params;
  4893. if (!Full)
  4894. {
  4895. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  4896. if (FLAGSET(Params.Options, soRecurse))
  4897. {
  4898. PParams |= TTerminal::spSubDirs;
  4899. }
  4900. }
  4901. else
  4902. {
  4903. // if keepuptodate is non-recursive,
  4904. // full sync before has to be non-recursive as well
  4905. if (FLAGCLEAR(Params.Options, soRecurse))
  4906. {
  4907. PParams |= TTerminal::spNoRecurse;
  4908. }
  4909. }
  4910. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  4911. PParams, Checklist, Options);
  4912. }
  4913. catch (Exception & E)
  4914. {
  4915. if (FLAGSET(Params.Options, soContinueOnError) && Terminal->Active &&
  4916. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  4917. {
  4918. // noop, already logged in MoreMessageDialog
  4919. }
  4920. else
  4921. {
  4922. ShowExtendedExceptionEx(Terminal, &E);
  4923. throw;
  4924. }
  4925. }
  4926. }
  4927. }
  4928. //---------------------------------------------------------------------------
  4929. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  4930. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  4931. const UnicodeString ErrorStr)
  4932. {
  4933. if (!Directory.IsEmpty())
  4934. {
  4935. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  4936. }
  4937. else
  4938. {
  4939. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  4940. }
  4941. }
  4942. //---------------------------------------------------------------------------
  4943. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  4944. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  4945. {
  4946. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  4947. {
  4948. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  4949. }
  4950. else
  4951. {
  4952. TMessageParams Params(mpNeverAskAgainCheck);
  4953. unsigned int Result = MessageDialog(
  4954. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  4955. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  4956. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  4957. {
  4958. MaxDirectories *= 2;
  4959. if (Result == qaNeverAskAgain)
  4960. {
  4961. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  4962. }
  4963. }
  4964. else
  4965. {
  4966. Abort();
  4967. }
  4968. }
  4969. }
  4970. //---------------------------------------------------------------------------
  4971. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  4972. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4973. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  4974. TSynchronizeOptions * Options)
  4975. {
  4976. // Keep-up-to-date mode
  4977. DebugAssert(!FAutoOperation);
  4978. void * BatchStorage;
  4979. BatchStart(BatchStorage);
  4980. FAutoOperation = true;
  4981. bool AnyOperation = false;
  4982. TDateTime StartTime = Now();
  4983. TSynchronizeChecklist * AChecklist = NULL;
  4984. try
  4985. {
  4986. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, true);
  4987. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  4988. {
  4989. FSynchronizeProgressForm->Start();
  4990. }
  4991. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  4992. static_cast<TTerminal::TSynchronizeMode>(Mode),
  4993. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  4994. Options);
  4995. SAFE_DESTROY(FSynchronizeProgressForm);
  4996. AnyOperation = (AChecklist->CheckedCount > 0);
  4997. if (AnyOperation)
  4998. {
  4999. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5000. CreateProgressForm(&SynchronizeProgress);
  5001. try
  5002. {
  5003. Terminal->SynchronizeApply(
  5004. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5005. SynchronizeProcessedItem, NULL, NULL, NULL);
  5006. }
  5007. __finally
  5008. {
  5009. DestroyProgressForm();
  5010. }
  5011. }
  5012. }
  5013. __finally
  5014. {
  5015. if (Checklist == NULL)
  5016. {
  5017. delete AChecklist;
  5018. }
  5019. else
  5020. {
  5021. *Checklist = AChecklist;
  5022. }
  5023. FAutoOperation = false;
  5024. SAFE_DESTROY(FSynchronizeProgressForm);
  5025. BatchEnd(BatchStorage);
  5026. ReloadLocalDirectory();
  5027. if (AnyOperation)
  5028. {
  5029. OperationComplete(StartTime);
  5030. }
  5031. }
  5032. }
  5033. //---------------------------------------------------------------------------
  5034. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5035. {
  5036. // can be called from command line
  5037. return Visible &&
  5038. ((DirView(osRemote)->SelCount > 0) ||
  5039. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5040. }
  5041. //---------------------------------------------------------------------------
  5042. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5043. {
  5044. LogSynchronizeEvent(Terminal, Message);
  5045. }
  5046. //---------------------------------------------------------------------------
  5047. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5048. int Params, TSynchronizeOptions & Options)
  5049. {
  5050. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5051. {
  5052. Options.Filter = new TStringList();
  5053. Options.Filter->CaseSensitive = false;
  5054. Options.Filter->Duplicates = Types::dupAccept;
  5055. if (DirView(osRemote)->SelCount > 0)
  5056. {
  5057. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5058. }
  5059. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5060. {
  5061. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5062. }
  5063. Options.Filter->Sort();
  5064. }
  5065. }
  5066. //---------------------------------------------------------------------------
  5067. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5068. {
  5069. TCopyParamType Defaults;
  5070. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5071. ConfigStorage->AccessMode = smRead;
  5072. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false, false))
  5073. {
  5074. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5075. }
  5076. ConfigStorage.reset(NULL);
  5077. std::unique_ptr<TStringList> Options(new TStringList());
  5078. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5079. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5080. UnicodeString Result;
  5081. if (Options->Count > 0)
  5082. {
  5083. Result =
  5084. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5085. }
  5086. return Result;
  5087. }
  5088. //---------------------------------------------------------------------------
  5089. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5090. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5091. {
  5092. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5093. UnicodeString AdditionalParams =
  5094. FORMAT(L"%s \"%s\" \"%s\" %d %d %s%s", (
  5095. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5096. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options,
  5097. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5098. SerializeCopyParamForCommandLine(CopyParams)));
  5099. ExecuteNewInstance(SessionName, AdditionalParams);
  5100. }
  5101. //---------------------------------------------------------------------------
  5102. struct TSynchronizeParams
  5103. {
  5104. UnicodeString LocalDirectory;
  5105. UnicodeString RemoteDirectory;
  5106. TSynchronizeMode Mode;
  5107. TSynchronizeChecklist * Checklist;
  5108. int Params;
  5109. TCopyParamType * CopyParam;
  5110. TDateTime CollectElapsed;
  5111. TDateTime * StartTime;
  5112. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5113. };
  5114. //---------------------------------------------------------------------------
  5115. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5116. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5117. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5118. {
  5119. DebugAssert(!FAutoOperation);
  5120. void * BatchStorage;
  5121. BatchStart(BatchStorage);
  5122. FAutoOperation = true;
  5123. TFileOperationStatistics Statistics;
  5124. TDateTime Start = Now();
  5125. try
  5126. {
  5127. Params.OnProcessedItem = OnProcessedItem;
  5128. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5129. CreateProgressForm(&SynchronizeProgress);
  5130. Terminal->SynchronizeApply(
  5131. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5132. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5133. &Statistics);
  5134. }
  5135. __finally
  5136. {
  5137. Params.OnProcessedItem = NULL;
  5138. FAutoOperation = false;
  5139. DestroyProgressForm();
  5140. BatchEnd(BatchStorage);
  5141. ReloadLocalDirectory();
  5142. }
  5143. if (WinConfiguration->SynchronizeSummary)
  5144. {
  5145. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5146. // The statistics should be 0 anyway in this case
  5147. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5148. {
  5149. Message += L"\n";
  5150. if (Statistics.FilesUploaded > 0)
  5151. {
  5152. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5153. }
  5154. if (Statistics.FilesDownloaded > 0)
  5155. {
  5156. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5157. }
  5158. if (Statistics.FilesDeletedLocal > 0)
  5159. {
  5160. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5161. }
  5162. if (Statistics.FilesDeletedRemote > 0)
  5163. {
  5164. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5165. }
  5166. }
  5167. TDateTime Elapsed = (Now() - Start);
  5168. Message +=
  5169. L"\n" +
  5170. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Configuration->TimeFormat, Params.CollectElapsed))) + L"\n" +
  5171. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Configuration->TimeFormat, Elapsed)));
  5172. TMessageParams Params(mpNeverAskAgainCheck);
  5173. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5174. if (Result == qaNeverAskAgain)
  5175. {
  5176. WinConfiguration->SynchronizeSummary = false;
  5177. }
  5178. }
  5179. }
  5180. //---------------------------------------------------------------------------
  5181. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5182. {
  5183. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5184. {
  5185. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5186. }
  5187. // Not set in keep-up-to-date mode - Synchronize() method
  5188. if (Token != NULL)
  5189. {
  5190. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5191. if (Params.OnProcessedItem != NULL)
  5192. {
  5193. Params.OnProcessedItem(NULL, ChecklistItem);
  5194. }
  5195. }
  5196. }
  5197. //---------------------------------------------------------------------------
  5198. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5199. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5200. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5201. {
  5202. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5203. *Params.StartTime = Now();
  5204. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5205. }
  5206. //---------------------------------------------------------------------------
  5207. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5208. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5209. {
  5210. // terminal can be already closed (e.g. dropped connection)
  5211. if (Terminal != NULL)
  5212. {
  5213. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5214. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5215. }
  5216. }
  5217. //---------------------------------------------------------------------------
  5218. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5219. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5220. {
  5221. TAutoBatch AutoBatch(this);
  5222. TAutoFlag AutoOperationFlag(FAutoOperation);
  5223. if (Side == osRemote)
  5224. {
  5225. std::unique_ptr<TStrings> FileList(new TStringList());
  5226. FileList->AddObject(FileName, RemoteFile);
  5227. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5228. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5229. RemoteDirView->SaveSelection();
  5230. RemoteDirView->SaveSelectedNames();
  5231. try
  5232. {
  5233. Terminal->MoveFiles(FileList.get(), Target, FileMask);
  5234. }
  5235. catch(...)
  5236. {
  5237. RemoteDirView->DiscardSavedSelection();
  5238. throw;
  5239. }
  5240. RemoteDirView->RestoreSelection();
  5241. }
  5242. else if (DebugAlwaysTrue(Side == osLocal))
  5243. {
  5244. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5245. {
  5246. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5247. }
  5248. UnicodeString Directory = ExtractFileDir(FileName);
  5249. ReloadLocalDirectory(Directory);
  5250. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5251. if (!SamePaths(Directory, NewDirectory))
  5252. {
  5253. ReloadLocalDirectory(NewDirectory);
  5254. }
  5255. }
  5256. }
  5257. //---------------------------------------------------------------------------
  5258. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  5259. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  5260. const TCopyParamType * CopyParams)
  5261. {
  5262. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5263. UnicodeString AdditionalParams =
  5264. FORMAT(L"%s \"%s\" \"%s\" %d %d %s%s", (
  5265. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  5266. LocalDirectory, RemoteDirectory, Mode, Params,
  5267. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5268. SerializeCopyParamForCommandLine(CopyParams)));
  5269. ExecuteNewInstance(SessionName, AdditionalParams);
  5270. }
  5271. //---------------------------------------------------------------------------
  5272. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  5273. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  5274. TSynchronizeMode & Mode, int Params, bool & SaveMode, bool UseDefaults)
  5275. {
  5276. int Result;
  5277. bool SaveSettings = false;
  5278. int Options =
  5279. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  5280. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  5281. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5282. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  5283. bool Continue =
  5284. UseDefaults ||
  5285. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  5286. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow);
  5287. if (Continue)
  5288. {
  5289. Configuration->Usage->Inc(L"Synchronizations");
  5290. UpdateCopyParamCounters(CopyParam);
  5291. TSynchronizeOptions SynchronizeOptions;
  5292. GetSynchronizeOptions(Params, SynchronizeOptions);
  5293. if (SaveSettings)
  5294. {
  5295. GUIConfiguration->SynchronizeParams = Params;
  5296. }
  5297. else
  5298. {
  5299. SaveMode = false;
  5300. }
  5301. TDateTime StartTime = Now();
  5302. TSynchronizeChecklist * Checklist = NULL;
  5303. try
  5304. {
  5305. DebugAssert(!FAutoOperation);
  5306. FAutoOperation = true;
  5307. try
  5308. {
  5309. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, true);
  5310. FSynchronizeProgressForm->Start();
  5311. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5312. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5313. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5314. &SynchronizeOptions);
  5315. }
  5316. __finally
  5317. {
  5318. FAutoOperation = false;
  5319. SAFE_DESTROY(FSynchronizeProgressForm);
  5320. }
  5321. TSynchronizeParams SynchronizeParams;
  5322. SynchronizeParams.LocalDirectory = LocalDirectory;
  5323. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  5324. SynchronizeParams.Mode = Mode;
  5325. SynchronizeParams.CopyParam = &CopyParam;
  5326. SynchronizeParams.Params = Params;
  5327. SynchronizeParams.Checklist = Checklist;
  5328. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  5329. SynchronizeParams.StartTime = &StartTime;
  5330. SynchronizeParams.OnProcessedItem = NULL;
  5331. Result = Checklist->Count;
  5332. if (Checklist->Count > 0)
  5333. {
  5334. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  5335. {
  5336. if (!DoSynchronizeChecklistDialog(
  5337. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  5338. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, &SynchronizeParams))
  5339. {
  5340. Result = -1;
  5341. }
  5342. }
  5343. else
  5344. {
  5345. FullSynchronize(SynchronizeParams, NULL, NULL);
  5346. }
  5347. }
  5348. else
  5349. {
  5350. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  5351. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  5352. }
  5353. }
  5354. __finally
  5355. {
  5356. delete Checklist;
  5357. }
  5358. OperationComplete(StartTime);
  5359. }
  5360. else
  5361. {
  5362. Result = -1;
  5363. }
  5364. return Result;
  5365. }
  5366. //---------------------------------------------------------------------------
  5367. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  5368. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  5369. bool & Continue, bool Collect)
  5370. {
  5371. if (Collect)
  5372. {
  5373. DebugAssert(FSynchronizeProgressForm != NULL);
  5374. if (!FSynchronizeProgressForm->Started)
  5375. {
  5376. FSynchronizeProgressForm->Start();
  5377. }
  5378. FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Continue);
  5379. }
  5380. else
  5381. {
  5382. DebugAssert(FSynchronizeProgressForm == NULL);
  5383. DebugAssert(FProgressForm != NULL);
  5384. }
  5385. }
  5386. //---------------------------------------------------------------------------
  5387. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  5388. {
  5389. UnicodeString FullFileName = AbsolutePath(FTerminal->CurrentDirectory, FileName);
  5390. TRemoteFile * File = NULL;
  5391. Terminal->ReadFile(FullFileName, File);
  5392. if (File != NULL)
  5393. {
  5394. std::unique_ptr<TRemoteFile> FileOwner(File);
  5395. TAutoFlag Flag(FStandaloneEditing);
  5396. ExecuteRemoteFile(FullFileName, File, efInternalEditor);
  5397. Application->ShowMainForm = false;
  5398. Application->Run();
  5399. }
  5400. }
  5401. //---------------------------------------------------------------------------
  5402. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory()
  5403. {
  5404. DebugFail();
  5405. }
  5406. //---------------------------------------------------------------------------
  5407. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  5408. {
  5409. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  5410. SessionData->Assign(Terminal->SessionData);
  5411. UpdateSessionData(SessionData.get());
  5412. Terminal->UpdateSessionCredentials(SessionData.get());
  5413. if (!Terminal->SessionData->HasSessionName())
  5414. {
  5415. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  5416. // once IsWorkspace is cleared
  5417. SessionData->Name = UnicodeString();
  5418. SessionData->IsWorkspace = false;
  5419. }
  5420. return SessionData.release();
  5421. }
  5422. //---------------------------------------------------------------------------
  5423. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  5424. {
  5425. TSessionData * SessionData = CloneCurrentSessionData();
  5426. try
  5427. {
  5428. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  5429. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  5430. }
  5431. __finally
  5432. {
  5433. delete SessionData;
  5434. }
  5435. }
  5436. //---------------------------------------------------------------------------
  5437. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  5438. {
  5439. TTerminalManager * Manager = TTerminalManager::Instance();
  5440. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5441. if (DebugAlwaysTrue(Terminal != NULL))
  5442. {
  5443. // Update (Managed)Terminal->StateData
  5444. UpdateTerminal(Terminal);
  5445. }
  5446. Manager->SaveWorkspace(DataList.get());
  5447. return DataList.release();
  5448. }
  5449. //---------------------------------------------------------------------------
  5450. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  5451. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  5452. {
  5453. WinConfiguration->LastWorkspace = Name;
  5454. if (!SavePasswords)
  5455. {
  5456. for (int Index = 0; Index < DataList->Count; Index++)
  5457. {
  5458. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  5459. if (SessionData->Link.IsEmpty())
  5460. {
  5461. SessionData->ClearSessionPasswords();
  5462. }
  5463. }
  5464. }
  5465. StoredSessions->NewWorkspace(Name, DataList);
  5466. // modified only
  5467. StoredSessions->Save(false, Explicit);
  5468. }
  5469. //---------------------------------------------------------------------------
  5470. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  5471. {
  5472. return
  5473. DefaultStr(WinConfiguration->LastWorkspace,
  5474. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  5475. }
  5476. //---------------------------------------------------------------------------
  5477. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  5478. {
  5479. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  5480. bool AnyNonStoredSessionWithPassword = false;
  5481. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  5482. bool AllNonStoredSessionsAnonymous = true;
  5483. TTerminalManager * Manager = TTerminalManager::Instance();
  5484. for (int Index = 0; Index < DataList->Count; Index++)
  5485. {
  5486. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  5487. if (SessionData->Link.IsEmpty())
  5488. {
  5489. if (SessionData->HasAnySessionPassword())
  5490. {
  5491. AnyNonStoredSessionWithPassword = true;
  5492. if (!Manager->Terminals[Index]->SessionData->IsWorkspace)
  5493. {
  5494. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  5495. }
  5496. }
  5497. if (!SameText(SessionData->UserName, AnonymousUserName))
  5498. {
  5499. AllNonStoredSessionsAnonymous = false;
  5500. }
  5501. }
  5502. }
  5503. bool SavePasswords;
  5504. bool * PSavePasswords;
  5505. bool NotRecommendedSavingPasswords =
  5506. !CustomWinConfiguration->UseMasterPassword &&
  5507. !AllNonStoredSessionsAnonymous;
  5508. if (Configuration->DisablePasswordStoring ||
  5509. !AnyNonStoredSessionWithPassword)
  5510. {
  5511. PSavePasswords = NULL;
  5512. SavePasswords = false;
  5513. }
  5514. else
  5515. {
  5516. PSavePasswords = &SavePasswords;
  5517. SavePasswords =
  5518. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  5519. !NotRecommendedSavingPasswords;
  5520. }
  5521. UnicodeString Name = WorkspaceName();
  5522. bool CreateShortcut = false;
  5523. bool Result =
  5524. DoSaveWorkspaceDialog(
  5525. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  5526. EnableAutoSave);
  5527. if (Result)
  5528. {
  5529. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  5530. if (CreateShortcut)
  5531. {
  5532. TOperationVisualizer Visualizer;
  5533. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  5534. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  5535. }
  5536. if (EnableAutoSave)
  5537. {
  5538. WinConfiguration->AutoSaveWorkspace = true;
  5539. WinConfiguration->AutoWorkspace = Name;
  5540. if (PSavePasswords != NULL)
  5541. {
  5542. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  5543. }
  5544. }
  5545. }
  5546. return Result;
  5547. }
  5548. //---------------------------------------------------------------------------
  5549. void __fastcall TCustomScpExplorerForm::UpdateTerminal(TTerminal * Terminal)
  5550. {
  5551. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  5552. DebugAssert(ManagedTerminal != NULL);
  5553. SAFE_DESTROY(ManagedTerminal->RemoteExplorerState);
  5554. if (WinConfiguration->PreservePanelState)
  5555. {
  5556. ManagedTerminal->RemoteExplorerState = RemoteDirView->SaveState();
  5557. }
  5558. UpdateSessionData(ManagedTerminal->StateData);
  5559. }
  5560. //---------------------------------------------------------------------------
  5561. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  5562. {
  5563. // Keep in sync with TSessionData::CopyStateData
  5564. DebugAssert(Data != NULL);
  5565. // This is inconsistent with how color (for example) is handled.
  5566. Data->Name = Terminal->SessionData->Name;
  5567. // cannot use RemoteDirView->Path, because it is empty if connection
  5568. // was already closed
  5569. // also only peek, we may not be connected at all atm
  5570. // so make sure we do not try retrieving current directory from the server
  5571. // (particularly with FTP)
  5572. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  5573. if (!ACurrentDirectory.IsEmpty())
  5574. {
  5575. Data->RemoteDirectory = ACurrentDirectory;
  5576. }
  5577. Data->Color = SessionColor;
  5578. }
  5579. //---------------------------------------------------------------------------
  5580. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  5581. {
  5582. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  5583. DebugAssert(Toolbar != NULL);
  5584. for (int i = 0; i < Toolbar->Items->Count; i++)
  5585. {
  5586. TTBXCustomDropDownItem * DropDownItem;
  5587. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  5588. if (DropDownItem != NULL)
  5589. {
  5590. ToolbarItemResize(DropDownItem,
  5591. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  5592. Toolbar->NonClientWidth);
  5593. break;
  5594. }
  5595. }
  5596. }
  5597. //---------------------------------------------------------------------------
  5598. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  5599. {
  5600. Item->EditWidth = Width;
  5601. }
  5602. //---------------------------------------------------------------------------
  5603. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  5604. TTBCustomToolbar * Toolbar, TPoint & ASize)
  5605. {
  5606. for (int i = 0; i < Toolbar->Items->Count; i++)
  5607. {
  5608. TTBXCustomDropDownItem * DropDownItem;
  5609. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  5610. if (DropDownItem != NULL)
  5611. {
  5612. ASize.x -= DropDownItem->EditWidth;
  5613. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  5614. }
  5615. }
  5616. }
  5617. //---------------------------------------------------------------------------
  5618. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  5619. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  5620. {
  5621. if (WinConfiguration->DDWarnLackOfTempSpace)
  5622. {
  5623. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  5624. if (!ADrive.IsEmpty())
  5625. {
  5626. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  5627. DebugAssert(RequiredSpace >= 0);
  5628. __int64 RequiredWithReserve;
  5629. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  5630. if (FreeSpace < RequiredWithReserve)
  5631. {
  5632. unsigned int Result;
  5633. TMessageParams Params(mpNeverAskAgainCheck);
  5634. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  5635. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  5636. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  5637. if (Result == qaNeverAskAgain)
  5638. {
  5639. WinConfiguration->DDWarnLackOfTempSpace = false;
  5640. }
  5641. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  5642. }
  5643. }
  5644. }
  5645. }
  5646. //---------------------------------------------------------------------------
  5647. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  5648. {
  5649. DoOpenDirectoryDialog(odAddBookmark, Side);
  5650. }
  5651. //---------------------------------------------------------------------------
  5652. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  5653. {
  5654. // we should better use TCustomDirView::FCaseSensitive, but it is private
  5655. TStringList * VisitedDirectories = CreateSortedStringList((Side == osRemote));
  5656. try
  5657. {
  5658. TCustomDirView * DView = DirView(Side);
  5659. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  5660. {
  5661. VisitedDirectories->Add(DView->HistoryPath[Index]);
  5662. }
  5663. }
  5664. catch (...)
  5665. {
  5666. delete VisitedDirectories;
  5667. throw;
  5668. }
  5669. return VisitedDirectories;
  5670. }
  5671. //---------------------------------------------------------------------------
  5672. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  5673. TOpenDirectoryMode Mode, TOperationSide Side)
  5674. {
  5675. bool Continue = true;
  5676. if (Mode == odAddBookmark)
  5677. {
  5678. TMessageParams Params(mpNeverAskAgainCheck);
  5679. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  5680. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  5681. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  5682. unsigned int Answer =
  5683. MessageDialog(Message,
  5684. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  5685. if (Answer == qaNeverAskAgain)
  5686. {
  5687. Continue = true;
  5688. WinConfiguration->UseSharedBookmarks = true;
  5689. }
  5690. else if (Answer == qaOK)
  5691. {
  5692. Continue = true;
  5693. WinConfiguration->UseSharedBookmarks = false;
  5694. }
  5695. else
  5696. {
  5697. Continue = false;
  5698. }
  5699. }
  5700. if (Continue)
  5701. {
  5702. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  5703. try
  5704. {
  5705. UnicodeString Name = DirView(Side)->PathName;
  5706. bool Repeat;
  5707. do
  5708. {
  5709. Repeat = false;
  5710. if (::DoOpenDirectoryDialog(Mode, Side, Name, VisitedDirectories, Terminal,
  5711. // do not allow switching to location profiles,
  5712. // if we are not connected
  5713. HasDirView[osLocal] && (Terminal != NULL)))
  5714. {
  5715. TWindowLock Lock(this);
  5716. if (!TryOpenDirectory(Side, Name))
  5717. {
  5718. Repeat = true;
  5719. Mode = odBrowse;
  5720. }
  5721. }
  5722. }
  5723. while (Repeat);
  5724. }
  5725. __finally
  5726. {
  5727. delete VisitedDirectories;
  5728. }
  5729. }
  5730. }
  5731. //---------------------------------------------------------------------------
  5732. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  5733. {
  5734. DebugAssert(!FTerminal->CommandSessionOpened);
  5735. return TTerminalManager::Instance()->ConnectTerminal(FTerminal->CommandSession);
  5736. }
  5737. //---------------------------------------------------------------------------
  5738. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  5739. {
  5740. bool Result = FTerminal->IsCapable[Capability] ||
  5741. FTerminal->CommandSessionOpened;
  5742. if (!Result)
  5743. {
  5744. DebugAssert(FTerminal->IsCapable[fcSecondaryShell]);
  5745. if (!GUIConfiguration->ConfirmCommandSession)
  5746. {
  5747. Result = true;
  5748. }
  5749. else
  5750. {
  5751. TMessageParams Params(mpNeverAskAgainCheck);
  5752. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  5753. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  5754. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  5755. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  5756. if (Answer == qaNeverAskAgain)
  5757. {
  5758. GUIConfiguration->ConfirmCommandSession = false;
  5759. Result = true;
  5760. }
  5761. else if (Answer == qaOK)
  5762. {
  5763. Result = true;
  5764. }
  5765. }
  5766. if (Result)
  5767. {
  5768. Result = CommandSessionFallback();
  5769. }
  5770. }
  5771. return Result;
  5772. }
  5773. //---------------------------------------------------------------------------
  5774. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  5775. {
  5776. if (EnsureCommandSessionFallback(fcAnyCommand))
  5777. {
  5778. DoConsoleDialog(Terminal, Command);
  5779. }
  5780. }
  5781. //---------------------------------------------------------------------------
  5782. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  5783. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  5784. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  5785. {
  5786. if (IsFileControl(DropSourceControl, osRemote) &&
  5787. (FDDExtMapFile != NULL))
  5788. {
  5789. Accept = true;
  5790. }
  5791. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  5792. DebugAssert(FDDTargetControl != NULL);
  5793. }
  5794. //---------------------------------------------------------------------------
  5795. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  5796. _di_IDataObject DataObj, int KeyState,
  5797. const TPoint & Point, int & Effect, bool & Accept)
  5798. {
  5799. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  5800. }
  5801. //---------------------------------------------------------------------------
  5802. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  5803. _di_IDataObject DataObj, int KeyState,
  5804. const TPoint & Point, int & Effect, bool & Accept)
  5805. {
  5806. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  5807. }
  5808. //---------------------------------------------------------------------------
  5809. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  5810. TObject * Sender)
  5811. {
  5812. DebugUsedParam(Sender);
  5813. DebugAssert(FDDTargetControl == Sender);
  5814. FDDTargetControl = NULL;
  5815. }
  5816. //---------------------------------------------------------------------------
  5817. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  5818. {
  5819. FileControlDDDragLeave(SessionsPageControl);
  5820. }
  5821. //---------------------------------------------------------------------------
  5822. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  5823. {
  5824. FileControlDDDragLeave(QueueView3);
  5825. }
  5826. //---------------------------------------------------------------------------
  5827. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  5828. {
  5829. DebugAssert(GetSide(Side) == osRemote);
  5830. DebugUsedParam(Side);
  5831. bool Edit = false;
  5832. TRemoteFile * File = NULL;
  5833. UnicodeString FileName;
  5834. UnicodeString PointTo;
  5835. bool SymbolicLink = true;
  5836. if (RemoteDirView->ItemFocused)
  5837. {
  5838. DebugAssert(RemoteDirView->ItemFocused->Data);
  5839. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  5840. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  5841. if (Edit)
  5842. {
  5843. FileName = File->FileName;
  5844. PointTo = File->LinkTo;
  5845. }
  5846. else
  5847. {
  5848. PointTo = File->FileName;
  5849. }
  5850. }
  5851. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  5852. Terminal->IsCapable[fcHardLink]))
  5853. {
  5854. Configuration->Usage->Inc(L"RemoteLinksCreated");
  5855. if (Edit)
  5856. {
  5857. DebugAssert(File->FileName == FileName);
  5858. int Params = dfNoRecursive;
  5859. Terminal->ExceptionOnFail = true;
  5860. try
  5861. {
  5862. Terminal->DeleteFile(L"", File, &Params);
  5863. }
  5864. __finally
  5865. {
  5866. Terminal->ExceptionOnFail = false;
  5867. }
  5868. }
  5869. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  5870. }
  5871. }
  5872. //---------------------------------------------------------------------------
  5873. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  5874. {
  5875. return
  5876. (Terminal != NULL) &&
  5877. ((GetSide(Side) != osRemote) ||
  5878. (Terminal->ResolvingSymlinks &&
  5879. Terminal->IsCapable[fcSymbolicLink]));
  5880. }
  5881. //---------------------------------------------------------------------------
  5882. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  5883. {
  5884. return
  5885. (FCurrentSide == osRemote) &&
  5886. (RemoteDirView->ItemFocused != NULL) &&
  5887. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  5888. Terminal->SessionData->ResolveSymlinks;
  5889. }
  5890. //---------------------------------------------------------------------------
  5891. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  5892. {
  5893. DebugAssert(!WinConfiguration->DisableOpenEdit);
  5894. FForceExecution = true;
  5895. try
  5896. {
  5897. DirView(osCurrent)->ExecuteCurrentFile();
  5898. }
  5899. __finally
  5900. {
  5901. FForceExecution = false;
  5902. }
  5903. }
  5904. //---------------------------------------------------------------------------
  5905. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  5906. {
  5907. TEditorData ExternalEditor;
  5908. ExternalEditor.Editor = edExternal;
  5909. bool Remember = false;
  5910. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc,
  5911. (GetSide(osCurrent) == osRemote)))
  5912. {
  5913. if (Remember)
  5914. {
  5915. TEditorList * EditorList = new TEditorList;
  5916. try
  5917. {
  5918. *EditorList = *WinConfiguration->EditorList;
  5919. bool Found = false;
  5920. int i = 0;
  5921. while (!Found && (i < EditorList->Count))
  5922. {
  5923. const TEditorPreferences * Editor = EditorList->Editors[i];
  5924. if ((Editor->Data->Editor == edExternal) &&
  5925. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  5926. {
  5927. Found = true;
  5928. }
  5929. i++;
  5930. }
  5931. if (!Found)
  5932. {
  5933. EditorList->Add(new TEditorPreferences(ExternalEditor));
  5934. WinConfiguration->EditorList = EditorList;
  5935. }
  5936. }
  5937. __finally
  5938. {
  5939. delete EditorList;
  5940. }
  5941. }
  5942. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  5943. }
  5944. }
  5945. //---------------------------------------------------------------------------
  5946. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  5947. {
  5948. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  5949. if (FFileFindTerminal == Sender)
  5950. {
  5951. FFileFindTerminal = NULL;
  5952. HideFileFindDialog();
  5953. }
  5954. if (FClipboardTerminal == Sender)
  5955. {
  5956. ClipboardClear(); // implies ClipboardStop
  5957. }
  5958. }
  5959. //---------------------------------------------------------------------------
  5960. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  5961. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  5962. {
  5963. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  5964. DebugAssert(Terminal != NULL);
  5965. if (Data->Terminal == Terminal)
  5966. {
  5967. Data->Terminal = NULL;
  5968. }
  5969. }
  5970. //---------------------------------------------------------------------------
  5971. void __fastcall TCustomScpExplorerForm::LastTerminalClosed(TObject * /*Sender*/)
  5972. {
  5973. UpdateControls();
  5974. SessionColor = TColor(0);
  5975. UpdateRemotePathComboBox(false);
  5976. NeedSession(true);
  5977. }
  5978. //---------------------------------------------------------------------------
  5979. void __fastcall TCustomScpExplorerForm::NeedSession(bool ReloadSessions)
  5980. {
  5981. try
  5982. {
  5983. try
  5984. {
  5985. TTerminalManager::Instance()->NewSession(false, L"", ReloadSessions, this);
  5986. }
  5987. __finally
  5988. {
  5989. if (!WinConfiguration->KeepOpenWhenNoSession &&
  5990. (!Terminal || !Terminal->Active))
  5991. {
  5992. TerminateApplication();
  5993. }
  5994. }
  5995. }
  5996. catch (EAbort &)
  5997. {
  5998. // swallow
  5999. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6000. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6001. }
  6002. }
  6003. //---------------------------------------------------------------------------
  6004. void __fastcall TCustomScpExplorerForm::DoTerminalListChanged()
  6005. {
  6006. TStrings * TerminalList = TTerminalManager::Instance()->TerminalList;
  6007. int ActiveTerminalIndex = TTerminalManager::Instance()->ActiveTerminalIndex;
  6008. Configuration->Usage->SetMax(L"MaxOpenedSessions", TerminalList->Count);
  6009. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6010. try
  6011. {
  6012. while ((SessionsPageControl->PageCount > TerminalList->Count + 1) ||
  6013. // Clear the design time unthemed tab
  6014. ((SessionsPageControl->PageCount > 0) &&
  6015. (dynamic_cast<TThemeTabSheet *>(SessionsPageControl->Pages[SessionsPageControl->PageCount - 1]) == NULL)))
  6016. {
  6017. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6018. }
  6019. for (int Index = 0; Index <= TerminalList->Count; Index++)
  6020. {
  6021. TThemeTabSheet * TabSheet;
  6022. if (Index >= SessionsPageControl->PageCount)
  6023. {
  6024. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6025. TabSheet->PageControl = SessionsPageControl;
  6026. }
  6027. else
  6028. {
  6029. TabSheet = DebugNotNull(dynamic_cast<TThemeTabSheet *>(SessionsPageControl->Pages[Index]));
  6030. }
  6031. bool IsSessionTab = (Index < TerminalList->Count);
  6032. if (IsSessionTab)
  6033. {
  6034. TTerminal * Terminal = dynamic_cast<TTerminal *>(TerminalList->Objects[Index]);
  6035. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6036. UpdateSessionTab(TabSheet);
  6037. }
  6038. else
  6039. {
  6040. TabSheet->ImageIndex = FNewSessionTabImageIndex;
  6041. TabSheet->Tag = 0; // not really needed
  6042. // We know that we are at the last page, sotherwise we could not call this (it assumes that new session tab is the last one)
  6043. UpdateNewSessionTab();
  6044. }
  6045. TabSheet->ShowCloseButton = IsSessionTab;
  6046. }
  6047. }
  6048. __finally
  6049. {
  6050. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6051. }
  6052. SessionsPageControl->ActivePageIndex = ActiveTerminalIndex;
  6053. }
  6054. //---------------------------------------------------------------------------
  6055. void __fastcall TCustomScpExplorerForm::TerminalListChanged(TObject * /*Sender*/)
  6056. {
  6057. DoTerminalListChanged();
  6058. }
  6059. //---------------------------------------------------------------------------
  6060. void __fastcall TCustomScpExplorerForm::UpdateNewSessionTab()
  6061. {
  6062. TTabSheet * TabSheet = SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6063. DebugAssert(TabSheet->ImageIndex == 0);
  6064. TabSheet->Caption =
  6065. WinConfiguration->SelectiveToolbarText ?
  6066. StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewSessionAction->Caption)) :
  6067. UnicodeString();
  6068. }
  6069. //---------------------------------------------------------------------------
  6070. TTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabTerminal(TTabSheet * TabSheet)
  6071. {
  6072. return reinterpret_cast<TTerminal *>(TabSheet->Tag);
  6073. }
  6074. //---------------------------------------------------------------------------
  6075. void __fastcall TCustomScpExplorerForm::UpdateSessionTab(TTabSheet * TabSheet)
  6076. {
  6077. if (DebugAlwaysTrue(TabSheet != NULL))
  6078. {
  6079. TManagedTerminal * ManagedTerminal =
  6080. dynamic_cast<TManagedTerminal *>(GetSessionTabTerminal(TabSheet));
  6081. if (DebugAlwaysTrue(ManagedTerminal != NULL))
  6082. {
  6083. TColor Color = (ManagedTerminal == FTerminal) ? FSessionColor : ManagedTerminal->StateData->Color;
  6084. TabSheet->ImageIndex = AddSessionColor(Color);
  6085. UnicodeString TabCaption = TTerminalManager::Instance()->GetTerminalTitle(ManagedTerminal, true);
  6086. TabSheet->Caption = SessionsPageControl->FormatCaptionWithCloseButton(TabCaption);
  6087. TThemeTabSheet * ThemeTabSheet = dynamic_cast<TThemeTabSheet *>(TabSheet);
  6088. if (DebugAlwaysTrue(ThemeTabSheet != NULL))
  6089. {
  6090. ThemeTabSheet->Shadowed = !ManagedTerminal->Active;
  6091. }
  6092. }
  6093. }
  6094. }
  6095. //---------------------------------------------------------------------------
  6096. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6097. {
  6098. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6099. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->ActivePage);
  6100. bool Result = (Terminal != NULL);
  6101. if (Result)
  6102. {
  6103. TTerminalManager::Instance()->ActiveTerminal = Terminal;
  6104. }
  6105. else
  6106. {
  6107. try
  6108. {
  6109. NewSession(false);
  6110. }
  6111. __finally
  6112. {
  6113. DoTerminalListChanged();
  6114. }
  6115. FSessionsPageControlNewSessionTime = Now();
  6116. }
  6117. return Result;
  6118. }
  6119. //---------------------------------------------------------------------------
  6120. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6121. {
  6122. SessionTabSwitched();
  6123. }
  6124. //---------------------------------------------------------------------------
  6125. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6126. {
  6127. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6128. DebugAssert(TransferList != NULL);
  6129. UnicodeString Name;
  6130. if (TransferList->ItemIndex <= 0)
  6131. {
  6132. Name = L"";
  6133. }
  6134. else
  6135. {
  6136. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  6137. }
  6138. if (FCopyParamAutoSelected.IsEmpty())
  6139. {
  6140. // if previous preset was not autoselected, make new preset the "default"
  6141. FCopyParamDefault = Name;
  6142. }
  6143. GUIConfiguration->CopyParamCurrent = Name;
  6144. }
  6145. //---------------------------------------------------------------------------
  6146. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  6147. {
  6148. // sanity check
  6149. bool ExistingPreset =
  6150. (FTransferListHoverIndex >= 0) &&
  6151. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  6152. DebugAssert(ExistingPreset);
  6153. if (ExistingPreset)
  6154. {
  6155. HDC DC = GetDC(0);
  6156. TCanvas * Canvas = new TCanvas();
  6157. try
  6158. {
  6159. Canvas->Handle = DC;
  6160. Canvas->Font = GetToolbarFont(this);
  6161. UnicodeString Name;
  6162. if (FTransferListHoverIndex == 0)
  6163. {
  6164. Name = L"";
  6165. }
  6166. else
  6167. {
  6168. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  6169. }
  6170. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  6171. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  6172. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  6173. static_cast<TObject*>(GetComponent(fcTransferList)));
  6174. UnicodeString InfoStr =
  6175. GUIConfiguration->CopyParamPreset[Name].
  6176. GetInfoStr(L"; ",
  6177. FLAGMASK(((Terminal != NULL) && Terminal->Active), Terminal->UsableCopyParamAttrs(0).General));
  6178. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  6179. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  6180. {
  6181. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  6182. {
  6183. InfoStr.SetLength(InfoStr.Length() - 1);
  6184. }
  6185. InfoStr += Ellipsis;
  6186. }
  6187. // UpdateCaption does not cause invalidation of whole submenu, while
  6188. // setting Caption property does.
  6189. // also it probably does not resize the label, even if necessary
  6190. // (we do not want that anyway)
  6191. TransferLabel->UpdateCaption(InfoStr);
  6192. }
  6193. __finally
  6194. {
  6195. Canvas->Handle = NULL;
  6196. ReleaseDC(0, DC);
  6197. delete Canvas;
  6198. }
  6199. }
  6200. }
  6201. //---------------------------------------------------------------------------
  6202. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  6203. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  6204. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  6205. {
  6206. if (FTransferListHoverIndex != AHoverIndex)
  6207. {
  6208. FTransferListHoverIndex = AHoverIndex;
  6209. UpdateTransferLabel();
  6210. }
  6211. }
  6212. //---------------------------------------------------------------------------
  6213. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  6214. {
  6215. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  6216. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  6217. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  6218. {
  6219. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  6220. {
  6221. OpenDirectory(GetSide(osCurrent));
  6222. Message.Result = 1;
  6223. }
  6224. else
  6225. {
  6226. TForm::Dispatch(&Message);
  6227. }
  6228. }
  6229. else
  6230. {
  6231. TForm::Dispatch(&Message);
  6232. }
  6233. }
  6234. //---------------------------------------------------------------------------
  6235. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  6236. {
  6237. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  6238. if ((FIgnoreNextDialogChar != 0) &&
  6239. (toupper(Message.CharCode) == toupper(FIgnoreNextDialogChar)))
  6240. {
  6241. Message.Result = 1;
  6242. }
  6243. else
  6244. {
  6245. TForm::Dispatch(&Message);
  6246. }
  6247. FIgnoreNextDialogChar = 0;
  6248. }
  6249. //---------------------------------------------------------------------------
  6250. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  6251. {
  6252. // The four low-order bits are used internally by Windows
  6253. unsigned int Cmd = (Message.WParam & 0xFFF0);
  6254. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  6255. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  6256. // 61730 - restore thru double click - undocumented
  6257. // 61490 - maximize thru double click - undocumented
  6258. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  6259. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  6260. {
  6261. SysResizing(Cmd);
  6262. }
  6263. TForm::Dispatch(&Message);
  6264. }
  6265. //---------------------------------------------------------------------------
  6266. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  6267. {
  6268. // We were actually never able to make ENDSESSION_CRITICAL happen.
  6269. // Also there no point returning TRUE as we are not able to
  6270. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  6271. // Hence the process termination might be safer :)
  6272. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  6273. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  6274. {
  6275. Message.Result = FALSE;
  6276. }
  6277. else
  6278. {
  6279. Message.Result = TRUE;
  6280. }
  6281. // Do not call default handling as that triggers OnCloseQuery,
  6282. // where our implementation will popup confirmation dialogs, what we do not want,
  6283. // as per Vista guidelines:
  6284. // https://docs.microsoft.com/en-us/windows/desktop/shutdown/shutting-down
  6285. }
  6286. //---------------------------------------------------------------------------
  6287. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  6288. {
  6289. if (Message.EndSession && IsApplicationMinimized())
  6290. {
  6291. // WORKAROUND
  6292. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  6293. // when it receives WM_ENDSESSION,
  6294. // but that sometimes (particularly when application is minimized) cause crashes.
  6295. // Crash popups message that blocks log off.
  6296. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  6297. // so we call ExitProcess() immediately, not even trying to cleanup.
  6298. // It still causes beep, so there's likely some popup, but it does not block
  6299. // log off.
  6300. ExitProcess(0);
  6301. }
  6302. TForm::Dispatch(&Message);
  6303. }
  6304. #ifdef _DEBUG
  6305. //---------------------------------------------------------------------------
  6306. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  6307. {
  6308. TForm::Dispatch(&Message);
  6309. }
  6310. #endif
  6311. //---------------------------------------------------------------------------
  6312. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  6313. {
  6314. }
  6315. //---------------------------------------------------------------------------
  6316. void __fastcall TCustomScpExplorerForm::DoShow()
  6317. {
  6318. // only now are the controls resized finally, so the size constraints
  6319. // will not conflict with possibly very small window size
  6320. RestoreFormParams();
  6321. FixControlsPlacement();
  6322. if (Position == poDefaultPosOnly)
  6323. {
  6324. CutFormToDesktop(this);
  6325. }
  6326. TForm::DoShow();
  6327. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  6328. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  6329. if (Terminal == NULL)
  6330. {
  6331. StartingDisconnected();
  6332. }
  6333. UpdatePixelsPerInchMainWindowCounter();
  6334. FShowing = true;
  6335. }
  6336. //---------------------------------------------------------------------------
  6337. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  6338. {
  6339. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  6340. }
  6341. //---------------------------------------------------------------------------
  6342. void __fastcall TCustomScpExplorerForm::StartingDisconnected()
  6343. {
  6344. DoTerminalListChanged();
  6345. }
  6346. //---------------------------------------------------------------------------
  6347. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  6348. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  6349. TNotifyEvent OnBalloonClick, TObject * UserData)
  6350. {
  6351. bool Do;
  6352. UnicodeString Message;
  6353. if (E == NULL)
  6354. {
  6355. Message = Str;
  6356. Do = true;
  6357. }
  6358. else
  6359. {
  6360. Do = ExceptionMessage(E, Message);
  6361. }
  6362. if (Do && WinConfiguration->BalloonNotifications)
  6363. {
  6364. UnicodeString Title;
  6365. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  6366. {
  6367. Message = TrimLeft(Message);
  6368. }
  6369. else
  6370. {
  6371. Message = UnformatMessage(Message);
  6372. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  6373. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  6374. Title = LoadResourceString(Captions[Type]);
  6375. if (Terminal != NULL)
  6376. {
  6377. Title = FORMAT(L"%s - %s",
  6378. (TTerminalManager::Instance()->GetTerminalTitle(Terminal, true), Title));
  6379. }
  6380. }
  6381. if (Seconds == 0)
  6382. {
  6383. Seconds = WinConfiguration->NotificationsTimeout;
  6384. }
  6385. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  6386. }
  6387. }
  6388. //---------------------------------------------------------------------------
  6389. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  6390. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  6391. UnicodeString HelpKeyword, const TMessageParams * Params,
  6392. TTerminal * Terminal)
  6393. {
  6394. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  6395. (FOnFeedSynchronizeError != NULL)) &&
  6396. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  6397. {
  6398. if (FOnFeedSynchronizeError != NULL)
  6399. {
  6400. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  6401. }
  6402. else
  6403. {
  6404. DebugAssert(FErrorList != NULL);
  6405. TStringList * MoreMessagesCopy = NULL;
  6406. if (MoreMessages)
  6407. {
  6408. MoreMessagesCopy = new TStringList();
  6409. MoreMessagesCopy->Assign(MoreMessages);
  6410. }
  6411. FErrorList->AddObject(Message, MoreMessagesCopy);
  6412. }
  6413. PopupTrayBalloon(Terminal, Message, Type);
  6414. return ContinueAnswer(Answers);
  6415. }
  6416. else
  6417. {
  6418. bool UseBalloon = FTrayIcon->Visible;
  6419. if (UseBalloon)
  6420. {
  6421. PopupTrayBalloon(Terminal, Message, Type);
  6422. }
  6423. unsigned int Result;
  6424. try
  6425. {
  6426. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  6427. }
  6428. __finally
  6429. {
  6430. // cancel only balloon we popped up, otherwise we may cancel notification
  6431. // balloon that was there before the message dialog
  6432. // (such as "dd confirmation opt in balloon)
  6433. if (UseBalloon)
  6434. {
  6435. FTrayIcon->CancelBalloon();
  6436. }
  6437. }
  6438. return Result;
  6439. }
  6440. }
  6441. //---------------------------------------------------------------------------
  6442. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  6443. TTerminal * Terminal, Exception * E)
  6444. {
  6445. if (FTrayIcon->Visible)
  6446. {
  6447. PopupTrayBalloon(Terminal, L"", qtError, E);
  6448. }
  6449. // particularly prevent opening new session from jump list,
  6450. // while exception is shown
  6451. NonVisualDataModule->StartBusy();
  6452. try
  6453. {
  6454. ShowExtendedExceptionEx(Terminal, E);
  6455. }
  6456. __finally
  6457. {
  6458. NonVisualDataModule->EndBusy();
  6459. FTrayIcon->CancelBalloon();
  6460. }
  6461. }
  6462. //---------------------------------------------------------------------------
  6463. void __fastcall TCustomScpExplorerForm::TerminalReady()
  6464. {
  6465. // cannot rely on active page being page for active terminal,
  6466. // as it can happen that active page is the "new session" page
  6467. // (e.g. when reconnecting active terminal, while login dialog
  6468. // invoked from "new session" page is modal)
  6469. int ActiveTerminalIndex = TTerminalManager::Instance()->ActiveTerminalIndex;
  6470. UpdateSessionTab(SessionsPageControl->Pages[ActiveTerminalIndex]);
  6471. }
  6472. //---------------------------------------------------------------------------
  6473. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  6474. TTerminal * Terminal, Exception * E)
  6475. {
  6476. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  6477. if (!Terminal->Active)
  6478. {
  6479. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  6480. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  6481. {
  6482. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  6483. }
  6484. }
  6485. }
  6486. //---------------------------------------------------------------------------
  6487. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  6488. UnicodeString Message, TQueryType Type,
  6489. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  6490. {
  6491. if ((E == NULL) ||
  6492. ExceptionMessage(E, Message))
  6493. {
  6494. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  6495. if (Important)
  6496. {
  6497. Seconds *= 5;
  6498. }
  6499. UnicodeString NoteMessage(UnformatMessage(Message));
  6500. if (Terminal != NULL)
  6501. {
  6502. NoteMessage = FORMAT(L"%s: %s",
  6503. (TTerminalManager::Instance()->GetTerminalTitle(Terminal, true), NoteMessage));
  6504. }
  6505. if (WinConfiguration->BalloonNotifications)
  6506. {
  6507. AddNote(NoteMessage);
  6508. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  6509. }
  6510. else
  6511. {
  6512. FlashOnBackground();
  6513. PostNote(NoteMessage, Seconds, OnClick, UserData);
  6514. }
  6515. }
  6516. }
  6517. //---------------------------------------------------------------------------
  6518. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  6519. {
  6520. RestoreApp();
  6521. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  6522. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  6523. !NonVisualDataModule->Busy)
  6524. {
  6525. TTerminal * Terminal = TerminalNoteData->Terminal;
  6526. TTerminalManager::Instance()->ActiveTerminal = Terminal;
  6527. if (!ComponentVisible[fcQueueView])
  6528. {
  6529. ToggleQueueVisibility();
  6530. GoToQueue();
  6531. }
  6532. }
  6533. }
  6534. //---------------------------------------------------------------------------
  6535. void __fastcall TCustomScpExplorerForm::QueueEvent(TTerminal * ATerminal,
  6536. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  6537. {
  6538. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  6539. UnicodeString Message;
  6540. TNotifyEvent OnClick = NULL;
  6541. TObject * UserData = NULL;
  6542. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  6543. switch (Event)
  6544. {
  6545. case qeEmptyButMonitored:
  6546. if ((ATerminal != Terminal) || QueueInvisible)
  6547. {
  6548. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  6549. OnClick = QueueEmptyNoteClicked;
  6550. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  6551. TerminalNoteData->Terminal = ATerminal;
  6552. UserData = TerminalNoteData;
  6553. }
  6554. break;
  6555. case qeEmpty:
  6556. OperationComplete(ManagedTerminal->QueueOperationStart);
  6557. break;
  6558. case qePendingUserAction:
  6559. if ((ATerminal != Terminal) ||
  6560. (QueueInvisible && !IsQueueAutoPopup()))
  6561. {
  6562. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  6563. }
  6564. break;
  6565. default:
  6566. DebugFail();
  6567. }
  6568. if (!Message.IsEmpty())
  6569. {
  6570. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  6571. }
  6572. }
  6573. //---------------------------------------------------------------------------
  6574. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  6575. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  6576. {
  6577. if (FDDExtMapFile != NULL)
  6578. {
  6579. CloseHandle(FDDExtMapFile);
  6580. FDDExtMapFile = NULL;
  6581. }
  6582. if (WinConfiguration->DDFakeFile)
  6583. {
  6584. DDFakeFileInitDrag(FileList, Created);
  6585. }
  6586. }
  6587. //---------------------------------------------------------------------------
  6588. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  6589. {
  6590. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  6591. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  6592. {
  6593. FFakeFileDropTarget = FileName;
  6594. }
  6595. }
  6596. //---------------------------------------------------------------------------
  6597. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  6598. {
  6599. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  6600. if (!ForceDirectories(ApiPath(Result)))
  6601. {
  6602. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  6603. }
  6604. FileSetAttr(ApiPath(Result), faHidden);
  6605. return Result;
  6606. }
  6607. //---------------------------------------------------------------------------
  6608. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  6609. bool & Created)
  6610. {
  6611. FFakeFileDropTarget = UnicodeString();
  6612. FDragFakeDirectory = CreateFakeTransferDirectory();
  6613. FileList->AddItem(NULL, FDragFakeDirectory);
  6614. Created = true;
  6615. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  6616. {
  6617. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  6618. }
  6619. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  6620. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  6621. {
  6622. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  6623. TDragExtCommStruct* CommStruct;
  6624. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  6625. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  6626. DebugAssert(CommStruct != NULL);
  6627. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  6628. CommStruct->Dragging = true;
  6629. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  6630. LENOF(CommStruct->DropDest));
  6631. NULL_TERMINATE(CommStruct->DropDest);
  6632. UnmapViewOfFile(CommStruct);
  6633. }
  6634. }
  6635. //---------------------------------------------------------------------------
  6636. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  6637. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  6638. {
  6639. bool Result;
  6640. if (Sender == RemoteDirView)
  6641. {
  6642. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  6643. }
  6644. else
  6645. {
  6646. DebugAssert(Sender == RemoteDriveView);
  6647. TStrings * FileList = RemoteDriveView->DragFileList();
  6648. try
  6649. {
  6650. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  6651. }
  6652. __finally
  6653. {
  6654. delete FileList;
  6655. }
  6656. }
  6657. if (FDDTargetControl == RemoteDriveView)
  6658. {
  6659. RemoteDriveView->UpdateDropTarget();
  6660. }
  6661. // foRemoteMove happens when file/dir is dragged within the remote tree view
  6662. // or from tree view to dir view.
  6663. // foMove happens when file/dir is dragged from remote tree view outside of
  6664. // application via dragex
  6665. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  6666. (DropSourceControl == RemoteDriveView))
  6667. {
  6668. RemoteDriveView->UpdateDropSource();
  6669. }
  6670. return Result;
  6671. }
  6672. //---------------------------------------------------------------------------
  6673. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  6674. {
  6675. // This also handles drops of remote files to queue.
  6676. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  6677. SAFE_DESTROY(FDDFileList);
  6678. if (!FFakeFileDropTarget.IsEmpty())
  6679. {
  6680. RemoveDir(ApiPath(FFakeFileDropTarget));
  6681. }
  6682. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  6683. {
  6684. try
  6685. {
  6686. TDragResult DDResult = (Sender == RemoteDirView) ?
  6687. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  6688. // Focus is moved to the target application,
  6689. // but as we are going to present the UI, we need to steal the focus back.
  6690. // This most likely won't work though (windows does not allow application
  6691. // to steal focus most of the time)
  6692. Application->BringToFront();
  6693. // On older version of Windows we never got drMove here, see also comment below.
  6694. // On Windows 10, we get the "move".
  6695. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  6696. {
  6697. UnicodeString TargetDirectory;
  6698. TFileOperation Operation;
  6699. // drInvalid may mean drMove, see comment below
  6700. switch (DDResult)
  6701. {
  6702. case drCopy:
  6703. Operation = foCopy;
  6704. break;
  6705. case drMove:
  6706. Operation = foMove;
  6707. break;
  6708. default:
  6709. DebugFail();
  6710. case drInvalid:
  6711. // prefer "copy" for safety
  6712. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  6713. break;
  6714. }
  6715. TTransferOperationParam Param;
  6716. UnicodeString CounterName;
  6717. bool ForceQueue;
  6718. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  6719. {
  6720. // we get drInvalid both if d&d was intercepted by ddext,
  6721. // and when users drops on no-drop location.
  6722. // we tell the difference by existence of response from ddext,
  6723. // so we ignore absence of response in this case
  6724. if (DDResult != drInvalid)
  6725. {
  6726. // here we know that the extension is installed,
  6727. // as it is checked as soon as drag&drop starts from
  6728. // RemoteFileControlDDCreateDragFileList
  6729. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  6730. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  6731. {
  6732. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  6733. }
  6734. else
  6735. {
  6736. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  6737. }
  6738. }
  6739. }
  6740. else
  6741. {
  6742. // download using fake file
  6743. Param.Temp = false;
  6744. Param.DragDrop = true;
  6745. if (ForceQueue)
  6746. {
  6747. Param.Queue = asOn;
  6748. }
  6749. if (Sender == RemoteDirView)
  6750. {
  6751. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  6752. }
  6753. if (RemoteFileControlFileOperation(Sender, Operation,
  6754. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  6755. {
  6756. Configuration->Usage->Inc(CounterName);
  6757. }
  6758. }
  6759. }
  6760. }
  6761. __finally
  6762. {
  6763. CloseHandle(FDDExtMapFile);
  6764. FDDExtMapFile = NULL;
  6765. delete FDragFakeMonitors;
  6766. FDragFakeMonitors = NULL;
  6767. RemoveDir(ApiPath(FDragFakeDirectory));
  6768. FDragFakeDirectory = L"";
  6769. FFakeFileDropTarget = UnicodeString();
  6770. }
  6771. }
  6772. if (FDragDropSshTerminate.get() != NULL)
  6773. {
  6774. FDragDropSshTerminate->Rethrow();
  6775. }
  6776. }
  6777. //---------------------------------------------------------------------------
  6778. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  6779. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  6780. {
  6781. // Remember drop effect so we know (when user drops files), if we copy or move
  6782. FLastDropEffect = dwEffect;
  6783. }
  6784. //---------------------------------------------------------------------------
  6785. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  6786. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  6787. {
  6788. bool Result;
  6789. if (FDDTargetControl == QueueView3)
  6790. {
  6791. Directory = DefaultDownloadTargetDirectory();
  6792. Result = true;
  6793. CounterName = L"DownloadsDragDropQueue";
  6794. ForceQueue = true;
  6795. }
  6796. else if (!FFakeFileDropTarget.IsEmpty())
  6797. {
  6798. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  6799. Result = true;
  6800. ForceQueue = false;
  6801. CounterName = L"DownloadsDragDropFakeFile";
  6802. }
  6803. else
  6804. {
  6805. ForceQueue = false;
  6806. Enabled = false;
  6807. try
  6808. {
  6809. int Timer = 0;
  6810. Result = false;
  6811. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  6812. {
  6813. {
  6814. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  6815. TDragExtCommStruct* CommStruct;
  6816. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  6817. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  6818. DebugAssert(CommStruct != NULL);
  6819. Result = !CommStruct->Dragging;
  6820. if (Result)
  6821. {
  6822. Directory = ExtractFilePath(CommStruct->DropDest);
  6823. CounterName = L"DownloadsDragDropExternalExt";
  6824. }
  6825. UnmapViewOfFile(CommStruct);
  6826. }
  6827. if (!Result)
  6828. {
  6829. Sleep(50);
  6830. Timer += 50;
  6831. Application->ProcessMessages();
  6832. }
  6833. }
  6834. }
  6835. __finally
  6836. {
  6837. Enabled = true;
  6838. }
  6839. }
  6840. return Result;
  6841. }
  6842. //---------------------------------------------------------------------------
  6843. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  6844. const UnicodeString TempDir, int SecDelay)
  6845. {
  6846. TDateTime Alarm = Now() + (double)((double)SecDelay*OneMillisecond);
  6847. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  6848. if (FDelayedDeletionTimer == NULL)
  6849. {
  6850. DebugAssert(HandleAllocated());
  6851. FDelayedDeletionTimer = new TTimer(this);
  6852. FDelayedDeletionTimer->Interval = 10000;
  6853. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  6854. }
  6855. else
  6856. {
  6857. FDelayedDeletionTimer->Enabled = true;
  6858. }
  6859. }
  6860. //---------------------------------------------------------------------------
  6861. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  6862. {
  6863. DebugAssert(FDelayedDeletionList != NULL);
  6864. TDateTime N = Now();
  6865. TDateTime Alert;
  6866. UnicodeString Directory;
  6867. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  6868. {
  6869. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  6870. if ((N >= Alert) || (Sender == NULL))
  6871. {
  6872. Directory = FDelayedDeletionList->Strings[Index];
  6873. if (DeleteDirectory(ExcludeTrailingBackslash(Directory)))
  6874. {
  6875. FDelayedDeletionList->Delete(Index);
  6876. }
  6877. }
  6878. }
  6879. if (FDelayedDeletionList->Count == 0)
  6880. {
  6881. FDelayedDeletionTimer->Enabled = false;
  6882. }
  6883. }
  6884. //---------------------------------------------------------------------------
  6885. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  6886. {
  6887. if (IsFileControl(FDDTargetControl, osRemote) ||
  6888. (FDDTargetControl == SessionsPageControl))
  6889. {
  6890. TTerminal * TargetTerminal = NULL;
  6891. TFileOperation Operation = foNone;
  6892. if (FDDTargetControl == SessionsPageControl)
  6893. {
  6894. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  6895. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  6896. // do not allow dropping on the "+" tab
  6897. TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  6898. if (TargetTerminal != NULL)
  6899. {
  6900. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  6901. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  6902. {
  6903. Operation = foRemoteMove;
  6904. }
  6905. else
  6906. {
  6907. Operation = foRemoteCopy;
  6908. }
  6909. }
  6910. }
  6911. else
  6912. {
  6913. if (FLastDropEffect == DROPEFFECT_MOVE)
  6914. {
  6915. Operation = foRemoteMove;
  6916. }
  6917. else if (FLastDropEffect == DROPEFFECT_COPY)
  6918. {
  6919. Operation = foRemoteCopy;
  6920. }
  6921. }
  6922. if (Operation != foNone)
  6923. {
  6924. RemoteFileControlFileOperation(DropSourceControl,
  6925. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  6926. }
  6927. // abort drag&drop
  6928. Abort();
  6929. }
  6930. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  6931. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  6932. (FDDTargetControl != QueueView3))
  6933. {
  6934. DebugAssert(!FDragTempDir.IsEmpty());
  6935. TTransferType Type;
  6936. UnicodeString TempDir = FDragTempDir;
  6937. // We clear FDragTempDir before calling
  6938. // just in case it fail (raises exception)
  6939. FDragTempDir = L"";
  6940. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  6941. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  6942. // empty directory parameter means temp directory -> don't display it!
  6943. UnicodeString TargetDir = L"";
  6944. int Options = 0;
  6945. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  6946. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  6947. {
  6948. Abort();
  6949. }
  6950. // TargetDir is set when dropped on local file control
  6951. // (this was workaround for legacy dirview event handling, now it should be
  6952. // made prettier)
  6953. if (TargetDir.IsEmpty())
  6954. {
  6955. TargetDir = TempDir;
  6956. if (ForceDirectories(ApiPath(TargetDir)))
  6957. {
  6958. DebugAssert(Terminal && !TargetDir.IsEmpty());
  6959. FPendingTempSpaceWarn = true;
  6960. try
  6961. {
  6962. FDragDropOperation = true;
  6963. int Params = cpTemporary |
  6964. (Type == ttMove ? cpDelete : 0);
  6965. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  6966. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  6967. }
  6968. __finally
  6969. {
  6970. FDragDropOperation = false;
  6971. FPendingTempSpaceWarn = false;
  6972. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  6973. }
  6974. }
  6975. else
  6976. {
  6977. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  6978. }
  6979. }
  6980. }
  6981. }
  6982. //---------------------------------------------------------------------------
  6983. void __fastcall TCustomScpExplorerForm::DDDownload(
  6984. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params)
  6985. {
  6986. TAutoBatch AutoBatch(this);
  6987. UpdateCopyParamCounters(*CopyParam);
  6988. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  6989. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  6990. {
  6991. RemoteDriveView->UpdateDropSource();
  6992. }
  6993. }
  6994. //---------------------------------------------------------------------------
  6995. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  6996. {
  6997. public:
  6998. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  6999. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7000. {
  7001. }
  7002. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7003. {
  7004. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7005. TDataObjectFilesEx::AllowData(FormatEtc);
  7006. }
  7007. };
  7008. //---------------------------------------------------------------------------
  7009. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7010. TObject * Sender, TDataObject *& DataObject)
  7011. {
  7012. if (FDDExtMapFile != NULL)
  7013. {
  7014. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7015. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7016. {
  7017. Abort();
  7018. }
  7019. if (FileList->Count > 0)
  7020. {
  7021. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7022. if (!FilesObject->IsValid(true, true))
  7023. {
  7024. FilesObject->_Release();
  7025. }
  7026. else
  7027. {
  7028. DataObject = FilesObject;
  7029. }
  7030. }
  7031. }
  7032. }
  7033. //---------------------------------------------------------------------------
  7034. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7035. {
  7036. DebugFail();
  7037. }
  7038. //---------------------------------------------------------------------------
  7039. void __fastcall TCustomScpExplorerForm::GoToTree()
  7040. {
  7041. ComponentVisible[fcRemoteTree] = true;
  7042. RemoteDriveView->SetFocus();
  7043. }
  7044. //---------------------------------------------------------------------------
  7045. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7046. TPanelExport Export)
  7047. {
  7048. TCustomDirView * DirView = this->DirView(Side);
  7049. std::unique_ptr<TStrings> ExportData(new TStringList());
  7050. switch (Export)
  7051. {
  7052. case pePath:
  7053. ExportData->Add(DirView->PathName);
  7054. break;
  7055. case peFileList:
  7056. case peFullFileList:
  7057. {
  7058. bool FullPath = (Export == peFullFileList);
  7059. DirView->CreateFileList(false, FullPath, ExportData.get());
  7060. for (int Index = 0; Index < ExportData->Count; Index++)
  7061. {
  7062. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7063. {
  7064. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7065. }
  7066. }
  7067. }
  7068. break;
  7069. default:
  7070. DebugFail();
  7071. }
  7072. return ExportData.release();
  7073. }
  7074. //---------------------------------------------------------------------------
  7075. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7076. TPanelExport Export, TPanelExportDestination Destination)
  7077. {
  7078. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7079. PanelExportStore(Side, Export, Destination, ExportData.get());
  7080. }
  7081. //---------------------------------------------------------------------------
  7082. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7083. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7084. TStrings * ExportData)
  7085. {
  7086. if (Destination == pedClipboard)
  7087. {
  7088. TInstantOperationVisualizer Visualizer;
  7089. CopyToClipboard(ExportData);
  7090. }
  7091. else
  7092. {
  7093. DebugFail();
  7094. }
  7095. }
  7096. //---------------------------------------------------------------------------
  7097. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  7098. {
  7099. TCustomDirView * DirView = this->DirView(Side);
  7100. UnicodeString Mask = DirView->Mask;
  7101. if (DoFilterMaskDialog(DirView, Mask))
  7102. {
  7103. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  7104. Configuration->Usage->Inc(L"Filters");
  7105. }
  7106. }
  7107. //---------------------------------------------------------------------------
  7108. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  7109. {
  7110. return FQueueController->DefaultOperation();
  7111. }
  7112. //---------------------------------------------------------------------------
  7113. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  7114. TQueueOperation Operation, void ** Param)
  7115. {
  7116. switch (Operation)
  7117. {
  7118. case qoPreferences:
  7119. return true;
  7120. case qoGoTo:
  7121. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  7122. case qoOnceEmpty:
  7123. return !FQueueController->Empty;
  7124. default:
  7125. return FQueueController->AllowOperation(Operation, Param);
  7126. }
  7127. }
  7128. //---------------------------------------------------------------------------
  7129. void __fastcall TCustomScpExplorerForm::GoToQueue()
  7130. {
  7131. if (DebugAlwaysTrue(QueueView3->Visible))
  7132. {
  7133. QueueView3->SetFocus();
  7134. }
  7135. }
  7136. //---------------------------------------------------------------------------
  7137. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  7138. TQueueOperation Operation, void * Param)
  7139. {
  7140. if (Operation == qoGoTo)
  7141. {
  7142. GoToQueue();
  7143. }
  7144. else if (Operation == qoPreferences)
  7145. {
  7146. PreferencesDialog(pmQueue);
  7147. }
  7148. else
  7149. {
  7150. FQueueController->ExecuteOperation(Operation, Param);
  7151. }
  7152. }
  7153. //---------------------------------------------------------------------------
  7154. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  7155. {
  7156. return (Queue != NULL) && Queue->Enabled;
  7157. }
  7158. //---------------------------------------------------------------------------
  7159. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  7160. {
  7161. DebugAssert(Queue != NULL);
  7162. if (Queue != NULL)
  7163. {
  7164. Queue->Enabled = !Queue->Enabled;
  7165. }
  7166. }
  7167. //---------------------------------------------------------------------------
  7168. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  7169. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  7170. {
  7171. FQueueActedItem = QueueView3->ItemFocused;
  7172. }
  7173. //---------------------------------------------------------------------------
  7174. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  7175. {
  7176. return TopDock->Height + QueueSplitter->Height;
  7177. }
  7178. //---------------------------------------------------------------------------
  7179. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  7180. TObject * /*Sender*/, int & NewSize, bool & Accept)
  7181. {
  7182. // when queue is hidden by double-clicking splitter, stray attempt to
  7183. // resize the panel with strange value arrives, make sure it is ignored
  7184. if (ComponentVisible[fcQueueView])
  7185. {
  7186. int HeightLimit = ClientHeight - GetStaticComponentsHeight() -
  7187. RemotePanel->Constraints->MinHeight;
  7188. if (NewSize > HeightLimit)
  7189. {
  7190. NewSize = HeightLimit;
  7191. }
  7192. }
  7193. else
  7194. {
  7195. Accept = false;
  7196. }
  7197. }
  7198. //---------------------------------------------------------------------------
  7199. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  7200. TDragObject *& /*DragObject*/)
  7201. {
  7202. FQueueActedItem = QueueView3->ItemFocused;
  7203. }
  7204. //---------------------------------------------------------------------------
  7205. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  7206. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  7207. {
  7208. Accept = true;
  7209. if (Source == QueueView3)
  7210. {
  7211. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  7212. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  7213. if (Accept)
  7214. {
  7215. TQueueItemProxy * QueueItem;
  7216. TQueueItemProxy * DestQueueItem;
  7217. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  7218. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  7219. Accept = (QueueItem != DestQueueItem) &&
  7220. (QueueItem->Status == TQueueItem::qsPending) &&
  7221. (DestQueueItem->Status == TQueueItem::qsPending);
  7222. }
  7223. }
  7224. }
  7225. //---------------------------------------------------------------------------
  7226. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  7227. TObject * /*Source*/, int /*X*/, int /*Y*/)
  7228. {
  7229. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  7230. {
  7231. TQueueItemProxy * QueueItem;
  7232. TQueueItemProxy * DestQueueItem;
  7233. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  7234. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  7235. QueueItem->Move(DestQueueItem);
  7236. }
  7237. }
  7238. //---------------------------------------------------------------------------
  7239. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  7240. {
  7241. if ((QueueView3->ItemFocused == NULL) &&
  7242. (QueueView3->Items->Count > 0))
  7243. {
  7244. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  7245. }
  7246. QueueLabelUpdateStatus();
  7247. }
  7248. //---------------------------------------------------------------------------
  7249. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  7250. {
  7251. QueueLabelUpdateStatus();
  7252. }
  7253. //---------------------------------------------------------------------------
  7254. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  7255. {
  7256. QueueLabel->UpdateStatus();
  7257. }
  7258. //---------------------------------------------------------------------------
  7259. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  7260. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  7261. {
  7262. if (Selected)
  7263. {
  7264. NonVisualDataModule->UpdateNonVisibleActions();
  7265. }
  7266. }
  7267. //---------------------------------------------------------------------------
  7268. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  7269. {
  7270. TDragDropFilesEx * Result = NULL;
  7271. if (Sender == SessionsPageControl)
  7272. {
  7273. Result = FSessionsDragDropFilesEx;
  7274. }
  7275. else if (Sender == QueueView3)
  7276. {
  7277. Result = FQueueDragDropFilesEx;
  7278. }
  7279. else
  7280. {
  7281. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  7282. if (DirView != NULL)
  7283. {
  7284. Result = DirView->DragDropFilesEx;
  7285. }
  7286. else
  7287. {
  7288. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  7289. if (DriveView != NULL)
  7290. {
  7291. Result = DriveView->DragDropFilesEx;
  7292. }
  7293. }
  7294. }
  7295. DebugAssert(Result != NULL);
  7296. return Result;
  7297. }
  7298. //---------------------------------------------------------------------------
  7299. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  7300. {
  7301. return (DView->SelCount == DView->FilesCount);
  7302. }
  7303. //---------------------------------------------------------------------------
  7304. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  7305. {
  7306. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  7307. }
  7308. //---------------------------------------------------------------------------
  7309. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  7310. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  7311. {
  7312. TFileOperation Operation;
  7313. switch (Effect)
  7314. {
  7315. case DROPEFFECT_MOVE:
  7316. Operation = foMove;
  7317. break;
  7318. case DROPEFFECT_COPY:
  7319. // occures on WinXP (reported by user)
  7320. default:
  7321. Operation = foCopy;
  7322. break;
  7323. };
  7324. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  7325. // see a comment in TUnixDirView::PerformItemDragDropOperation
  7326. if (DragDropFilesEx->FileList->Count > 0)
  7327. {
  7328. TStrings * FileList = new TStringList();
  7329. try
  7330. {
  7331. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  7332. {
  7333. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  7334. }
  7335. FDragDropOperation = true;
  7336. TTransferOperationParam Param;
  7337. Param.TargetDirectory = TargetPath;
  7338. // upload, no temp dirs
  7339. Param.Temp = false;
  7340. Param.DragDrop = DragDrop;
  7341. Param.Options =
  7342. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  7343. if (ForceQueue)
  7344. {
  7345. Param.Queue = asOn;
  7346. }
  7347. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  7348. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  7349. {
  7350. if (IsFileControl(DropSourceControl, osLocal))
  7351. {
  7352. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  7353. }
  7354. else
  7355. {
  7356. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  7357. }
  7358. }
  7359. }
  7360. __finally
  7361. {
  7362. FDragDropOperation = false;
  7363. delete FileList;
  7364. }
  7365. }
  7366. }
  7367. //---------------------------------------------------------------------------
  7368. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  7369. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  7370. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  7371. {
  7372. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  7373. }
  7374. //---------------------------------------------------------------------------
  7375. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  7376. TObject * Sender, int grfKeyState, int & dwEffect)
  7377. {
  7378. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  7379. if ((dwEffect != DROPEFFECT_None) &&
  7380. IsFileControl(DropSourceControl, osRemote))
  7381. {
  7382. // do not allow drop on remote panel (on free space, still allow drop on directories)
  7383. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  7384. (RemoteDirView->DropTarget == NULL))
  7385. {
  7386. dwEffect = DROPEFFECT_None;
  7387. }
  7388. else
  7389. {
  7390. if (dwEffect == DROPEFFECT_Copy)
  7391. {
  7392. bool MoveCapable = FTerminal->IsCapable[fcRemoteMove];
  7393. // currently we support copying always (at least via temporary directory);
  7394. // remove associated checks once this all proves stable and working
  7395. bool CopyCapable = true;
  7396. // if we do not support neither of operations, there's no discussion
  7397. if (!MoveCapable && !CopyCapable)
  7398. {
  7399. dwEffect = DROPEFFECT_None;
  7400. }
  7401. else
  7402. {
  7403. // The default effect inside remote panel is move,
  7404. // unless we do not support it, but support copy
  7405. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  7406. {
  7407. dwEffect = MoveCapable ? DROPEFFECT_Move : DROPEFFECT_Copy;
  7408. }
  7409. else
  7410. {
  7411. // with ctrl-down, we want copy unless it is not supported
  7412. dwEffect = CopyCapable ? DROPEFFECT_Copy : DROPEFFECT_None;
  7413. }
  7414. }
  7415. }
  7416. }
  7417. }
  7418. }
  7419. //---------------------------------------------------------------------------
  7420. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  7421. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  7422. {
  7423. if (FDDTotalSize >= 0)
  7424. {
  7425. if (File->IsDirectory)
  7426. {
  7427. FDDTotalSize = -1;
  7428. }
  7429. else
  7430. {
  7431. FDDTotalSize += File->Size;
  7432. }
  7433. }
  7434. DebugAssert(!FDragTempDir.IsEmpty());
  7435. // TODO: this is quite ineffective
  7436. // TODO: what if invalid character replacement is disabled?
  7437. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  7438. UnicodeString TransferFileName;
  7439. if (Sender == RemoteDriveView)
  7440. {
  7441. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  7442. }
  7443. else
  7444. {
  7445. TransferFileName = File->FileName;
  7446. }
  7447. FDDFileList->AddObject(TransferFileName, File);
  7448. }
  7449. //---------------------------------------------------------------------------
  7450. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  7451. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  7452. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  7453. {
  7454. // sometimes we do not get DDEnd so the list is not released
  7455. SAFE_DESTROY(FDDFileList);
  7456. FDDFileList = new TStringList();
  7457. FDragTempDir = WinConfiguration->TemporaryDir();
  7458. FDDTotalSize = 0;
  7459. FDragDropSshTerminate.reset(NULL);
  7460. }
  7461. //---------------------------------------------------------------------------
  7462. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  7463. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  7464. HRESULT & Result)
  7465. {
  7466. if (Result == DRAGDROP_S_DROP)
  7467. {
  7468. try
  7469. {
  7470. GlobalDragImageList->HideDragImage();
  7471. try
  7472. {
  7473. RemoteFileControlDDTargetDrop();
  7474. }
  7475. catch(ESshTerminate & E)
  7476. {
  7477. FDragDropSshTerminate.reset(E.Clone());
  7478. }
  7479. }
  7480. catch (Exception &E)
  7481. {
  7482. // If downloading fails we need to cancel drag&drop, otherwise
  7483. // Explorer shows error
  7484. // But by the way exception probably never reach this point as
  7485. // it's catched on way.
  7486. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  7487. Result = DRAGDROP_S_CANCEL;
  7488. ShowExtendedException(Terminal, &E);
  7489. }
  7490. }
  7491. }
  7492. //---------------------------------------------------------------------------
  7493. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  7494. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  7495. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  7496. {
  7497. TFileMasks::TParams MaskParams;
  7498. MaskParams.Size = Size;
  7499. MaskParams.Modification = Modification;
  7500. // this does not re-parse the mask if it is the same as the last time
  7501. FDirViewMatchMask = Masks;
  7502. bool ImplicitMatch;
  7503. Matches =
  7504. // RecurseInclude parameter has no effect as the Path is empty
  7505. FDirViewMatchMask.Matches(FileName, Directory, UnicodeString(L""), &MaskParams, true, ImplicitMatch) &&
  7506. (AllowImplicitMatches || !ImplicitMatch);
  7507. }
  7508. //---------------------------------------------------------------------------
  7509. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  7510. TObject * Sender, TListItem * Item, WORD & Indexes)
  7511. {
  7512. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  7513. UnicodeString Ext;
  7514. if (DirView == RemoteDirView)
  7515. {
  7516. Ext = UnixExtractFileExt(DirView->ItemFileName(Item));
  7517. }
  7518. else
  7519. {
  7520. Ext = ExtractFileExt(DirView->ItemFileName(Item));
  7521. }
  7522. if (SameText(Ext, Configuration->PartialExt))
  7523. {
  7524. Indexes |= oiPartial;
  7525. }
  7526. }
  7527. //---------------------------------------------------------------------------
  7528. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  7529. {
  7530. return
  7531. DirViewEnabled(osCurrent) &&
  7532. DirView(osCurrent)->CanPasteFromClipBoard();
  7533. }
  7534. //---------------------------------------------------------------------------
  7535. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  7536. {
  7537. bool Result = false;
  7538. if (CanPasteToDirViewFromClipBoard())
  7539. {
  7540. Result = true;
  7541. }
  7542. else
  7543. {
  7544. UnicodeString ClipboardText;
  7545. if (NonEmptyTextFromClipboard(ClipboardText))
  7546. {
  7547. if (StoredSessions->IsUrl(ClipboardText))
  7548. {
  7549. Result = true;
  7550. }
  7551. else
  7552. {
  7553. Result = DirViewEnabled(osCurrent);
  7554. }
  7555. }
  7556. }
  7557. return Result;
  7558. }
  7559. //---------------------------------------------------------------------------
  7560. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  7561. {
  7562. if (DoesClipboardContainOurFiles())
  7563. {
  7564. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  7565. {
  7566. TTerminalManager * Manager = TTerminalManager::Instance();
  7567. TTerminal * TergetTerminal = Manager->ActiveTerminal;
  7568. Manager->ActiveTerminal = FClipboardTerminal;
  7569. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TergetTerminal);
  7570. }
  7571. }
  7572. else if (CanPasteToDirViewFromClipBoard())
  7573. {
  7574. DirView(osCurrent)->PasteFromClipBoard();
  7575. }
  7576. else
  7577. {
  7578. UnicodeString ClipboardText;
  7579. if (NonEmptyTextFromClipboard(ClipboardText))
  7580. {
  7581. if (StoredSessions->IsUrl(ClipboardText))
  7582. {
  7583. NewSession(false, ClipboardText);
  7584. }
  7585. else
  7586. {
  7587. DirView(osCurrent)->Path = ClipboardText;
  7588. }
  7589. }
  7590. }
  7591. }
  7592. //---------------------------------------------------------------------------
  7593. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  7594. {
  7595. // TBD
  7596. }
  7597. //---------------------------------------------------------------------------
  7598. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  7599. {
  7600. TCustomDirView * ADirView = DirView(Side);
  7601. ADirView->SelectAll(Mode);
  7602. ADirView->SetFocus();
  7603. }
  7604. //---------------------------------------------------------------------------
  7605. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  7606. {
  7607. TCustomDirView * ADirView = DirView(Side);
  7608. TFileFilter Filter;
  7609. DefaultFileFilter(Filter);
  7610. if (DoSelectMaskDialog(ADirView, Select, Filter))
  7611. {
  7612. Configuration->Usage->Inc(L"MaskSelections");
  7613. ADirView->SelectFiles(Filter, Select);
  7614. ADirView->SetFocus();
  7615. }
  7616. }
  7617. //---------------------------------------------------------------------------
  7618. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  7619. {
  7620. TCustomDirView * ADirView = DirView(Side);
  7621. ADirView->RestoreSelectedNames();
  7622. ADirView->SetFocus();
  7623. }
  7624. //---------------------------------------------------------------------------
  7625. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  7626. {
  7627. TCustomDirView * CurrentDirView = DirView(osCurrent);
  7628. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  7629. {
  7630. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  7631. UnicodeString Ext;
  7632. if (GetSide(osCurrent) == osRemote)
  7633. {
  7634. Ext = UnixExtractFileExt(FileName);
  7635. }
  7636. else
  7637. {
  7638. Ext = ExtractFileExt(FileName);
  7639. }
  7640. if (Ext.IsEmpty())
  7641. {
  7642. Ext = L".";
  7643. }
  7644. TFileFilter Filter;
  7645. Filter.Masks = FORMAT(L"*%s", (Ext));
  7646. Filter.Directories = false;
  7647. CurrentDirView->SelectFiles(Filter, Select);
  7648. }
  7649. }
  7650. //---------------------------------------------------------------------------
  7651. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  7652. const TStatusFileInfo & FileInfo, TOperationSide Side)
  7653. {
  7654. UnicodeString Result;
  7655. if ((Side == osRemote) && (Terminal == NULL))
  7656. {
  7657. // noop
  7658. }
  7659. else
  7660. {
  7661. Result =
  7662. FMTLOAD(FILE_INFO_FORMAT,
  7663. (FormatBytes(FileInfo.SelectedSize),
  7664. FormatBytes(FileInfo.FilesSize),
  7665. FormatNumber(FileInfo.SelectedCount),
  7666. FormatNumber(FileInfo.FilesCount)));
  7667. }
  7668. return Result;
  7669. }
  7670. //---------------------------------------------------------------------------
  7671. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  7672. TTBXStatusPanel * Panel, TOperationSide Side)
  7673. {
  7674. if (Panel->Index == 1)
  7675. {
  7676. ToggleShowHiddenFiles();
  7677. }
  7678. else if (Panel->Index == 2)
  7679. {
  7680. Filter(Side);
  7681. }
  7682. }
  7683. //---------------------------------------------------------------------------
  7684. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  7685. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  7686. {
  7687. DebugAssert(!StatusBar->SimplePanel);
  7688. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  7689. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  7690. }
  7691. //---------------------------------------------------------------------------
  7692. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  7693. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  7694. {
  7695. DebugAssert(StatusBar->Panels->Count >= 3);
  7696. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  7697. if (FileInfo.HiddenCount > 0)
  7698. {
  7699. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  7700. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  7701. }
  7702. else
  7703. {
  7704. HiddenFilesPanel->ViewPriority = 0;
  7705. // not really necessary, just to cleanup no-longer-valid data
  7706. HiddenFilesPanel->Caption = L"";
  7707. }
  7708. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  7709. if (FileInfo.FilteredCount > 0)
  7710. {
  7711. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  7712. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  7713. }
  7714. else
  7715. {
  7716. FilteredFilesPanel->ViewPriority = 0;
  7717. // not really necessary, just to cleanup no-longer-valid data
  7718. FilteredFilesPanel->Caption = L"";
  7719. }
  7720. }
  7721. //---------------------------------------------------------------------------
  7722. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  7723. TObject * /*Sender*/)
  7724. {
  7725. if (RemoteDirView->Enabled)
  7726. {
  7727. RemoteDirView->SetFocus();
  7728. }
  7729. }
  7730. //---------------------------------------------------------------------------
  7731. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  7732. {
  7733. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  7734. switch (Config.Show)
  7735. {
  7736. case qvShow:
  7737. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  7738. {
  7739. Config.Show = qvHide;
  7740. }
  7741. else
  7742. {
  7743. Config.Show = Config.LastHideShow;
  7744. }
  7745. break;
  7746. case qvHideWhenEmpty:
  7747. if (ComponentVisible[fcQueueView])
  7748. {
  7749. Config.Show = qvHide;
  7750. }
  7751. else
  7752. {
  7753. Config.LastHideShow = Config.Show;
  7754. Config.Show = qvShow;
  7755. }
  7756. break;
  7757. case qvHide:
  7758. Config.LastHideShow = Config.Show;
  7759. Config.Show = qvShow;
  7760. break;
  7761. }
  7762. WinConfiguration->QueueView = Config;
  7763. }
  7764. //---------------------------------------------------------------------------
  7765. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  7766. {
  7767. UnicodeString Result;
  7768. if (FTerminal != NULL)
  7769. {
  7770. switch (WinConfiguration->PathInCaption)
  7771. {
  7772. case picShort:
  7773. Result = TTerminalManager::Instance()->GetTerminalShortPath(FTerminal);
  7774. break;
  7775. case picFull:
  7776. Result = FTerminal->CurrentDirectory;
  7777. break;
  7778. }
  7779. }
  7780. return Result;
  7781. }
  7782. //---------------------------------------------------------------------------
  7783. void __fastcall TCustomScpExplorerForm::UpdateControls()
  7784. {
  7785. TTerminalManager::Instance()->UpdateAppTitle();
  7786. // WORAKRDOUND: Disabling list view when it is not showing yet does not set its
  7787. // background to gray on Windows 7 (works on Windows 10).
  7788. // See also EnableControl
  7789. if (Showing)
  7790. {
  7791. bool HasTerminal = (Terminal != NULL) && Terminal->Active;
  7792. if (HasTerminal)
  7793. {
  7794. // Update path when it changes
  7795. if ((SessionsPageControl->ActivePage != NULL) && (GetSessionTabTerminal(SessionsPageControl->ActivePage) == Terminal))
  7796. {
  7797. UpdateSessionTab(SessionsPageControl->ActivePage);
  7798. }
  7799. if (!RemoteDirView->Enabled)
  7800. {
  7801. RemoteDirView->Enabled = true;
  7802. if (FRemoteDirViewWasFocused)
  7803. {
  7804. ActiveControl = RemoteDirView;
  7805. }
  7806. }
  7807. RemoteDriveView->Enabled = true;
  7808. RemoteDirView->Color = (FSessionColor != 0 ? FSessionColor : clWindow);
  7809. RemoteDriveView->Color = RemoteDirView->Color;
  7810. }
  7811. else
  7812. {
  7813. if (RemoteDirView->Enabled)
  7814. {
  7815. // This is first called when the form is being constructed
  7816. // (not anymore due to Showing test above)
  7817. // but the false is overriden in the constructor later.
  7818. // An even later in TScpCommanderForm::DoShow()
  7819. FRemoteDirViewWasFocused = (ActiveControl == RemoteDirView);
  7820. EnableControl(RemoteDirView, false);
  7821. }
  7822. EnableControl(RemoteDriveView, false);
  7823. }
  7824. EnableControl(QueueView3, HasTerminal && Terminal->IsCapable[fsBackgroundTransfers]);
  7825. QueueLabelUpdateStatus();
  7826. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal;
  7827. }
  7828. }
  7829. //---------------------------------------------------------------------------
  7830. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  7831. {
  7832. UpdateControls();
  7833. }
  7834. //---------------------------------------------------------------------------
  7835. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  7836. TObject * Sender)
  7837. {
  7838. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  7839. DebugAssert(DirView != NULL);
  7840. DoDirViewLoaded(DirView);
  7841. TransferPresetAutoSelect();
  7842. }
  7843. //---------------------------------------------------------------------------
  7844. void __fastcall TCustomScpExplorerForm::StartUpdates()
  7845. {
  7846. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  7847. // first run after installation
  7848. if (double(Updates.LastCheck) == 0)
  7849. {
  7850. // make sure next time there will be an update (if enabled)
  7851. Updates.LastCheck = TDateTime(1);
  7852. WinConfiguration->Updates = Updates;
  7853. }
  7854. else if ((double(Updates.Period) > 0) &&
  7855. (Now() - Updates.LastCheck >= Updates.Period))
  7856. {
  7857. TThreadMethod OnUpdatesChecked = NULL;
  7858. if (!IsUWP())
  7859. {
  7860. OnUpdatesChecked = UpdatesChecked;
  7861. }
  7862. StartUpdateThread(OnUpdatesChecked);
  7863. }
  7864. }
  7865. //---------------------------------------------------------------------------
  7866. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  7867. {
  7868. UnicodeString Message;
  7869. bool New;
  7870. TQueryType Type;
  7871. GetUpdatesMessage(Message, New, Type, false);
  7872. if (!Message.IsEmpty())
  7873. {
  7874. if (New)
  7875. {
  7876. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  7877. }
  7878. if (!New && (Type != qtWarning))
  7879. {
  7880. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  7881. }
  7882. else
  7883. {
  7884. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  7885. }
  7886. if (New)
  7887. {
  7888. Configuration->Usage->Inc(L"UpdateNotifications");
  7889. }
  7890. }
  7891. }
  7892. //---------------------------------------------------------------------------
  7893. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  7894. {
  7895. RestoreApp();
  7896. bool CanDisplay = !NonVisualDataModule->Busy;
  7897. if (!CanDisplay && (Screen->ActiveForm != NULL))
  7898. {
  7899. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  7900. }
  7901. if (CanDisplay)
  7902. {
  7903. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  7904. CheckForUpdates(true);
  7905. }
  7906. else
  7907. {
  7908. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  7909. }
  7910. }
  7911. //---------------------------------------------------------------------------
  7912. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  7913. TCopyParamRuleData & Data)
  7914. {
  7915. DebugAssert(Terminal != NULL);
  7916. Data.HostName = Terminal->SessionData->HostNameExpanded;
  7917. Data.UserName = Terminal->SessionData->UserNameExpanded;
  7918. Data.RemoteDirectory = RemoteDirView->PathName;
  7919. }
  7920. //---------------------------------------------------------------------------
  7921. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  7922. {
  7923. // Terminal can be null when we are changing local directory implicitly,
  7924. // because it has been deleted, while no session is connected
  7925. // (Login dialog is open)
  7926. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  7927. {
  7928. TCopyParamRuleData Data;
  7929. GetTransferPresetAutoSelectData(Data);
  7930. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  7931. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  7932. if (CopyParamIndex < 0)
  7933. {
  7934. // there is no preset that matches autoselection
  7935. // set preset that we consider "default"
  7936. FCopyParamAutoSelected = L""; // forget last autoselected preset
  7937. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  7938. }
  7939. else
  7940. {
  7941. // there is preset matching autoselection
  7942. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  7943. if (CopyParamName == FCopyParamAutoSelected)
  7944. {
  7945. // autoselected the same preset as the last time
  7946. // make no change (i.e. preserve custom user preset, if any)
  7947. }
  7948. else
  7949. {
  7950. // autoselected the different preset then the last time (or there
  7951. // was default preset set)
  7952. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  7953. GUIConfiguration->CopyParamCurrent = CopyParamName;
  7954. }
  7955. }
  7956. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  7957. {
  7958. if (CopyParamIndex >= 0)
  7959. {
  7960. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  7961. }
  7962. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  7963. try
  7964. {
  7965. int Fmt =
  7966. (CopyParamIndex < 0) ?
  7967. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  7968. COPY_PARAM_AUTOSELECTED;
  7969. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  7970. Data->Message = MainInstructions(Message);
  7971. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  7972. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  7973. CopyParamAttrs);
  7974. if (CopyParamIndex >= 0)
  7975. {
  7976. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  7977. Info = FORMAT(L"%s\n \n%s", (Info,
  7978. FMTLOAD(COPY_PARAM_RULE,
  7979. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  7980. }
  7981. Data->Message += L"\n\n" + Info;
  7982. if (WinConfiguration->CopyParamAutoSelectNotice)
  7983. {
  7984. TransferPresetNoteMessage(Data, true);
  7985. }
  7986. else
  7987. {
  7988. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  7989. Data = NULL; // ownership passed
  7990. }
  7991. }
  7992. __finally
  7993. {
  7994. delete Data;
  7995. }
  7996. }
  7997. }
  7998. }
  7999. //---------------------------------------------------------------------------
  8000. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  8001. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  8002. {
  8003. DebugAssert(NoteData != NULL);
  8004. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  8005. TQueryButtonAlias Aliases[1];
  8006. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  8007. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  8008. Params.Aliases = Aliases;
  8009. Params.AliasesCount = LENOF(Aliases);
  8010. unsigned int Result =
  8011. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  8012. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  8013. switch (Result)
  8014. {
  8015. case qaNeverAskAgain:
  8016. DebugAssert(AllowNeverAskAgain);
  8017. WinConfiguration->CopyParamAutoSelectNotice = false;
  8018. break;
  8019. case qaIgnore:
  8020. PreferencesDialog(pmPresets);
  8021. break;
  8022. }
  8023. }
  8024. //---------------------------------------------------------------------------
  8025. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  8026. {
  8027. // as of now useless, as this is used for notes only, never for balloons, ...
  8028. RestoreApp();
  8029. // .. and we should never be busy here
  8030. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  8031. {
  8032. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  8033. }
  8034. }
  8035. //---------------------------------------------------------------------------
  8036. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  8037. TPreferencesMode APreferencesMode)
  8038. {
  8039. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  8040. TCopyParamRuleData Data;
  8041. if (Terminal != NULL)
  8042. {
  8043. PreferencesData.reset(new TPreferencesDialogData());
  8044. GetTransferPresetAutoSelectData(Data);
  8045. PreferencesData->CopyParamRuleData = &Data;
  8046. }
  8047. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  8048. }
  8049. //---------------------------------------------------------------------------
  8050. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  8051. const TCustomCommandType & Command)
  8052. {
  8053. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  8054. {
  8055. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE, (Command.Command)));
  8056. }
  8057. }
  8058. //---------------------------------------------------------------------------
  8059. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  8060. {
  8061. bool RemoteAllowed = CustomCommandRemoteAllowed();
  8062. TCustomCommandType Command;
  8063. // make sure we use local custom command when remote are not supported
  8064. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  8065. {
  8066. Command = FLastCustomCommand;
  8067. }
  8068. else
  8069. {
  8070. Command.Params = Command.Params | ccLocal;
  8071. }
  8072. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  8073. FEditingFocusedAdHocCommand = OnFocused;
  8074. bool LocalSide = (FCurrentSide == osLocal);
  8075. int Options =
  8076. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  8077. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  8078. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  8079. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  8080. {
  8081. FLastCustomCommand = Command;
  8082. UpdateCustomCommandsToolbar();
  8083. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  8084. }
  8085. }
  8086. //---------------------------------------------------------------------------
  8087. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  8088. {
  8089. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  8090. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  8091. DebugAssert(State > 0);
  8092. if (State <= 0)
  8093. {
  8094. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE, (FLastCustomCommand.Command)));
  8095. }
  8096. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  8097. }
  8098. //---------------------------------------------------------------------------
  8099. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  8100. TCustomCommandType & Command, int & State)
  8101. {
  8102. bool Result = !FLastCustomCommand.Command.IsEmpty();
  8103. if (Result)
  8104. {
  8105. Command = FLastCustomCommand;
  8106. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  8107. }
  8108. return Result;
  8109. }
  8110. //---------------------------------------------------------------------------
  8111. void __fastcall TCustomScpExplorerForm::BeforeAction()
  8112. {
  8113. if (RemoteDirView->ItemFocused != NULL)
  8114. {
  8115. RemoteDirView->ItemFocused->CancelEdit();
  8116. }
  8117. }
  8118. //---------------------------------------------------------------------------
  8119. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  8120. {
  8121. DebugAssert(ComponentVisible[Component]);
  8122. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  8123. }
  8124. //---------------------------------------------------------------------------
  8125. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  8126. {
  8127. // when queue panel is resized here directly, the status bar is stretched
  8128. // over whole space the panel occupied
  8129. PostComponentHide(fcQueueView);
  8130. }
  8131. //---------------------------------------------------------------------------
  8132. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  8133. {
  8134. TMessage * M = static_cast<TMessage*>(Message);
  8135. switch (M->Msg)
  8136. {
  8137. case CM_DIALOGCHAR:
  8138. CMDialogChar(*M);
  8139. break;
  8140. case WM_APPCOMMAND:
  8141. WMAppCommand(*M);
  8142. break;
  8143. case WM_SYSCOMMAND:
  8144. WMSysCommand(*M);
  8145. break;
  8146. case WM_QUERYENDSESSION:
  8147. WMQueryEndSession(*M);
  8148. break;
  8149. case WM_ENDSESSION:
  8150. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  8151. break;
  8152. #ifdef _DEBUG
  8153. case WM_WINDOWPOSCHANGED:
  8154. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  8155. break;
  8156. case CM_CUSTOMSTYLECHANGED:
  8157. TForm::Dispatch(Message);
  8158. break;
  8159. #endif
  8160. case WM_COMPONENT_HIDE:
  8161. {
  8162. Byte Component = static_cast<Byte>(M->WParam);
  8163. // sanity check
  8164. if (ComponentVisible[Component])
  8165. {
  8166. // special treatment
  8167. if (Component == fcQueueView)
  8168. {
  8169. ToggleQueueVisibility();
  8170. DebugAssert(!ComponentVisible[fcQueueView]);
  8171. }
  8172. else
  8173. {
  8174. ComponentVisible[Component] = false;
  8175. }
  8176. }
  8177. }
  8178. break;
  8179. case WM_COPYDATA:
  8180. WMCopyData(*M);
  8181. break;
  8182. case WM_MANAGES_CAPTION:
  8183. // caption managed in TTerminalManager::UpdateAppTitle()
  8184. M->Result = 1;
  8185. break;
  8186. case WM_WANTS_MOUSEWHEEL:
  8187. M->Result = 1;
  8188. break;
  8189. case CM_SHOWINGCHANGED:
  8190. CMShowingChanged(*M);
  8191. break;
  8192. case WM_CLOSE:
  8193. WMClose(*M);
  8194. break;
  8195. case WM_DPICHANGED:
  8196. WMDpiChanged(*M);
  8197. break;
  8198. case CM_DPICHANGED:
  8199. CMDpiChanged(*M);
  8200. break;
  8201. default:
  8202. TForm::Dispatch(Message);
  8203. break;
  8204. }
  8205. }
  8206. //---------------------------------------------------------------------------
  8207. void __fastcall TCustomScpExplorerForm::UpdateImages()
  8208. {
  8209. // noop
  8210. }
  8211. //---------------------------------------------------------------------------
  8212. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  8213. {
  8214. TForm::Dispatch(&Message);
  8215. FSessionColors->Clear();
  8216. AddFixedSessionImages();
  8217. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  8218. UpdateImages();
  8219. }
  8220. //---------------------------------------------------------------------------
  8221. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  8222. {
  8223. TForm::Dispatch(&Message);
  8224. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  8225. UpdatePixelsPerInchMainWindowCounter();
  8226. }
  8227. //---------------------------------------------------------------------------
  8228. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  8229. {
  8230. // Cannot close window while we are busy.
  8231. // We cannot test this in FormCloseQuery as that is called also from
  8232. // Close(), which is called by CloseApplicationAction. So we can be busy
  8233. // there already even, when it is legitimate to close the application.
  8234. // Possibly a better place to handle this would be WMSysCommand.
  8235. if (NonVisualDataModule->Busy)
  8236. {
  8237. Message.Result = 1;
  8238. }
  8239. else
  8240. {
  8241. TForm::Dispatch(&Message);
  8242. }
  8243. }
  8244. //---------------------------------------------------------------------------
  8245. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  8246. {
  8247. TForm::Dispatch(&Message);
  8248. if (Showing && (Terminal == NULL))
  8249. {
  8250. // When we are starting minimized (i.e. from an installer),
  8251. // postpone showing Login dialog until we get restored.
  8252. // Otherwise the Login dialog (and Authentication window) show restored
  8253. // over invidible (minimized) main window.
  8254. if (WindowState == wsMinimized)
  8255. {
  8256. FNeedSession = true;
  8257. }
  8258. else
  8259. {
  8260. // This happens before application ever goes idle, so the toolbars would
  8261. // stay enabled (initial state) until the Login dialog is dismissed.
  8262. UpdateActions();
  8263. NonVisualDataModule->StartBusy();
  8264. try
  8265. {
  8266. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  8267. // otherwise the dialog does not receive focus.
  8268. // With Commander interface the ProcessMessages is called already
  8269. // by TDriveView, but with Explorer interface, we need to call it explicily
  8270. Application->ProcessMessages();
  8271. // do not reload sessions, they have been loaded just now (optimization)
  8272. NeedSession(false);
  8273. }
  8274. __finally
  8275. {
  8276. NonVisualDataModule->EndBusy();
  8277. }
  8278. }
  8279. }
  8280. }
  8281. //---------------------------------------------------------------------------
  8282. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  8283. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  8284. int & MaxHeight)
  8285. {
  8286. // workaround for bug in TWinControl.CalcConstraints
  8287. // Check for empty rect (restore from iconic state) is done there only after
  8288. // call to AdjustClientRect, which enlarges the rect (for forms).
  8289. TRect R = GetClientRect();
  8290. // when restoring from iconic state, place no restrictions
  8291. if (IsRectEmpty(R))
  8292. {
  8293. MinWidth = 0;
  8294. MinHeight = 0;
  8295. MaxWidth = 32000;
  8296. MaxHeight = 32000;
  8297. }
  8298. }
  8299. //---------------------------------------------------------------------------
  8300. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  8301. TSpaceAvailable & ASpaceAvailable, bool & Close)
  8302. {
  8303. // terminal can be already closed (e.g. dropped connection)
  8304. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  8305. {
  8306. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  8307. try
  8308. {
  8309. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  8310. }
  8311. catch(...)
  8312. {
  8313. if (!Terminal->Active)
  8314. {
  8315. Close = true;
  8316. }
  8317. throw;
  8318. }
  8319. }
  8320. }
  8321. //---------------------------------------------------------------------------
  8322. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  8323. {
  8324. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  8325. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  8326. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  8327. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  8328. {
  8329. OnGetSpaceAvailable = GetSpaceAvailable;
  8330. }
  8331. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  8332. OnGetSpaceAvailable);
  8333. }
  8334. //---------------------------------------------------------------------------
  8335. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  8336. {
  8337. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  8338. Terminal->FillSessionDataForCode(Data.get());
  8339. return Data.release();
  8340. }
  8341. //---------------------------------------------------------------------------
  8342. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  8343. {
  8344. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  8345. DoGenerateUrlDialog(Data.get(), Paths);
  8346. }
  8347. //---------------------------------------------------------------------------
  8348. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  8349. {
  8350. GenerateUrl(NULL);
  8351. }
  8352. //---------------------------------------------------------------------------
  8353. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  8354. {
  8355. std::unique_ptr<TStrings> Paths(new TStringList());
  8356. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  8357. GenerateUrl(Paths.get());
  8358. }
  8359. //---------------------------------------------------------------------------
  8360. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  8361. {
  8362. if (value != FSessionColor)
  8363. {
  8364. FSessionColor = value;
  8365. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  8366. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  8367. static_cast<TObject *>(GetComponent(fcColorMenu)));
  8368. DebugAssert(ColorItem != NULL);
  8369. ColorItem->Color = C;
  8370. NonVisualDataModule->ColorMenuItem->Color = C;
  8371. // Is null when called from LastTerminalClosed
  8372. if (Terminal != NULL)
  8373. {
  8374. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  8375. }
  8376. UpdateControls();
  8377. }
  8378. }
  8379. //---------------------------------------------------------------------------
  8380. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  8381. {
  8382. bool Result = FNoteTimer->Enabled;
  8383. if (Result)
  8384. {
  8385. // cannot cancel note too early
  8386. bool NotEarly =
  8387. (Now() - FNoteShown >
  8388. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  8389. if (Force || NotEarly)
  8390. {
  8391. FNoteTimer->Enabled = false;
  8392. FNote = L"";
  8393. SAFE_DESTROY(FNoteData);
  8394. FOnNoteClick = NULL;
  8395. FNoteHints = FNotes->Text;
  8396. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8397. UpdateStatusBar();
  8398. }
  8399. }
  8400. return Result;
  8401. }
  8402. //---------------------------------------------------------------------------
  8403. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  8404. {
  8405. DebugAssert(FNoteTimer->Enabled);
  8406. CancelNote(true);
  8407. }
  8408. //---------------------------------------------------------------------------
  8409. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  8410. {
  8411. int P = Note.Pos(L"\n");
  8412. if (P > 0)
  8413. {
  8414. Note.SetLength(P - 1);
  8415. }
  8416. FNotes->Add(FORMAT(L"[%s] %s",
  8417. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  8418. while (FNotes->Count > 10)
  8419. {
  8420. FNotes->Delete(0);
  8421. }
  8422. if (UpdateNow)
  8423. {
  8424. FNoteHints = FNotes->Text;
  8425. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8426. UpdateStatusBar();
  8427. }
  8428. }
  8429. //---------------------------------------------------------------------------
  8430. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  8431. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  8432. {
  8433. int P = Note.Pos(L"\n");
  8434. if (P > 0)
  8435. {
  8436. Note.SetLength(P - 1);
  8437. }
  8438. FNoteHints = FNotes->Text;
  8439. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8440. FNote = Note;
  8441. SAFE_DESTROY(FNoteData);
  8442. FNoteData = NoteData;
  8443. FOnNoteClick = OnNoteClick;
  8444. AddNote(Note, false);
  8445. UpdateStatusBar();
  8446. FNoteShown = Now();
  8447. FNoteTimer->Enabled = false;
  8448. if (Seconds == 0)
  8449. {
  8450. Seconds = WinConfiguration->NotificationsTimeout;
  8451. }
  8452. FNoteTimer->Interval = Seconds * MSecsPerSec;
  8453. FNoteTimer->Enabled = true;
  8454. }
  8455. //---------------------------------------------------------------------------
  8456. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  8457. {
  8458. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  8459. }
  8460. //---------------------------------------------------------------------------
  8461. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  8462. {
  8463. if (NonVisualDataModule->SynchronizeBrowsingAction->Checked)
  8464. {
  8465. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  8466. }
  8467. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  8468. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  8469. (NonVisualDataModule->SynchronizeBrowsingAction->Checked ? 2 : 3)))),
  8470. 0, NULL, NULL);
  8471. }
  8472. //---------------------------------------------------------------------------
  8473. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  8474. {
  8475. WinConfiguration->ShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  8476. PostNote(FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1),
  8477. (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE,
  8478. (WinConfiguration->ShowHiddenFiles ? 2 : 3)))), 0, NULL, NULL);
  8479. }
  8480. //---------------------------------------------------------------------------
  8481. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  8482. {
  8483. WinConfiguration->FormatSizeBytes = Style;
  8484. }
  8485. //---------------------------------------------------------------------------
  8486. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  8487. {
  8488. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  8489. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  8490. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  8491. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  8492. }
  8493. //---------------------------------------------------------------------------
  8494. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  8495. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  8496. {
  8497. if (Panel->Index == 0)
  8498. {
  8499. if (FOnNoteClick != NULL)
  8500. {
  8501. // prevent the user data from being freed by possible call
  8502. // to CancelNote or PostNote during call to OnNoteClick
  8503. std::unique_ptr<TObject> NoteData(FNoteData);
  8504. TNotifyEvent OnNoteClick = FOnNoteClick;
  8505. FNoteData = NULL;
  8506. // need to cancel the note as we are going to delete its user data
  8507. CancelNote(true);
  8508. OnNoteClick(NoteData.get());
  8509. }
  8510. }
  8511. if (Panel->Index >= Sender->Panels->Count - SessionPanelCount)
  8512. {
  8513. FileSystemInfo();
  8514. }
  8515. }
  8516. //---------------------------------------------------------------------------
  8517. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  8518. {
  8519. // workaround:
  8520. // 1) for unknown reason, disabling window, while minimized,
  8521. // prevents it from restoring, even if it was enabled again meanwhile
  8522. // 2) when disabling the main window, while another has focus
  8523. // minimize is no longer possible
  8524. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  8525. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  8526. // Shouldn't we use IsApplicationMinimized() here?
  8527. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  8528. {
  8529. Enabled = false;
  8530. }
  8531. FLockLevel++;
  8532. }
  8533. //---------------------------------------------------------------------------
  8534. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  8535. {
  8536. DebugAssert(FLockLevel > 0);
  8537. FLockLevel--;
  8538. if (FLockLevel == 0)
  8539. {
  8540. DebugAssert(FLockSuspendLevel == 0);
  8541. Enabled = true;
  8542. }
  8543. }
  8544. //---------------------------------------------------------------------------
  8545. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  8546. {
  8547. // We need to make sure that window is enabled when the last modal window closes
  8548. // otherwise focus is not restored correctly.
  8549. // So we re-enable the window when modal window opens and
  8550. // disable it back after is closes
  8551. if (FLockLevel > 0)
  8552. {
  8553. // while we have nesting counter, we know that we never be called
  8554. // recursivelly as Application->OnModalBegin is called only
  8555. // for the top-level modal window
  8556. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  8557. {
  8558. // won't be disabled when conditions in LockWindow() were not satisfied
  8559. FDisabledOnLockSuspend = !Enabled;
  8560. // When minimized to tray (or actually when set to SW_HIDE),
  8561. // setting Enabled makes the window focusable even when there's
  8562. // modal window over it
  8563. if (!FTrayIcon->Visible)
  8564. {
  8565. Enabled = true;
  8566. }
  8567. }
  8568. FLockSuspendLevel++;
  8569. }
  8570. }
  8571. //---------------------------------------------------------------------------
  8572. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  8573. {
  8574. if (FLockSuspendLevel > 0)
  8575. {
  8576. DebugAssert(FLockLevel > 0);
  8577. FLockSuspendLevel--;
  8578. // see comment in SuspendWindowLock
  8579. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  8580. {
  8581. // Note that window can be enabled here, when we were minized to tray when
  8582. // was SuspendWindowLock() called.
  8583. // We should possibly do the same check as in LockWindow(),
  8584. // if it is ever possible that the consitions change between
  8585. // SuspendWindowLock() and ResumeWindowLock()
  8586. Enabled = !FDisabledOnLockSuspend;
  8587. }
  8588. }
  8589. }
  8590. //---------------------------------------------------------------------------
  8591. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  8592. {
  8593. if (!TextOnly)
  8594. {
  8595. TTBXComboBoxItem * RemotePathComboBox =
  8596. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  8597. TStrings * Items = RemotePathComboBox->Strings;
  8598. Items->BeginUpdate();
  8599. try
  8600. {
  8601. Items->Clear();
  8602. if (Terminal != NULL)
  8603. {
  8604. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  8605. while (!IsUnixRootPath(APath))
  8606. {
  8607. int P = APath.LastDelimiter(L'/');
  8608. DebugAssert(P >= 0);
  8609. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  8610. APath.SetLength(P - 1);
  8611. }
  8612. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  8613. }
  8614. }
  8615. __finally
  8616. {
  8617. RemotePathComboBox->ItemIndex = Items->Count - 1;
  8618. // Setting ItemIndex to -1 does not reset its text
  8619. if (Items->Count == 0)
  8620. {
  8621. RemotePathComboBox->Text = L"";
  8622. }
  8623. Items->EndUpdate();
  8624. }
  8625. }
  8626. }
  8627. //---------------------------------------------------------------------------
  8628. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  8629. TTBXComboBoxItem * Sender, const UnicodeString /*AText*/, int AIndex,
  8630. int & ImageIndex)
  8631. {
  8632. if (AIndex < 0)
  8633. {
  8634. AIndex = Sender->ItemIndex;
  8635. }
  8636. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  8637. }
  8638. //---------------------------------------------------------------------------
  8639. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  8640. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  8641. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  8642. {
  8643. ARect.Left += (10 * AIndex);
  8644. }
  8645. //---------------------------------------------------------------------------
  8646. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  8647. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  8648. {
  8649. AWidth += (10 * AIndex);
  8650. }
  8651. //---------------------------------------------------------------------------
  8652. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(
  8653. TObject * Sender)
  8654. {
  8655. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  8656. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  8657. int Index = RemotePathComboBox->ItemIndex;
  8658. while (Index < RemotePathComboBox->Strings->Count - 1)
  8659. {
  8660. APath = UnixExtractFileDir(APath);
  8661. Index++;
  8662. }
  8663. // VanDyke style paths
  8664. if (APath.IsEmpty())
  8665. {
  8666. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  8667. APath = ROOTDIRECTORY;
  8668. }
  8669. if (RemoteDirView->Path != APath)
  8670. {
  8671. RemoteDirView->Path = APath;
  8672. }
  8673. }
  8674. //---------------------------------------------------------------------------
  8675. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  8676. {
  8677. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  8678. DebugUsedParam(Sender);
  8679. UpdateRemotePathComboBox(true);
  8680. }
  8681. //---------------------------------------------------------------------------
  8682. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  8683. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  8684. {
  8685. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8686. DebugAssert(DirView != NULL);
  8687. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  8688. {
  8689. HWND Edit = ListView_GetEditControl(DirView->Handle);
  8690. // OnEditing is called also from TCustomListView::CanEdit
  8691. if (Edit != NULL)
  8692. {
  8693. EditSelectBaseName(Edit);
  8694. }
  8695. }
  8696. }
  8697. //---------------------------------------------------------------------------
  8698. //---------------------------------------------------------------------------
  8699. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  8700. {
  8701. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  8702. Result->AutoDetectDnD = false;
  8703. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  8704. Result->RenderDataOn = rdoEnterAndDropSync;
  8705. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  8706. return Result;
  8707. }
  8708. //---------------------------------------------------------------------------
  8709. void __fastcall TCustomScpExplorerForm::CreateWnd()
  8710. {
  8711. TForm::CreateWnd();
  8712. if (FSessionsDragDropFilesEx == NULL)
  8713. {
  8714. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  8715. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  8716. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  8717. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  8718. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  8719. }
  8720. if (FQueueDragDropFilesEx == NULL)
  8721. {
  8722. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  8723. // No need to set OnDragOver as we do not have any restrictions
  8724. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  8725. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  8726. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  8727. }
  8728. }
  8729. //---------------------------------------------------------------------------
  8730. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  8731. {
  8732. TForm::DestroyWnd();
  8733. FSessionsDragDropFilesEx->DragDropControl = NULL;
  8734. FQueueDragDropFilesEx->DragDropControl = NULL;
  8735. }
  8736. //---------------------------------------------------------------------------
  8737. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  8738. {
  8739. SideEnter(FCurrentSide);
  8740. FEverShown = true;
  8741. }
  8742. //---------------------------------------------------------------------------
  8743. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  8744. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  8745. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  8746. {
  8747. if (!NonVisualDataModule->Busy)
  8748. {
  8749. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8750. Configuration->Usage->Inc(L"FileFinds");
  8751. LockWindow(true);
  8752. NonVisualDataModule->StartBusy();
  8753. WinConfiguration->LockedInterface = true;
  8754. try
  8755. {
  8756. FTerminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  8757. }
  8758. __finally
  8759. {
  8760. WinConfiguration->LockedInterface = false;
  8761. NonVisualDataModule->EndBusy();
  8762. UnlockWindow();
  8763. }
  8764. }
  8765. }
  8766. //---------------------------------------------------------------------------
  8767. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  8768. {
  8769. if (!NonVisualDataModule->Busy)
  8770. {
  8771. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8772. SetFocus();
  8773. RemoteDirView->Path = UnixExtractFilePath(Path);
  8774. TListItem * Item = RemoteDirView->FindFileItem(UnixExtractFileName(Path));
  8775. if (Item != NULL)
  8776. {
  8777. RemoteDirView->ItemFocused = Item;
  8778. RemoteDirView->ItemFocused->MakeVisible(false);
  8779. RemoteDirView->SetFocus();
  8780. }
  8781. }
  8782. }
  8783. //---------------------------------------------------------------------------
  8784. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  8785. {
  8786. bool Result = !NonVisualDataModule->Busy;
  8787. if (Result)
  8788. {
  8789. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8790. }
  8791. return Result;
  8792. }
  8793. //---------------------------------------------------------------------------
  8794. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  8795. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8796. {
  8797. if (CanOperateOnFoundFiles(ATerminal))
  8798. {
  8799. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  8800. FOnFileOperationFinished = OnFileOperationFinished;
  8801. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  8802. }
  8803. }
  8804. //---------------------------------------------------------------------------
  8805. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  8806. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8807. {
  8808. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  8809. }
  8810. //---------------------------------------------------------------------------
  8811. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  8812. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8813. {
  8814. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  8815. }
  8816. //---------------------------------------------------------------------------
  8817. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  8818. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8819. {
  8820. if (CanOperateOnFoundFiles(ATerminal))
  8821. {
  8822. for (int Index = 0; Index < FileList->Count; Index++)
  8823. {
  8824. UnicodeString FileName = FileList->Strings[Index];
  8825. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  8826. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  8827. OnFileOperationFinished(FileName, true);
  8828. }
  8829. }
  8830. }
  8831. //---------------------------------------------------------------------------
  8832. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  8833. {
  8834. FFileFindTerminal = Terminal;
  8835. ShowFileFindDialog(
  8836. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  8837. DoDownloadFoundFiles, DoEditFoundFiles);
  8838. }
  8839. //---------------------------------------------------------------------------
  8840. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  8841. {
  8842. FTaskbarList = TaskbarList;
  8843. }
  8844. //---------------------------------------------------------------------------
  8845. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  8846. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  8847. {
  8848. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  8849. if (Index >= 0)
  8850. {
  8851. if (Button == mbLeft)
  8852. {
  8853. // "Mouse down" is raised only after tab is switched.
  8854. // If switching tab (switching session) takes long enough for user
  8855. // to actually release the button, "mouse down" is still raised,
  8856. // but we do not get "mouse up" event, so dragging is not cancelled,
  8857. // prevent that by not beginning dragging in the first place.
  8858. if (IsKeyPressed(VK_LBUTTON))
  8859. {
  8860. // when user clicks the "+", we get mouse down only after the session
  8861. // is closed, when new session tab is already on X:Y, so dragging
  8862. // starts, prevent that
  8863. if (MilliSecondsBetween(Now(), FSessionsPageControlNewSessionTime) > 500)
  8864. {
  8865. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8866. if (Terminal != NULL)
  8867. {
  8868. SessionsPageControl->BeginDrag(false);
  8869. }
  8870. }
  8871. }
  8872. }
  8873. else if (Button == mbMiddle)
  8874. {
  8875. // ignore middle-click for "New session tab"
  8876. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8877. if (Terminal != NULL)
  8878. {
  8879. CloseSessionTab(Index);
  8880. }
  8881. }
  8882. }
  8883. }
  8884. //---------------------------------------------------------------------------
  8885. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  8886. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  8887. {
  8888. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  8889. // do not allow dropping on the "+" tab
  8890. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8891. if ((TargetTerminal != NULL) &&
  8892. (SessionsPageControl->ActivePage->PageIndex != Index))
  8893. {
  8894. Configuration->Usage->Inc(L"SessionTabMoves");
  8895. // this is almost redundant as we would recreate tabs in DoTerminalListChanged,
  8896. // but we want to actually prevent that to avoid flicker
  8897. SessionsPageControl->ActivePage->PageIndex = Index;
  8898. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->ActivePage);
  8899. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  8900. }
  8901. }
  8902. //---------------------------------------------------------------------------
  8903. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  8904. TObject * Sender, TObject * Source, int X, int Y,
  8905. TDragState /*State*/, bool & Accept)
  8906. {
  8907. Accept = (Sender == Source);
  8908. if (Accept)
  8909. {
  8910. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  8911. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8912. // do not allow dragging to the "+" tab
  8913. Accept = (Terminal != NULL);
  8914. }
  8915. }
  8916. //---------------------------------------------------------------------------
  8917. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(int /*KeyState*/,
  8918. const TPoint & Point, int & Effect)
  8919. {
  8920. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  8921. if (Index < 0)
  8922. {
  8923. Effect = DROPEFFECT_None;
  8924. }
  8925. else
  8926. {
  8927. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8928. // do not allow dropping on the "+" tab
  8929. if (TargetTerminal == NULL)
  8930. {
  8931. Effect = DROPEFFECT_None;
  8932. }
  8933. else if ((TargetTerminal != Terminal) && (Effect == DROPEFFECT_Move))
  8934. {
  8935. Effect = DROPEFFECT_Copy;
  8936. }
  8937. }
  8938. }
  8939. //---------------------------------------------------------------------------
  8940. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  8941. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  8942. {
  8943. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  8944. // do not allow dropping on the "+" tab
  8945. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8946. if (TargetTerminal != NULL)
  8947. {
  8948. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  8949. if (!IsFileControl(DropSourceControl, osRemote))
  8950. {
  8951. TTerminalManager::Instance()->ActiveTerminal = TargetTerminal;
  8952. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  8953. // Why don't we use Terminal->CurrentDirectory directly?
  8954. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  8955. // do not force queue, drag drop
  8956. false, true);
  8957. }
  8958. }
  8959. }
  8960. //---------------------------------------------------------------------------
  8961. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  8962. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  8963. {
  8964. // Downloads are handled in RemoteFileControlDDEnd
  8965. if (!IsFileControl(DropSourceControl, osRemote))
  8966. {
  8967. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  8968. Terminal->CurrentDirectory,
  8969. // force queue, drag drop
  8970. true, true);
  8971. }
  8972. }
  8973. //---------------------------------------------------------------------------
  8974. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  8975. {
  8976. FShowing = false;
  8977. // Do not save empty workspace
  8978. if (WinConfiguration->AutoSaveWorkspace && (Terminal != NULL))
  8979. {
  8980. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  8981. UnicodeString Name = WorkspaceName();
  8982. DoSaveWorkspace(
  8983. Name, DataList.get(),
  8984. !Configuration->DisablePasswordStoring &&
  8985. WinConfiguration->AutoSaveWorkspacePasswords, false);
  8986. WinConfiguration->LastStoredSession = Name;
  8987. }
  8988. }
  8989. //---------------------------------------------------------------------------
  8990. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  8991. {
  8992. TManagedTerminal * ManagedTerminal =
  8993. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  8994. if (ManagedTerminal != NULL)
  8995. {
  8996. ManagedTerminal->DirectoryLoaded = Now();
  8997. }
  8998. }
  8999. //---------------------------------------------------------------------------
  9000. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  9001. TListItem * /*Item*/, bool /*Selected*/)
  9002. {
  9003. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  9004. switch (DirView->LastSelectMethod)
  9005. {
  9006. case smKeyboard:
  9007. Configuration->Usage->Inc(L"KeyboardSelections");
  9008. break;
  9009. case smMouse:
  9010. Configuration->Usage->Inc(L"MouseSelections");
  9011. break;
  9012. }
  9013. }
  9014. //---------------------------------------------------------------------------
  9015. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  9016. {
  9017. if (Color != 0)
  9018. {
  9019. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  9020. }
  9021. else
  9022. {
  9023. return FSessionTabImageIndex;
  9024. }
  9025. }
  9026. //---------------------------------------------------------------------------
  9027. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  9028. {
  9029. TPngImageCollectionItem * Item =
  9030. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  9031. FSessionColors->AddPng(Item->PngImage);
  9032. return FSessionColors->Count - 1;
  9033. }
  9034. //---------------------------------------------------------------------------
  9035. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  9036. {
  9037. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  9038. FNewSessionTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewSessionAction->ImageIndex);
  9039. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  9040. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  9041. }
  9042. //---------------------------------------------------------------------------
  9043. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  9044. {
  9045. for (int Index = 0; Index < Control->ControlCount; Index++)
  9046. {
  9047. TControl * AControl = Control->Controls[Index];
  9048. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  9049. if (WinControl != NULL)
  9050. {
  9051. CollectItemsWithTextDisplayMode(WinControl);
  9052. }
  9053. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  9054. if (Toolbar != NULL)
  9055. {
  9056. // we care for top-level items only
  9057. TTBCustomItem * Items = Toolbar->Items;
  9058. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  9059. {
  9060. TTBCustomItem * Item = Items->Items[ItemIndex];
  9061. if (((Item->DisplayMode == nbdmImageAndText) ||
  9062. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  9063. EligibleForImageDisplayMode(Item))
  9064. {
  9065. FItemsWithTextDisplayMode.insert(Item);
  9066. }
  9067. }
  9068. }
  9069. }
  9070. }
  9071. //---------------------------------------------------------------------------
  9072. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  9073. {
  9074. return true;
  9075. }
  9076. //---------------------------------------------------------------------------
  9077. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  9078. {
  9079. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  9080. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  9081. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  9082. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  9083. bool Result = true;
  9084. while (Result && (i != FItemsWithTextDisplayMode.end()))
  9085. {
  9086. TTBCustomItem * Item = *i;
  9087. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  9088. if (Label != NULL)
  9089. {
  9090. // optimization
  9091. if (Label->Visible == SelectiveToolbarText)
  9092. {
  9093. Result = false;
  9094. }
  9095. else
  9096. {
  9097. Label->Visible = SelectiveToolbarText;
  9098. }
  9099. }
  9100. else
  9101. {
  9102. // optimization
  9103. if (Item->DisplayMode == DisplayMode)
  9104. {
  9105. Result = false;
  9106. }
  9107. else
  9108. {
  9109. Item->DisplayMode = DisplayMode;
  9110. }
  9111. }
  9112. ++i;
  9113. }
  9114. if (Result)
  9115. {
  9116. UpdateNewSessionTab();
  9117. }
  9118. return Result;
  9119. }
  9120. //---------------------------------------------------------------------------
  9121. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  9122. {
  9123. DebugFail();
  9124. }
  9125. //---------------------------------------------------------------------------
  9126. bool __fastcall TCustomScpExplorerForm::IsBusy()
  9127. {
  9128. // Among other, a lock level is non zero, while directory is being loaded,
  9129. // even when it happens as a result of dirview navigation,
  9130. // i.e. when TNonVisualDataModule is NOT FBusy.
  9131. // That's why the TNonVisualDataModule::GetBusy calls this method.
  9132. // Among other this prevents a panel auto update to occur while
  9133. // directory is changing.
  9134. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  9135. }
  9136. //---------------------------------------------------------------------------
  9137. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * /*Action*/, TActionAllowed Allowed)
  9138. {
  9139. // While the window is disabled, we still seem to process menu shortcuts at least,
  9140. // so stop it at least here.
  9141. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  9142. return
  9143. (Allowed == aaUpdate) ||
  9144. !NonVisualDataModule->Busy;
  9145. }
  9146. //---------------------------------------------------------------------------
  9147. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  9148. {
  9149. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  9150. }
  9151. //---------------------------------------------------------------------------
  9152. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  9153. {
  9154. // This is somewhat redundant to LockWindow() call from
  9155. // TTerminalManager::TerminalReadDirectoryProgress.
  9156. // But disabling window is known not to block keyboard shorcuts
  9157. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  9158. if (Busy > 0)
  9159. {
  9160. if (NonVisualDataModule->Busy)
  9161. {
  9162. State = false;
  9163. }
  9164. else
  9165. {
  9166. NonVisualDataModule->StartBusy();
  9167. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  9168. LockWindow();
  9169. }
  9170. }
  9171. else if (Busy < 0)
  9172. {
  9173. UnlockWindow();
  9174. NonVisualDataModule->EndBusy();
  9175. }
  9176. else
  9177. {
  9178. State = NonVisualDataModule->Busy;
  9179. }
  9180. }
  9181. //---------------------------------------------------------------------------
  9182. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  9183. {
  9184. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  9185. // no context menu for "New session tab"
  9186. if ((Index >= 0) && (GetSessionTabTerminal(SessionsPageControl->Pages[Index]) != NULL))
  9187. {
  9188. SessionsPageControl->ActivePageIndex = Index;
  9189. if (DebugAlwaysTrue(SessionTabSwitched()))
  9190. {
  9191. // copied from TControl.WMContextMenu
  9192. SendCancelMode(SessionsPageControl);
  9193. // explicit popup instead of using PopupMenu property
  9194. // to avoid menu to popup somewhere within SessionTabSwitched above,
  9195. // while connecting yet not-connected session and hence
  9196. // allowing an access to commands over not-completelly connected session
  9197. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  9198. TPopupMenu * PopupMenu = NonVisualDataModule->SessionsPopup;
  9199. PopupMenu->PopupComponent = SessionsPageControl;
  9200. PopupMenu->Popup(Point.x, Point.y);
  9201. }
  9202. }
  9203. Handled = true;
  9204. }
  9205. //---------------------------------------------------------------------------
  9206. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  9207. {
  9208. return (Terminal != NULL) && Terminal->Active && Terminal->IsCapable[fcChangePassword];
  9209. }
  9210. //---------------------------------------------------------------------------
  9211. void __fastcall TCustomScpExplorerForm::ChangePassword()
  9212. {
  9213. Configuration->Usage->Inc(L"PasswordChanges");
  9214. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  9215. ChangePasswordData->DisableAuthentationsExceptPassword();
  9216. ChangePasswordData->ChangePassword = true;
  9217. std::unique_ptr<TTerminal> ChangePasswordSession(
  9218. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  9219. ChangePasswordSession->AutoReadDirectory = false;
  9220. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  9221. {
  9222. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  9223. }
  9224. else
  9225. {
  9226. Configuration->Usage->Inc(L"PasswordChangesFailed");
  9227. }
  9228. }
  9229. //---------------------------------------------------------------------------
  9230. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  9231. {
  9232. // No nice way to assert SSH2
  9233. return (Terminal != NULL) && Terminal->Active && (Terminal->FSProtocol == cfsSFTP);
  9234. }
  9235. //---------------------------------------------------------------------------
  9236. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  9237. {
  9238. TOperationVisualizer OperationVisualizer;
  9239. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  9240. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  9241. }
  9242. //---------------------------------------------------------------------------
  9243. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  9244. {
  9245. TForm::ChangeScale(M, D);
  9246. int APixelsPerInch = GetControlPixelsPerInch(this);
  9247. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  9248. try
  9249. {
  9250. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  9251. }
  9252. __finally
  9253. {
  9254. GUIConfiguration->ChangeResourceModule(ResourceModule);
  9255. }
  9256. }
  9257. //---------------------------------------------------------------------------
  9258. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  9259. {
  9260. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  9261. }
  9262. //---------------------------------------------------------------------
  9263. class TPublicControl : public TControl
  9264. {
  9265. friend class TCustomScpExplorerForm;
  9266. };
  9267. //---------------------------------------------------------------------------
  9268. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  9269. {
  9270. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  9271. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  9272. }
  9273. //---------------------------------------------------------------------------
  9274. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  9275. {
  9276. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  9277. OpenBookmark(Side, Bookmark);
  9278. }
  9279. //---------------------------------------------------------------------------
  9280. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  9281. {
  9282. DoBookmarkClick(osLocal, Sender);
  9283. }
  9284. //---------------------------------------------------------------------------
  9285. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  9286. {
  9287. DoBookmarkClick(osRemote, Sender);
  9288. }
  9289. //---------------------------------------------------------------------------
  9290. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  9291. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  9292. {
  9293. if (BookmarkList != NULL)
  9294. {
  9295. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  9296. if (!WinConfiguration->UseLocationProfiles)
  9297. {
  9298. std::unique_ptr<TStringList> Directories(new TStringList());
  9299. Directories->CaseSensitive = (Side == osRemote);
  9300. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9301. {
  9302. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9303. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  9304. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  9305. {
  9306. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  9307. Item->Caption = EscapeHotkey(Directory);
  9308. Item->ShortCut = Bookmark->ShortCut;
  9309. Item->OnClick = OnBookmarkClick;
  9310. Item->Tag = reinterpret_cast<int>(Bookmark);
  9311. Directories->Add(Directory);
  9312. Menu->Add(Item.release());
  9313. }
  9314. }
  9315. }
  9316. else
  9317. {
  9318. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  9319. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9320. {
  9321. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9322. if (!Bookmark->Node.IsEmpty())
  9323. {
  9324. Folders->Add(Bookmark->Node);
  9325. }
  9326. }
  9327. for (int Index = 0; Index < Folders->Count; Index++)
  9328. {
  9329. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  9330. Item->Caption = Folders->Strings[Index];
  9331. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction->ImageIndex;
  9332. Folders->Objects[Index] = Item.get();
  9333. Menu->Add(Item.release());
  9334. }
  9335. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9336. {
  9337. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9338. TTBCustomItem * Parent;
  9339. if (!Bookmark->Node.IsEmpty())
  9340. {
  9341. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  9342. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  9343. }
  9344. else
  9345. {
  9346. Parent = Menu;
  9347. }
  9348. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  9349. Item->Caption = Bookmark->Name;
  9350. Item->ShortCut = Bookmark->ShortCut;
  9351. Item->OnClick = OnBookmarkClick;
  9352. Item->Tag = reinterpret_cast<int>(Bookmark);
  9353. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  9354. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  9355. {
  9356. // No hint for location profiles that are actually mere "bookmarks"
  9357. }
  9358. else
  9359. {
  9360. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  9361. UnicodeString LongHint;
  9362. if (!Bookmark->Local.IsEmpty())
  9363. {
  9364. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  9365. }
  9366. if (!Bookmark->Remote.IsEmpty())
  9367. {
  9368. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  9369. }
  9370. AddToList(Hint, LongHint, L"|");
  9371. Item->Hint = Hint;
  9372. }
  9373. Parent->Add(Item.release());
  9374. }
  9375. }
  9376. AddMenuSeparator(Menu);
  9377. }
  9378. }
  9379. //---------------------------------------------------------------------------
  9380. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  9381. {
  9382. Menu->Clear();
  9383. std::unique_ptr<TTBCustomItem> Item;
  9384. Item.reset(new TTBXItem(Owner));
  9385. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  9386. Item->Options = Item->Options << tboDefault;
  9387. Menu->Add(Item.release());
  9388. AddMenuSeparator(Menu);
  9389. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  9390. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  9391. Item.reset(new TTBXItem(Owner));
  9392. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction : NonVisualDataModule->RemoteAddBookmarkAction;
  9393. Menu->Add(Item.release());
  9394. }
  9395. //---------------------------------------------------------------------------
  9396. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  9397. {
  9398. bool Result = true;
  9399. try
  9400. {
  9401. if (Side == osRemote)
  9402. {
  9403. Terminal->ExceptionOnFail = true;
  9404. }
  9405. try
  9406. {
  9407. DirView(Side)->Path = Path;
  9408. }
  9409. __finally
  9410. {
  9411. if (Side == osRemote)
  9412. {
  9413. Terminal->ExceptionOnFail = false;
  9414. }
  9415. }
  9416. }
  9417. catch (Exception & E)
  9418. {
  9419. if ((Side != osRemote) || Terminal->Active)
  9420. {
  9421. ShowExtendedExceptionEx(Terminal, &E);
  9422. Result = false;
  9423. }
  9424. else
  9425. {
  9426. throw;
  9427. }
  9428. }
  9429. return Result;
  9430. }
  9431. //---------------------------------------------------------------------------
  9432. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  9433. {
  9434. // Make sure there some feedback even when loading tine local folders
  9435. TInstantOperationVisualizer Visualizer;
  9436. DirView(Side)->ReloadDirectory();
  9437. }
  9438. //---------------------------------------------------------------------------
  9439. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  9440. {
  9441. if (Index == SessionsPageControl->TabIndex)
  9442. {
  9443. CloseSession();
  9444. }
  9445. else
  9446. {
  9447. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  9448. TTerminal * Terminal = GetSessionTabTerminal(TabSheet);
  9449. TTerminalManager * Manager = TTerminalManager::Instance();
  9450. if (!Terminal->Active)
  9451. {
  9452. Manager->FreeTerminal(Terminal);
  9453. }
  9454. else
  9455. {
  9456. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  9457. if (CanCloseQueue(Queue))
  9458. {
  9459. Manager->FreeTerminal(Terminal);
  9460. }
  9461. }
  9462. }
  9463. }
  9464. //---------------------------------------------------------------------------
  9465. void __fastcall TCustomScpExplorerForm::SessionsPageControlCloseButtonClick(TPageControl * /*Sender*/, int Index)
  9466. {
  9467. CloseSessionTab(Index);
  9468. }
  9469. //---------------------------------------------------------------------------
  9470. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side)
  9471. {
  9472. if (DebugAlwaysTrue(GetSide(Side) == osRemote))
  9473. {
  9474. TInstantOperationVisualizer Visualizer;
  9475. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  9476. // before we create a new data object
  9477. ClipboardClear();
  9478. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  9479. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  9480. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  9481. FClipboardFakeMonitors.reset(StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated));
  9482. if (FClipboardDragDropFilesEx.get() == NULL)
  9483. {
  9484. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  9485. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  9486. }
  9487. FClipboardDragDropFilesEx->FileList->Clear();
  9488. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  9489. FClipboardDragDropFilesEx->CopyToClipboard();
  9490. FClipboardTerminal = FTerminal;
  9491. // Need full paths, as cwd can be different once files are pasted
  9492. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(false, true)));
  9493. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  9494. {
  9495. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  9496. }
  9497. }
  9498. }
  9499. //---------------------------------------------------------------------------
  9500. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  9501. {
  9502. if (OpenClipboard(0))
  9503. {
  9504. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  9505. CloseClipboard();
  9506. }
  9507. }
  9508. //---------------------------------------------------------------------------
  9509. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  9510. {
  9511. return !FClipboardFakeDirectory.IsEmpty();
  9512. }
  9513. //---------------------------------------------------------------------------
  9514. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  9515. {
  9516. RemoveDir(ApiPath(FClipboardFakeDirectory));
  9517. FClipboardFakeDirectory = UnicodeString();
  9518. FClipboardTerminal = NULL;
  9519. // Also called in Idle()
  9520. FClipboardFakeMonitors.reset(NULL);
  9521. }
  9522. //---------------------------------------------------------------------------
  9523. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  9524. {
  9525. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  9526. {
  9527. ClipboardStop();
  9528. }
  9529. }
  9530. //---------------------------------------------------------------------------
  9531. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  9532. {
  9533. TTerminalManager * Manager = TTerminalManager::Instance();
  9534. Manager->ActiveTerminal = FClipboardTerminal;
  9535. TTransferOperationParam Params;
  9536. Params.TargetDirectory = TargetDirectory;
  9537. Params.DragDrop = DragDrop;
  9538. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  9539. }
  9540. //---------------------------------------------------------------------------
  9541. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  9542. {
  9543. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  9544. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  9545. {
  9546. RemoveDir(ApiPath(FileName));
  9547. if (!NonVisualDataModule->Busy)
  9548. {
  9549. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  9550. ClipboardDownload(ExtractFilePath(FileName), NoConfirmation, true);
  9551. }
  9552. }
  9553. }
  9554. //---------------------------------------------------------------------------
  9555. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  9556. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  9557. {
  9558. TFileMasks::TParams MaskParams;
  9559. MaskParams.Size = Size;
  9560. MaskParams.Modification = Modification;
  9561. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  9562. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  9563. {
  9564. bool ImplicitMatch;
  9565. if (Iter->FileMask.Matches(FileName, Directory, DirView->PathName, &MaskParams, false, ImplicitMatch) &&
  9566. !ImplicitMatch)
  9567. {
  9568. Color = Iter->Color;
  9569. break;
  9570. }
  9571. }
  9572. }
  9573. //---------------------------------------------------------------------------