1
0

CustomScpExplorer.cpp 417 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384
  1. //---------------------------------------------------------------------------
  2. #include <WinPCH.h>
  3. #pragma hdrstop
  4. #include "CustomScpExplorer.h"
  5. #include <Bookmarks.h>
  6. #include <FileSystems.h>
  7. #include <Progress.h>
  8. #include <SynchronizeProgress.h>
  9. #include <DragExt.h>
  10. #include <WinApi.h>
  11. #include "NonVisual.h"
  12. #include "Glyphs.h"
  13. #include "TerminalManager.h"
  14. #include "EditorManager.h"
  15. #include "ProgParams.h"
  16. #include "Setup.h"
  17. #include <TB2Common.hpp>
  18. #include <DirectoryMonitor.hpp>
  19. #include <mmsystem.h>
  20. //---------------------------------------------------------------------------
  21. #pragma link "CustomDirView"
  22. #pragma link "CustomUnixDirView"
  23. #pragma link "IEListView"
  24. #pragma link "NortonLikeListView"
  25. #pragma link "UnixDirView"
  26. #pragma link "CustomDriveView"
  27. #pragma link "UnixDriveView"
  28. #pragma link "CustomDriveView"
  29. #pragma link "TB2Dock"
  30. #pragma link "TBXStatusBars"
  31. #pragma link "TB2Item"
  32. #pragma link "TB2Toolbar"
  33. #pragma link "ThemePageControl"
  34. #pragma link "PathLabel"
  35. #pragma resource "*.dfm"
  36. //---------------------------------------------------------------------------
  37. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  38. #define WM_PASTE_FILES (WM_WINSCP_USER + 14)
  39. static const int SessionPanelCount = 3;
  40. //---------------------------------------------------------------------------
  41. class TMutexGuard
  42. {
  43. public:
  44. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  45. int Timeout = 5000)
  46. {
  47. FMutex = NULL;
  48. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  49. if (WaitResult == WAIT_TIMEOUT)
  50. {
  51. throw Exception(LoadStr(Message));
  52. }
  53. else
  54. {
  55. FMutex = AMutex;
  56. }
  57. }
  58. ~TMutexGuard()
  59. {
  60. if (FMutex != NULL)
  61. {
  62. ReleaseMutex(FMutex);
  63. }
  64. }
  65. private:
  66. HANDLE FMutex;
  67. };
  68. //---------------------------------------------------------------------------
  69. class TWindowLock
  70. {
  71. public:
  72. TWindowLock(TCustomScpExplorerForm * Form) :
  73. FForm(Form)
  74. {
  75. FForm->LockWindow();
  76. }
  77. ~TWindowLock()
  78. {
  79. FForm->UnlockWindow();
  80. }
  81. private:
  82. TCustomScpExplorerForm * FForm;
  83. };
  84. //---------------------------------------------------------------------------
  85. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  86. FForm(Form)
  87. {
  88. FForm->BatchStart(FBatchStorage);
  89. }
  90. //---------------------------------------------------------------------------
  91. TAutoBatch::~TAutoBatch()
  92. {
  93. FForm->BatchEnd(FBatchStorage);
  94. }
  95. //---------------------------------------------------------------------------
  96. struct TTransferOperationParam
  97. {
  98. TTransferOperationParam();
  99. UnicodeString TargetDirectory;
  100. bool Temp;
  101. bool DragDrop;
  102. int Options;
  103. TAutoSwitch Queue;
  104. };
  105. //---------------------------------------------------------------------------
  106. TTransferOperationParam::TTransferOperationParam()
  107. {
  108. Temp = false;
  109. DragDrop = false;
  110. Options = 0;
  111. Queue = asAuto;
  112. }
  113. //---------------------------------------------------------------------------
  114. class TTransferPresetNoteData : public TObject
  115. {
  116. public:
  117. UnicodeString Message;
  118. };
  119. //---------------------------------------------------------------------------
  120. class TTerminalNoteData : public TObject
  121. {
  122. public:
  123. TManagedTerminal * Terminal;
  124. };
  125. //---------------------------------------------------------------------------
  126. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  127. TForm(Owner),
  128. FFormRestored(false)
  129. {
  130. AddStartupSequence(L"F");
  131. FInvalid = false;
  132. FCurrentSide = osRemote;
  133. FEverShown = false;
  134. FDocks = new TList();
  135. InitControls();
  136. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  137. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  138. NonVisualDataModule->ScpExplorer = this;
  139. RestoreParams();
  140. ConfigurationChanged();
  141. RemoteDirView->Invalidate();
  142. FAutoOperation = false;
  143. FOnFileOperationFinished = NULL;
  144. FPrimaryOperation = foNone;
  145. FForceExecution = false;
  146. FIgnoreNextDialogChar = 0;
  147. FErrorList = NULL;
  148. FSynchronizeProgressForm = NULL;
  149. FProgressForm = NULL;
  150. FRefreshLocalDirectory = false;
  151. FRefreshRemoteDirectory = false;
  152. FDDExtMapFile = NULL;
  153. // CreateMutexW keeps failing with ERROR_NOACCESS
  154. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  155. DebugAssert(FDDExtMutex != NULL);
  156. FDDTargetControl = NULL;
  157. FDelayedDeletionTimer = NULL;
  158. FDelayedDeletionList = new TStringList();
  159. FDDFileList = NULL;
  160. FPendingTempSpaceWarn = false;
  161. FCapturedLog = NULL;
  162. FDragDropOperation = false;
  163. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  164. FAllowTransferPresetAutoSelect = true;
  165. FSessionChanging = false;
  166. FCopyParamDefault = L"";
  167. FSynchronizeController = NULL;
  168. FPendingQueueActionItem = NULL;
  169. FLockLevel = 0;
  170. FLockSuspendLevel = 0;
  171. FDisabledOnLockSuspend = false;
  172. FAlternativeDelete = false;
  173. FTrayIcon = new ::TTrayIcon(0);
  174. FTrayIcon->OnClick = TrayIconClick;
  175. FMaxQueueLength = 0;
  176. FLastContextPopupScreenPoint = TPoint(-1, -1);
  177. FTransferResumeList = NULL;
  178. FDeletedFiles = NULL;
  179. FMoveToQueue = false;
  180. StandaloneOperation = false;
  181. FOnFeedSynchronizeError = NULL;
  182. FOnSynchronizeAbort = NULL;
  183. FSynchronizeTerminal = NULL;
  184. FNeedSession = false;
  185. FDoNotIdleCurrentTerminal = 0;
  186. FIncrementalSearching = 0;
  187. FQueueFileList.reset(new TQueueFileList());
  188. FProgressSide = osCurrent;
  189. FCalculateSizeOperation = NULL;
  190. FDownloadingFromClipboard = false;
  191. FClipboardFakeMonitorsPendingReset = false;
  192. FHiContrastTheme = NULL;
  193. InitializeRemoteThumbnailMask();
  194. GlyphsModule->PixelsPerInch = CurrentPPI;
  195. FEditorManager = new TEditorManager();
  196. FEditorManager->OnFileChange = ExecutedFileChanged;
  197. FEditorManager->OnFileReload = ExecutedFileReload;
  198. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  199. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  200. FLocalEditors = new TList();
  201. FQueueStatus = NULL;
  202. FQueueStatusSection = new TCriticalSection();
  203. FQueueStatusInvalidated = false;
  204. FQueueItemInvalidated = false;
  205. FQueueStatusUpdating = false;
  206. FQueueActedItem = NULL;
  207. FQueueController = new TQueueController(QueueView3);
  208. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  209. FUserActionTimer = new TTimer(this);
  210. FUserActionTimer->Enabled = false;
  211. FUserActionTimer->Interval = 10;
  212. FUserActionTimer->OnTimer = UserActionTimer;
  213. FNotes = new TStringList();
  214. FNoteTimer = new TTimer(this);
  215. FNoteTimer->Enabled = false;
  216. FNoteTimer->OnTimer = NoteTimer;
  217. FOnNoteClick = NULL;
  218. FOle32Library = LoadLibrary(L"Ole32.dll");
  219. FDragMoveCursor = FOle32Library != NULL ?
  220. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  221. UseSystemSettings(this);
  222. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  223. static_cast<TObject*>(GetComponent(fcTransferList)));
  224. DebugAssert(TransferList != NULL);
  225. FTransferListHoverIndex = -1;
  226. TransferList->OnChange = TransferListChange;
  227. TransferList->OnDrawItem = TransferListDrawItem;
  228. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  229. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  230. UseDesktopFont(SessionsPageControl);
  231. UseDesktopFont(RemoteDirView);
  232. UseDesktopFont(RemoteDriveView);
  233. UseDesktopFont(QueueView3);
  234. UseDesktopFont(QueueFileList);
  235. UseDesktopFont(QueueLabel);
  236. UseDesktopFont(RemoteStatusBar);
  237. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  238. QueueSplitter->ShowHint = true;
  239. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  240. QueueFileListSplitter->ShowHint = true;
  241. RemotePanelSplitter->ShowHint = true;
  242. UpdateImages();
  243. FCustomCommandMenu = CreateTBXPopupMenu(this);
  244. FCustomCommandLocalFileList = NULL;
  245. FCustomCommandRemoteFileList = NULL;
  246. FSessionColors = new TPngImageList(this);
  247. FSessionColors->ColorDepth = cd32Bit;
  248. AddFixedSessionImages();
  249. SessionsPageControl->Images = FSessionColors;
  250. // Needed for Explorer (Commander calls it implicitly on its own)
  251. UpdateSessionsPageControlHeight();
  252. UpdateQueueLabel();
  253. CheckStoreTransition();
  254. CreateHiddenWindow();
  255. StartUpdates();
  256. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  257. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  258. DriveInfo->NeedData();
  259. UsesCustomColorMode(this);
  260. }
  261. //---------------------------------------------------------------------------
  262. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  263. {
  264. AppLog(L"Destroying main window");
  265. FInvalid = true;
  266. ReleaseHiContrastTheme();
  267. if (FClipboardTerminal != NULL)
  268. {
  269. ClipboardClear(); // implies ClipboardStop
  270. }
  271. // this has to be one of the very first things to do
  272. StopUpdateThread();
  273. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  274. TTerminalManager::Instance()->ScpExplorer = NULL;
  275. delete FCustomCommandLocalFileList;
  276. delete FCustomCommandRemoteFileList;
  277. delete FCustomCommandMenu;
  278. delete FTrayIcon;
  279. FTrayIcon = NULL;
  280. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  281. delete FEditorManager;
  282. ForceCloseLocalEditors();
  283. delete FLocalEditors;
  284. HideFileFindDialog();
  285. if (FDelayedDeletionTimer)
  286. {
  287. DoDelayedDeletion(NULL);
  288. SAFE_DESTROY(FDelayedDeletionTimer);
  289. }
  290. SAFE_DESTROY(FDelayedDeletionList);
  291. // sometimes we do not get DDEnd so the list is not released
  292. SAFE_DESTROY(FDDFileList);
  293. DebugAssert(FSynchronizeController == NULL);
  294. CloseHandle(FDDExtMutex);
  295. FDDExtMutex = NULL;
  296. FreeLibrary(FOle32Library);
  297. FOle32Library = NULL;
  298. FDragMoveCursor = NULL;
  299. DebugAssert(!FErrorList);
  300. if (FEverShown)
  301. {
  302. // when window is never shown (like when running command-line operation),
  303. // particularly window site is not restored correctly (BoundsRect value set
  304. // in RestoreForm gets lost during handle allocation), so we do not want
  305. // it to be stored
  306. AppLog(L"Storing main window configuration");
  307. StoreParams();
  308. }
  309. ManagedSession = NULL;
  310. Queue = NULL;
  311. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  312. NonVisualDataModule->ScpExplorer = NULL;
  313. delete FQueueScrollOnDragOver;
  314. FQueueScrollOnDragOver = 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 SessionListChanged => ... => 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. AppLog(L"Main window destroyed");
  341. }
  342. //---------------------------------------------------------------------------
  343. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  344. {
  345. if (FHiContrastTheme != NULL)
  346. {
  347. ReleaseTBXTheme(FHiContrastTheme);
  348. FHiContrastTheme = NULL;
  349. }
  350. }
  351. //---------------------------------------------------------------------------
  352. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  353. {
  354. std::unique_ptr<TSessionData> Data;
  355. if (!Session.IsEmpty())
  356. {
  357. bool DefaultsOnly;
  358. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  359. }
  360. TTerminalManager * Manager = TTerminalManager::Instance();
  361. for (int Index = 0; Index < Manager->Count; Index++)
  362. {
  363. TTerminal * Terminal = Manager->Sessions[Index];
  364. if (Session.IsEmpty() ||
  365. Manager->IsAvailableTerminalForSite(Terminal, Data.get()))
  366. {
  367. if (Path.IsEmpty())
  368. {
  369. Terminal->ClearCaches();
  370. }
  371. else
  372. {
  373. Terminal->DirectoryModified(Path, true);
  374. }
  375. }
  376. }
  377. // We should flag a pending refresh for the background terminals or busy foreground terminals
  378. if (HasAvailableTerminal() &&
  379. CanCommandLineFromAnotherInstance() &&
  380. (Session.IsEmpty() || Manager->IsAvailableTerminalForSite(Terminal, Data.get())) &&
  381. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  382. {
  383. Terminal->ReloadDirectory();
  384. }
  385. }
  386. //---------------------------------------------------------------------------
  387. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  388. {
  389. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  390. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  391. size_t MessageSize = sizeof(TCopyDataMessage);
  392. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  393. if (Result)
  394. {
  395. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  396. Result = (Message.Version == TCopyDataMessage::Version1);
  397. if (Result)
  398. {
  399. switch (Message.Command)
  400. {
  401. case TCopyDataMessage::CommandCanCommandLine:
  402. Result = CanCommandLineFromAnotherInstance();
  403. if (Result)
  404. {
  405. AppLog(L"Can process command-line from other instance");
  406. }
  407. else
  408. {
  409. AppLog(L"Cannot process command-line from other instance");
  410. }
  411. break;
  412. case TCopyDataMessage::CommandCommandLine:
  413. {
  414. UnicodeString CommandLine(Message.Data.CommandLine);
  415. Result = CommandLineFromAnotherInstance(CommandLine);
  416. }
  417. break;
  418. case TCopyDataMessage::RefreshPanel:
  419. RefreshPanel(Message.Data.Refresh.Session, Message.Data.Refresh.Path);
  420. break;
  421. case TCopyDataMessage::MainWindowCheck:
  422. Result = true;
  423. break;
  424. default:
  425. Result = false;
  426. break;
  427. }
  428. }
  429. }
  430. Message.Result = Result ? 1 : 0;
  431. }
  432. //---------------------------------------------------------------------------
  433. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  434. {
  435. WNDCLASS WindowClass = {};
  436. WindowClass.lpfnWndProc = DefWindowProc;
  437. WindowClass.hInstance = HInstance;
  438. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  439. FHiddenWindow = NULL;
  440. if (RegisterClass(&WindowClass))
  441. {
  442. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  443. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  444. }
  445. }
  446. //---------------------------------------------------------------------------
  447. bool __fastcall TCustomScpExplorerForm::CanConsole()
  448. {
  449. return
  450. HasAvailableTerminal() &&
  451. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  452. }
  453. //---------------------------------------------------------------------------
  454. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  455. {
  456. bool Result = Visible && !NonVisualDataModule->Busy;
  457. return Result;
  458. }
  459. //---------------------------------------------------------------------------
  460. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  461. const UnicodeString & CommandLine)
  462. {
  463. TProgramParams Params(CommandLine);
  464. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  465. if (Result)
  466. {
  467. NonVisualDataModule->StartBusy();
  468. try
  469. {
  470. // this action is initiated from another process,
  471. // so it's likely that our window is not visible,
  472. // and user won't see what is going on
  473. Application->BringToFront();
  474. // reload sessions as we may be asked to open a session
  475. // just stored by another instance
  476. StoredSessions->Reload();
  477. UnicodeString SessionName = Params.Param[1];
  478. std::unique_ptr<TObjectList> DataList(new TObjectList());
  479. try
  480. {
  481. UnicodeString DownloadFile; // unused
  482. int Flags = GetCommandLineParseUrlFlags(&Params);
  483. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  484. }
  485. catch (EAbort &)
  486. {
  487. // Happens when opening session in PuTTY and in other situations,
  488. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  489. // to process the command-line on its own (or to pass it to yet another instance)
  490. }
  491. if (DataList->Count > 0)
  492. {
  493. TTerminalManager * Manager = TTerminalManager::Instance();
  494. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  495. }
  496. }
  497. __finally
  498. {
  499. NonVisualDataModule->EndBusy();
  500. }
  501. }
  502. return Result;
  503. }
  504. //---------------------------------------------------------------------------
  505. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  506. {
  507. TManagedTerminal * Result;
  508. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  509. {
  510. Result = FManagedSession;
  511. }
  512. else
  513. {
  514. Result = NULL;
  515. }
  516. return Result;
  517. }
  518. //---------------------------------------------------------------------------
  519. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  520. {
  521. if (FManagedSession != value)
  522. {
  523. TWindowLock Lock(this);
  524. SessionChanging();
  525. DoSetManagedSession(value, false);
  526. }
  527. }
  528. //---------------------------------------------------------------------------
  529. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  530. {
  531. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  532. FManagedSession = value;
  533. {
  534. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect, false);
  535. TAutoFlag SessionChangingFlag(FSessionChanging);
  536. SessionChanged(Replace);
  537. }
  538. if (Terminal != NULL)
  539. {
  540. TransferPresetAutoSelect();
  541. }
  542. // Update app and tab titles, prevented above by FSessionChanging.
  543. UpdateControls();
  544. }
  545. //---------------------------------------------------------------------------
  546. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  547. {
  548. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  549. DoSetManagedSession(value, true);
  550. }
  551. //---------------------------------------------------------------------------
  552. void __fastcall TCustomScpExplorerForm::SessionChanging()
  553. {
  554. if (ManagedSession != NULL)
  555. {
  556. UpdateSession(ManagedSession);
  557. }
  558. }
  559. //---------------------------------------------------------------------------
  560. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  561. {
  562. if (ManagedSession != NULL)
  563. {
  564. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  565. }
  566. if (!TTerminalManager::Instance()->Updating)
  567. {
  568. SessionListChanged();
  569. }
  570. if (Terminal != NULL)
  571. {
  572. TObject * State = NULL;
  573. if (WinConfiguration->PreservePanelState)
  574. {
  575. State = Terminal->RemoteExplorerState;
  576. DirView(osRemote)->AnnounceState(State);
  577. }
  578. try
  579. {
  580. if (Replaced)
  581. {
  582. RemoteDirView->ReplaceTerminal(Terminal);
  583. }
  584. else
  585. {
  586. RemoteDirView->Terminal = Terminal;
  587. }
  588. if (Terminal->Active)
  589. {
  590. Terminal->RefreshDirectory();
  591. }
  592. if (State != NULL)
  593. {
  594. DirView(osRemote)->RestoreState(State);
  595. }
  596. }
  597. __finally
  598. {
  599. DirView(osRemote)->AnnounceState(NULL);
  600. }
  601. }
  602. else
  603. {
  604. RemoteDirView->Terminal = NULL;
  605. }
  606. InitStatusBar();
  607. UpdateTransferList();
  608. // Update panels Enable state before refreshing the labels
  609. UpdateControls();
  610. }
  611. //---------------------------------------------------------------------------
  612. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  613. {
  614. if (Queue != value)
  615. {
  616. if (FQueue != NULL)
  617. {
  618. FQueue->OnListUpdate = NULL;
  619. FQueue->OnQueueItemUpdate = NULL;
  620. }
  621. FQueue = value;
  622. if (FQueue != NULL)
  623. {
  624. DebugAssert(FQueue->OnListUpdate == NULL);
  625. FQueue->OnListUpdate = QueueListUpdate;
  626. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  627. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  628. }
  629. QueueChanged();
  630. }
  631. }
  632. //---------------------------------------------------------------------------
  633. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  634. TListItem * Item)
  635. {
  636. if (FQueueActedItem == Item)
  637. {
  638. FQueueActedItem = NULL;
  639. if ((QueueView3->PopupMenu != NULL) &&
  640. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  641. {
  642. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  643. ReleaseCapture();
  644. }
  645. }
  646. if (Item->Data == FPendingQueueActionItem)
  647. {
  648. FPendingQueueActionItem = NULL;
  649. }
  650. }
  651. //---------------------------------------------------------------------------
  652. bool TCustomScpExplorerForm::IsAnythingQueued()
  653. {
  654. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  655. }
  656. //---------------------------------------------------------------------------
  657. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  658. {
  659. {
  660. TGuard Guard(FQueueStatusSection);
  661. FQueueStatusInvalidated = false;
  662. if (FQueue != NULL)
  663. {
  664. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  665. }
  666. }
  667. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  668. {
  669. FMaxQueueLength = FQueueStatus->Count;
  670. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  671. }
  672. {
  673. TAutoFlag Flag(FQueueStatusUpdating);
  674. FQueueController->UpdateQueueStatus(FQueueStatus);
  675. }
  676. UpdateQueueFileList();
  677. SetQueueProgress();
  678. UpdateQueueView();
  679. bool IsEmpty = !IsAnythingQueued();
  680. if (IsEmpty && (Terminal != NULL))
  681. {
  682. TOnceDoneOperation OnceDoneOperation =
  683. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  684. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  685. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  686. {
  687. FQueue->Enabled = false;
  688. }
  689. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  690. {
  691. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  692. }
  693. }
  694. }
  695. //---------------------------------------------------------------------------
  696. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  697. {
  698. UnicodeString Result;
  699. if (FQueueStatus != NULL)
  700. {
  701. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  702. {
  703. TFileOperationProgressType * ProgressData =
  704. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  705. if ((ProgressData != NULL) && ProgressData->InProgress)
  706. {
  707. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  708. }
  709. }
  710. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  711. {
  712. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  713. }
  714. }
  715. return Result;
  716. }
  717. //---------------------------------------------------------------------------
  718. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  719. {
  720. ComponentVisible[fcQueueView] =
  721. !IsLocalBrowserMode() &&
  722. ((WinConfiguration->QueueView.Show == qvShow) ||
  723. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  724. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  725. }
  726. //---------------------------------------------------------------------------
  727. void __fastcall TCustomScpExplorerForm::QueueChanged()
  728. {
  729. if (FQueueStatus != NULL)
  730. {
  731. // UpdateFileList implementation relies on the status being recreated when session changes
  732. delete FQueueStatus;
  733. FQueueStatus = NULL;
  734. }
  735. UpdateQueueStatus(true);
  736. }
  737. //---------------------------------------------------------------------------
  738. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  739. {
  740. if (FQueue == Queue)
  741. {
  742. FQueueStatusInvalidated = true;
  743. }
  744. }
  745. //---------------------------------------------------------------------------
  746. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  747. TQueueItem * Item)
  748. {
  749. if (FQueue == Queue)
  750. {
  751. TGuard Guard(FQueueStatusSection);
  752. // this may be running in parallel with QueueChanged
  753. if (FQueueStatus != NULL)
  754. {
  755. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  756. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  757. {
  758. FRefreshLocalDirectory = (QueueItem == NULL) ||
  759. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  760. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  761. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  762. }
  763. if (QueueItem != NULL)
  764. {
  765. QueueItem->UserData = (void*)true;
  766. FQueueItemInvalidated = true;
  767. }
  768. }
  769. }
  770. }
  771. //---------------------------------------------------------------------------
  772. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  773. {
  774. // during standalone editing, we have no way to see/control queue,
  775. // so we have to always popup prompts automatically
  776. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  777. }
  778. //---------------------------------------------------------------------------
  779. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  780. {
  781. if (FQueueStatus != NULL)
  782. {
  783. bool QueueAutoPopup = IsQueueAutoPopup();
  784. bool NeedRefresh = FQueueController->NeedRefresh();
  785. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  786. FQueueItemInvalidated = false;
  787. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  788. bool Updated = false;
  789. TQueueItemProxy * QueueItem;
  790. bool WasUserAction;
  791. for (int Index = 0; Index < Limit; Index++)
  792. {
  793. bool Update = false;
  794. QueueItem = FQueueStatus->Items[Index];
  795. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  796. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  797. (FPendingQueueActionItem == NULL))
  798. {
  799. FPendingQueueActionItem = QueueItem;
  800. FUserActionTimer->Enabled = true;
  801. }
  802. if ((bool)QueueItem->UserData)
  803. {
  804. QueueItem->UserData = (void*)false;
  805. QueueItem->Update();
  806. Updated = true;
  807. Update = true;
  808. }
  809. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  810. {
  811. Update = true;
  812. }
  813. if (Update)
  814. {
  815. FQueueController->RefreshQueueItem(QueueItem);
  816. }
  817. }
  818. if (Updated)
  819. {
  820. NonVisualDataModule->UpdateNonVisibleActions();
  821. SetQueueProgress();
  822. UpdateQueueFileList();
  823. }
  824. }
  825. }
  826. //---------------------------------------------------------------------------
  827. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  828. {
  829. if (FTaskbarList != NULL)
  830. {
  831. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  832. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  833. }
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  837. {
  838. if (Progress >= 0)
  839. {
  840. if (FTaskbarList != NULL)
  841. {
  842. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  843. }
  844. }
  845. else
  846. {
  847. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  848. }
  849. }
  850. //---------------------------------------------------------------------------
  851. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  852. {
  853. int OverallProgress;
  854. // FProgressForm is null when this is called from SetQueueProgress
  855. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  856. {
  857. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  858. }
  859. else if (!ProgressData->IsIndeterminate())
  860. {
  861. OverallProgress = ProgressData->OverallProgress();
  862. }
  863. else
  864. {
  865. OverallProgress = -1;
  866. }
  867. SetTaskbarListProgressValue(OverallProgress);
  868. }
  869. //---------------------------------------------------------------------------
  870. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  871. {
  872. TTerminalManager::Instance()->QueueStatusUpdated();
  873. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  874. {
  875. // Do not animate task bar button, when items are queued, but processing is disabled
  876. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  877. {
  878. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  879. {
  880. TFileOperationProgressType * ProgressData = NULL;
  881. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  882. {
  883. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  884. }
  885. if ((ProgressData != NULL) &&
  886. ProgressData->InProgress)
  887. {
  888. SetTaskbarListProgressValue(ProgressData);
  889. }
  890. else
  891. {
  892. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  893. }
  894. }
  895. else
  896. {
  897. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  898. }
  899. }
  900. else
  901. {
  902. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  903. }
  904. }
  905. UpdateQueueLabel();
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  909. {
  910. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  911. if (FQueueStatus != NULL)
  912. {
  913. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  914. if (ActiveAndPendingPrimaryCount > 0)
  915. {
  916. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  917. }
  918. }
  919. QueueLabel->Caption = Caption;
  920. }
  921. //---------------------------------------------------------------------------
  922. void TCustomScpExplorerForm::CheckStoreTransition()
  923. {
  924. if (WinConfiguration->StoreTransition == stInit)
  925. {
  926. if (IsUWP())
  927. {
  928. WinConfiguration->StoreTransition = stStoreFresh;
  929. AppLog(L"Fresh UWP/store installation");
  930. }
  931. else
  932. {
  933. WinConfiguration->StoreTransition = stStandard;
  934. AppLog(L"Fresh standard installation");
  935. }
  936. }
  937. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  938. {
  939. WinConfiguration->StoreTransition = stStoreMigrated;
  940. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  941. AppLog(L"Standard installation migrated to store installation");
  942. }
  943. if (WinConfiguration->StoreTransition == stStoreMigrated)
  944. {
  945. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  946. Toolbar->Parent = MessageDock;
  947. Toolbar->FullSize = true;
  948. Toolbar->Color = Application->HintColor;
  949. TTBXLabelItem * LabelItem;
  950. LabelItem = new TTBXLabelItem(Toolbar);
  951. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  952. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  953. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  954. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  955. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  956. Toolbar->Items->Add(LabelItem);
  957. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  958. LinkItem->FontSettings->Color = GetLightLinkColor(); // the background is not themed yet
  959. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  960. LinkItem->OnClick = StoreTransitionLinkClick;
  961. Toolbar->Items->Add(LinkItem);
  962. AddMenuSeparator(Toolbar->Items);
  963. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  964. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  965. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  966. CloseItem->OnClick = StoreTransitionCloseClick;
  967. Toolbar->Items->Add(CloseItem);
  968. GiveTBItemPriority(CloseItem);
  969. }
  970. }
  971. //---------------------------------------------------------------------------
  972. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  973. {
  974. ShowHelp(HELP_STORE_TRANSITION);
  975. }
  976. //---------------------------------------------------------------------------
  977. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  978. {
  979. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  980. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  981. delete Toolbar;
  982. WinConfiguration->StoreTransition = stStoreAcknowledged;
  983. UpdateControls();
  984. }
  985. //---------------------------------------------------------------------------
  986. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  987. {
  988. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  989. static_cast<TComponent*>(GetComponent(fcTransferList)));
  990. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  991. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  992. TransferList->Strings->BeginUpdate();
  993. try
  994. {
  995. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  996. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  997. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  998. if (FTransferDropDownHint.IsEmpty())
  999. {
  1000. FTransferDropDownHint = TransferDropDown->Hint;
  1001. }
  1002. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1003. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1004. TransferDropDown->Text = StripHotkey(Name);
  1005. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1006. (FTransferDropDownHint, StripHotkey(Name),
  1007. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1008. FLAGMASK(HasAvailableTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1009. // update the label, otherwise when it is updated only on the first draw
  1010. // of the list, it is drawn "bold" for some reason
  1011. FTransferListHoverIndex = TransferList->ItemIndex;
  1012. UpdateTransferLabel();
  1013. }
  1014. __finally
  1015. {
  1016. TransferList->Strings->EndUpdate();
  1017. }
  1018. }
  1019. //---------------------------------------------------------------------------
  1020. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1021. {
  1022. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1023. DebugAssert(Toolbar != NULL);
  1024. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1025. }
  1026. //---------------------------------------------------------------------------
  1027. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1028. {
  1029. TForm::UpdateActions();
  1030. if (ComponentVisible[fcCustomCommandsBand])
  1031. {
  1032. UpdateCustomCommandsToolbar();
  1033. }
  1034. }
  1035. //---------------------------------------------------------------------------
  1036. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1037. {
  1038. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1042. {
  1043. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1044. {
  1045. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1046. // Without this, the panel turns gray and unused part of header turns black
  1047. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1048. }
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1052. {
  1053. Color = GetBtnFaceColor();
  1054. DebugAssert(Configuration && RemoteDirView);
  1055. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1056. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1057. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1058. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1059. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1060. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1061. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1062. UpdateRowSelect(RemoteDirView);
  1063. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1064. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1065. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1066. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1067. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1068. UpdateSessionsPageControlHeight();
  1069. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1070. UpdateToolbarDisplayMode();
  1071. UpdateTransferList();
  1072. if (Terminal != NULL)
  1073. {
  1074. TransferPresetAutoSelect();
  1075. }
  1076. UpdateQueueView();
  1077. UpdateControls();
  1078. // this can be called even before constuctor finishes.
  1079. if (FEditorManager != NULL)
  1080. {
  1081. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1082. }
  1083. // this can be called even before constuctor finishes.
  1084. if (FLocalEditors != NULL)
  1085. {
  1086. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1087. {
  1088. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1089. }
  1090. }
  1091. if (ComponentVisible[fcCustomCommandsBand])
  1092. {
  1093. UpdateCustomCommandsToolbar();
  1094. }
  1095. // show only when keeping queue items forever,
  1096. // otherwise, it's enough to have it in the context menu
  1097. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1098. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1099. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1100. {
  1101. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1102. FFileColorsCurrent = WinConfiguration->FileColors;
  1103. FileColorsChanged();
  1104. }
  1105. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1106. (FSessionColors != NULL))
  1107. {
  1108. SessionListChanged();
  1109. }
  1110. if (GlyphsModule->LargerToolbar != WinConfiguration->LargerToolbar)
  1111. {
  1112. GlyphsModule->LargerToolbar = WinConfiguration->LargerToolbar;
  1113. if (FSessionColors != NULL)
  1114. {
  1115. RegenerateSessionColorsImageList();
  1116. UpdateSessionsPageControlHeight();
  1117. }
  1118. }
  1119. }
  1120. //---------------------------------------------------------------------------
  1121. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1122. {
  1123. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1124. DirView->Invalidate();
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1128. {
  1129. DoFileColorsChanged(RemoteDirView);
  1130. }
  1131. //---------------------------------------------------------------------------
  1132. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1133. const UnicodeString DebugUsedArg(FileName), TEditedFileData * /*Data*/, TObject * Token,
  1134. void * /*Arg*/)
  1135. {
  1136. if (Token != NULL)
  1137. {
  1138. TForm * Editor = dynamic_cast<TForm*>(Token);
  1139. DebugAssert(Editor != NULL);
  1140. ReconfigureEditorForm(Editor);
  1141. }
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1145. {
  1146. WinConfiguration->DDTransferConfirmation = asOn;
  1147. }
  1148. //---------------------------------------------------------------------------
  1149. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1150. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1151. {
  1152. // noop
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1156. {
  1157. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1161. {
  1162. if (DoNotShowAgain)
  1163. {
  1164. if (DragDrop)
  1165. {
  1166. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1167. {
  1168. PopupTrayBalloon(
  1169. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1170. }
  1171. WinConfiguration->DDTransferConfirmation = asOff;
  1172. }
  1173. else
  1174. {
  1175. WinConfiguration->ConfirmTransferring = false;
  1176. }
  1177. }
  1178. else
  1179. {
  1180. // User explicitly unchecked "do not show again",
  1181. // so show him the dialog the next time
  1182. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1183. {
  1184. WinConfiguration->DDTransferConfirmation = asOn;
  1185. }
  1186. }
  1187. }
  1188. //---------------------------------------------------------------------------
  1189. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1190. TTransferDirection Direction, TTransferType Type, bool Temp,
  1191. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1192. bool Confirm, bool DragDrop, int Options)
  1193. {
  1194. bool Result = true;
  1195. DebugAssert(HasAvailableTerminal());
  1196. // these parameters are known in advance
  1197. int Params =
  1198. FLAGMASK(Type == ttMove, cpDelete);
  1199. bool ToTemp = (Temp && (Direction == tdToLocal));
  1200. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1201. {
  1202. bool DisableNewerOnly =
  1203. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1204. ToTemp;
  1205. Options |=
  1206. FLAGMASK(ToTemp, coTemp) |
  1207. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1208. coDoNotShowAgain;
  1209. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1210. int CopyParamAttrs = (Direction == tdToRemote ?
  1211. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1212. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1213. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1214. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1215. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1216. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1217. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1218. if (Result)
  1219. {
  1220. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1221. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1222. }
  1223. }
  1224. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1225. {
  1226. Configuration->Usage->Inc(L"TransfersOnBackground");
  1227. // these parameter are known only after transfer dialog
  1228. Params |=
  1229. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1230. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1231. Result = false;
  1232. ClearTransferSourceSelection(Direction);
  1233. }
  1234. return Result;
  1235. }
  1236. //---------------------------------------------------------------------------
  1237. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1238. {
  1239. if (FOnFileOperationFinished != NULL)
  1240. {
  1241. FOnFileOperationFinished(Side, UnicodeString(), true, true);
  1242. }
  1243. else
  1244. {
  1245. if (HasDirView[Side])
  1246. {
  1247. DirView(Side)->SelectAll(smNone);
  1248. }
  1249. }
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1253. {
  1254. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1255. ClearOperationSelection(Side);
  1256. }
  1257. //---------------------------------------------------------------------------
  1258. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1259. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1260. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1261. int Params)
  1262. {
  1263. DebugAssert(Queue != NULL);
  1264. TQueueItem * QueueItem;
  1265. if (Direction == tdToRemote)
  1266. {
  1267. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1268. QueueItem =
  1269. new TUploadQueueItem(
  1270. Terminal, FileList, TargetDirectory, &CopyParam, Params, CopyParam.QueueParallel);
  1271. }
  1272. else
  1273. {
  1274. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1275. QueueItem =
  1276. new TDownloadQueueItem(
  1277. Terminal, FileList, TargetDirectory, &CopyParam, Params, CopyParam.QueueParallel);
  1278. }
  1279. AddQueueItem(Queue, QueueItem, Terminal);
  1280. }
  1281. //---------------------------------------------------------------------------
  1282. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1283. {
  1284. if (Queue->IsEmpty)
  1285. {
  1286. Terminal->QueueOperationStart = Now();
  1287. }
  1288. Queue->AddItem(QueueItem);
  1289. }
  1290. //---------------------------------------------------------------------------
  1291. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1292. {
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. void __fastcall TCustomScpExplorerForm::InitControls()
  1296. {
  1297. DebugAssert(FDocks != NULL);
  1298. for (int Index = 0; Index < ComponentCount; Index++)
  1299. {
  1300. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1301. if ((Dock != NULL) && (Dock->Tag == 0))
  1302. {
  1303. FDocks->Add(Dock);
  1304. }
  1305. }
  1306. CollectItemsWithTextDisplayMode(this);
  1307. }
  1308. //---------------------------------------------------------------------------
  1309. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1310. {
  1311. ConfigurationChanged();
  1312. QueuePanel->Height =
  1313. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1314. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1315. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1316. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1317. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1318. QueueFileList->Height =
  1319. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1320. if (QueueFileList->Visible)
  1321. {
  1322. AdjustQueueLayout();
  1323. }
  1324. UpdateCustomCommandsToolbar();
  1325. }
  1326. //---------------------------------------------------------------------------
  1327. void __fastcall TCustomScpExplorerForm::StoreParams()
  1328. {
  1329. int APixelsPerInch = GetControlPixelsPerInch(this);
  1330. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1331. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1332. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1333. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1334. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1335. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1336. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1337. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1338. }
  1339. //---------------------------------------------------------------------------
  1340. void __fastcall TCustomScpExplorerForm::Loaded()
  1341. {
  1342. // Loaded is called in more deterministic moment than previously used CreateParams
  1343. if (!FFormRestored)
  1344. {
  1345. FFormRestored = true;
  1346. RestoreFormParams();
  1347. }
  1348. TForm::Loaded();
  1349. }
  1350. //---------------------------------------------------------------------------
  1351. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1352. {
  1353. DebugAssert(FDocks != NULL);
  1354. for (int Index = 0; Index < FDocks->Count; Index++)
  1355. {
  1356. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1357. }
  1358. }
  1359. //---------------------------------------------------------------------------
  1360. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1361. {
  1362. SetDockAllowDrag(true);
  1363. while (!ButtonsStr.IsEmpty())
  1364. {
  1365. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1366. UnicodeString Name = CutToChar(S, L'=', true);
  1367. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1368. {
  1369. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1370. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1371. {
  1372. while (!S.IsEmpty())
  1373. {
  1374. UnicodeString S2 = CutToChar(S, L',', true);
  1375. UnicodeString Name = CutToChar(S2, L':', true);
  1376. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1377. {
  1378. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1379. if (SameText(GetToolbarItemName(Item), Name))
  1380. {
  1381. // forward compatibility
  1382. UnicodeString S3 = CutToChar(S2, L':', true);
  1383. bool Visible = StrToIntDef(S3, 0);
  1384. Item->Visible = Visible;
  1385. }
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1392. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1396. {
  1397. UnicodeString Result;
  1398. SetDockAllowDrag(true);
  1399. Result = ::GetToolbarsLayoutStr(this);
  1400. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1401. return Result;
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1405. {
  1406. UnicodeString Result;
  1407. if (Item->Action != NULL)
  1408. {
  1409. Result = Item->Action->Name;
  1410. Result = RemoveSuffix(Result, L"Action", true);
  1411. }
  1412. else
  1413. {
  1414. Result = Item->Name;
  1415. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1416. Result = RemoveSuffix(Result, L"Item", true);
  1417. }
  1418. return Result;
  1419. }
  1420. //---------------------------------------------------------------------------
  1421. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1422. {
  1423. UnicodeString Result;
  1424. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1425. {
  1426. UnicodeString ToolbarStr;
  1427. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1428. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1429. {
  1430. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1431. {
  1432. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1433. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1434. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1435. // and save the changes here only.
  1436. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1437. {
  1438. UnicodeString Name = GetToolbarItemName(Item);
  1439. DebugAssert(Name.Pos(L"TBX") == 0);
  1440. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1441. }
  1442. }
  1443. }
  1444. if (!ToolbarStr.IsEmpty())
  1445. {
  1446. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1447. }
  1448. }
  1449. return Result;
  1450. }
  1451. //---------------------------------------------------------------------------
  1452. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1453. {
  1454. DebugAssert(FProgressForm == NULL);
  1455. bool AllowSkip = HasAvailableTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1456. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1457. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1458. FProgressForm->DeleteLocalToRecycleBin =
  1459. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1460. FProgressForm->DeleteRemoteToRecycleBin =
  1461. HasAvailableTerminal() &&
  1462. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1463. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1464. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1465. LockWindow();
  1466. // Actually, do not know what hides the progress once the operation finishes
  1467. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1468. SetTaskbarListProgressState(TBPF_NORMAL);
  1469. }
  1470. //---------------------------------------------------------------------------
  1471. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1472. {
  1473. UnlockWindow();
  1474. SAFE_DESTROY(FProgressForm);
  1475. SetQueueProgress();
  1476. }
  1477. //---------------------------------------------------------------------------
  1478. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1479. TFileOperationProgressType & ProgressData)
  1480. {
  1481. // Download to temporary local directory
  1482. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1483. {
  1484. bool Continue = true;
  1485. FPendingTempSpaceWarn = false;
  1486. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1487. if (!Continue)
  1488. {
  1489. Abort();
  1490. }
  1491. }
  1492. // operation is being executed and we still didn't show up progress form
  1493. if (ProgressData.InProgress && !FProgressForm)
  1494. {
  1495. CreateProgressForm(NULL);
  1496. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1497. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1498. }
  1499. // operation is finished (or terminated), so we hide progress form
  1500. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1501. {
  1502. DestroyProgressForm();
  1503. if (ProgressData.Operation == foCalculateSize)
  1504. {
  1505. // When calculating size before transfer, the abort caused by
  1506. // cancel flag set due to "MoveToQueue" below,
  1507. // is not propagated back to us in ExecuteFileOperation,
  1508. // as it is silently swallowed.
  1509. // So we explicitly (re)throw it here.
  1510. if (FMoveToQueue)
  1511. {
  1512. Abort();
  1513. }
  1514. }
  1515. else
  1516. {
  1517. if ((ProgressData.Cancel == csContinue) &&
  1518. !FAutoOperation)
  1519. {
  1520. OperationComplete(ProgressData.StartTime);
  1521. }
  1522. }
  1523. }
  1524. if (FProgressForm &&
  1525. // Can happen only during synchronization, when ending one of the operations
  1526. ProgressData.InProgress)
  1527. {
  1528. FProgressForm->SetProgressData(ProgressData);
  1529. DebugAssert(ProgressData.InProgress);
  1530. SetTaskbarListProgressValue(&ProgressData);
  1531. if (FProgressForm->Cancel > csContinue)
  1532. {
  1533. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1534. if (FProgressForm->Cancel == csCancelFile)
  1535. {
  1536. FProgressForm->ClearCancel();
  1537. }
  1538. // cancel cancels even the move
  1539. FMoveToQueue = false;
  1540. }
  1541. else if (FProgressForm->MoveToQueue)
  1542. {
  1543. FMoveToQueue = true;
  1544. ProgressData.SetCancelAtLeast(csCancel);
  1545. }
  1546. if ((FTransferResumeList != NULL) &&
  1547. ProgressData.InProgress &&
  1548. ProgressData.IsTransfer() &&
  1549. !ProgressData.FullFileName.IsEmpty())
  1550. {
  1551. if ((FTransferResumeList->Count == 0) ||
  1552. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1553. {
  1554. // note that we do not recognize directories from files here
  1555. FTransferResumeList->Add(ProgressData.FullFileName);
  1556. }
  1557. }
  1558. }
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1562. const TDateTime & StartTime)
  1563. {
  1564. if (GUIConfiguration->BeepOnFinish &&
  1565. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1566. {
  1567. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1568. DWORD Sound;
  1569. if (!ExtractFileExt(BeepSound).IsEmpty())
  1570. {
  1571. Sound = SND_FILENAME;
  1572. }
  1573. else
  1574. {
  1575. Sound = SND_ALIAS;
  1576. }
  1577. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1578. }
  1579. }
  1580. //---------------------------------------------------------------------------
  1581. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1582. TFileOperationProgressType & ProgressData)
  1583. {
  1584. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1585. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1586. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1587. FileOperationProgress(ProgressData);
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1591. {
  1592. UnicodeString Result;
  1593. if (FProgressForm != NULL)
  1594. {
  1595. Result = FProgressForm->ProgressStr();
  1596. }
  1597. return Result;
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1601. bool DragDrop)
  1602. {
  1603. return (!DragDrop && (DropSourceControl == NULL)) ||
  1604. (DropSourceControl == DirView(osOther));
  1605. }
  1606. //---------------------------------------------------------------------------
  1607. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1608. {
  1609. TCustomDirView * ADirView = DirView(Side);
  1610. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1611. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1612. // this can happen when local drive is unplugged in the middle of the operation
  1613. if (Item != NULL)
  1614. {
  1615. if (Unselect)
  1616. {
  1617. Item->Selected = false;
  1618. }
  1619. ADirView->MakeProgressVisible(Item);
  1620. }
  1621. return Item;
  1622. }
  1623. //---------------------------------------------------------------------------
  1624. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1625. TFileOperation Operation, TOperationSide Side,
  1626. bool /*Temp*/, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1627. TOnceDoneOperation & OnceDoneOperation)
  1628. {
  1629. if (!FAutoOperation)
  1630. {
  1631. // no selection on "/upload", form serves only as event handler
  1632. // (it is not displayed)
  1633. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1634. ((Operation == FPrimaryOperation) ||
  1635. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1636. {
  1637. TOperationSide DViewSide;
  1638. if ((FProgressSide != osCurrent) &&
  1639. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1640. {
  1641. // assume the operation is over the focused panel
  1642. DViewSide = FProgressSide;
  1643. }
  1644. else
  1645. {
  1646. DViewSide = Side;
  1647. }
  1648. if (FOnFileOperationFinished != NULL)
  1649. {
  1650. FOnFileOperationFinished(DViewSide, FileName, Success, NotCancelled);
  1651. }
  1652. else
  1653. {
  1654. VisualiseOperationFinished(DViewSide, FileName, Success && NotCancelled);
  1655. }
  1656. }
  1657. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1658. {
  1659. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1660. {
  1661. if (Side == osLocal)
  1662. {
  1663. Configuration->Usage->Inc(L"UploadedFiles");
  1664. }
  1665. else
  1666. {
  1667. Configuration->Usage->Inc(L"DownloadedFiles");
  1668. }
  1669. }
  1670. }
  1671. }
  1672. if (Success && (FSynchronizeController != NULL))
  1673. {
  1674. DebugAssert(!IsSideLocalBrowser(osRemote));
  1675. if (Operation == foCopy)
  1676. {
  1677. DebugAssert(Side == osLocal);
  1678. FSynchronizeController->LogOperation(soUpload, FileName);
  1679. }
  1680. else if (Operation == foDelete)
  1681. {
  1682. DebugAssert(Side == osRemote);
  1683. FSynchronizeController->LogOperation(soDelete, FileName);
  1684. }
  1685. }
  1686. if (FProgressForm)
  1687. {
  1688. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1689. }
  1690. }
  1691. //---------------------------------------------------------------------------
  1692. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1693. TFileOperation Operation, TOperationSide Side,
  1694. bool Temp, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1695. TOnceDoneOperation & OnceDoneOperation)
  1696. {
  1697. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1698. DoOperationFinished(Operation, Side, Temp, FileName, Success, NotCancelled, OnceDoneOperation);
  1699. }
  1700. //---------------------------------------------------------------------------
  1701. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1702. {
  1703. return false;
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1707. {
  1708. return false;
  1709. }
  1710. //---------------------------------------------------------------------------
  1711. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1712. {
  1713. return false;
  1714. }
  1715. //---------------------------------------------------------------------------
  1716. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1717. {
  1718. return NULL;
  1719. }
  1720. //---------------------------------------------------------------------------
  1721. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1722. {
  1723. DebugAssert(GetSide(Side) == osRemote);
  1724. DebugUsedParam(Side);
  1725. return RemoteDirView;
  1726. }
  1727. //---------------------------------------------------------------------------
  1728. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1729. {
  1730. DebugAssert(GetSide(Side) == osRemote);
  1731. DebugUsedParam(Side);
  1732. return RemoteDriveView;
  1733. }
  1734. //---------------------------------------------------------------------------
  1735. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1736. {
  1737. DebugAssert(GetSide(Side) == osRemote);
  1738. DebugUsedParam(Side);
  1739. return HasAvailableTerminal();
  1740. }
  1741. //---------------------------------------------------------------------------
  1742. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1743. TOperationSide Side, int FilesOnly)
  1744. {
  1745. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1746. }
  1747. //---------------------------------------------------------------------------
  1748. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1749. TOperationSide Side, int FilesOnly)
  1750. {
  1751. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1752. }
  1753. //---------------------------------------------------------------------------
  1754. struct THistoryItemData
  1755. {
  1756. short int Side;
  1757. short int Index;
  1758. };
  1759. //---------------------------------------------------------------------------
  1760. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1761. {
  1762. DirView(Side)->HistoryGo(Index);
  1763. }
  1764. //---------------------------------------------------------------------------
  1765. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1766. {
  1767. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1768. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1769. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1770. }
  1771. //---------------------------------------------------------------------------
  1772. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1773. bool Back)
  1774. {
  1775. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1776. {
  1777. TCustomDirView * DView = DirView(Side);
  1778. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1779. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1780. if (ICount > 10)
  1781. {
  1782. ICount = 10;
  1783. }
  1784. Menu->Items->Clear();
  1785. THistoryItemData Data;
  1786. Data.Side = Side;
  1787. for (short int i = 1; i <= ICount; i++)
  1788. {
  1789. TTBCustomItem * Item = new TTBXItem(Menu);
  1790. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1791. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1792. Item->Hint = DView->HistoryPath[Data.Index];
  1793. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1794. Item->Tag = *reinterpret_cast<int*>(&Data);
  1795. Item->OnClick = HistoryItemClick;
  1796. Menu->Items->Add(Item);
  1797. }
  1798. }
  1799. }
  1800. //---------------------------------------------------------------------------
  1801. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1802. TOperationSide Side, bool Back)
  1803. {
  1804. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1805. {
  1806. // workaround
  1807. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1808. // operator new allocates memory in Pascal code, but calls inline
  1809. // constructor in C++, leading in problems, the function does
  1810. // both in Pascal code
  1811. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1812. UpdateHistoryMenu(Side, Back);
  1813. }
  1814. return FHistoryMenu[Side == osLocal][Back];
  1815. }
  1816. //---------------------------------------------------------------------------
  1817. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1818. TCustomDirView *Sender)
  1819. {
  1820. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1821. UpdateHistoryMenu(Side, true);
  1822. UpdateHistoryMenu(Side, false);
  1823. }
  1824. //---------------------------------------------------------------------------
  1825. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1826. {
  1827. // remote custom commands can be executed only if the server supports shell commands
  1828. // or have secondary shell
  1829. return HasAvailableTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1830. }
  1831. //---------------------------------------------------------------------------
  1832. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1833. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1834. {
  1835. // -1 = hidden, 0 = disabled, 1 = enabled
  1836. int Result;
  1837. TFileCustomCommand RemoteCustomCommand;
  1838. TLocalCustomCommand LocalCustomCommand;
  1839. TFileCustomCommand * NonInteractiveCustomCommand =
  1840. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1841. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1842. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1843. if (FLAGCLEAR(Command.Params, ccLocal))
  1844. {
  1845. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1846. // custom command that does not operate with files can be executed anytime ...
  1847. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1848. {
  1849. // ... but do not show such command in remote file menu
  1850. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1851. {
  1852. Result = AllowedState;
  1853. }
  1854. else
  1855. {
  1856. Result = -1;
  1857. }
  1858. }
  1859. else
  1860. {
  1861. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1862. {
  1863. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1864. }
  1865. else
  1866. {
  1867. Result = -1;
  1868. }
  1869. }
  1870. }
  1871. else
  1872. {
  1873. // custom command that does not operate with files can be executed anytime
  1874. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1875. {
  1876. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1877. }
  1878. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1879. {
  1880. if ((ListType == ccltAll) || (ListType == ccltFile))
  1881. {
  1882. // special case is "diff"-style command that can be executed over any side,
  1883. // if we have both sides
  1884. Result =
  1885. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1886. // directly (instead of EnableSelectedOperation) to pass
  1887. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1888. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1889. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1890. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1891. }
  1892. else if (ListType == ccltBoth)
  1893. {
  1894. DebugAssert(!IsLocalBrowserMode());
  1895. Result = 1;
  1896. }
  1897. else
  1898. {
  1899. Result = -1;
  1900. }
  1901. }
  1902. else
  1903. {
  1904. if ((ListType == ccltAll) ||
  1905. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1906. {
  1907. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1908. }
  1909. else
  1910. {
  1911. Result = -1;
  1912. }
  1913. }
  1914. if ((Result > 0) &&
  1915. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1916. !HasAvailableTerminal())
  1917. {
  1918. Result = 0;
  1919. }
  1920. }
  1921. return Result;
  1922. }
  1923. //---------------------------------------------------------------------------
  1924. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1925. TStrings * FileList, const TCustomCommandType & ACommand,
  1926. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1927. {
  1928. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1929. {
  1930. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1931. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1932. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1933. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1934. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1935. bool Capture =
  1936. FLAGSET(ACommand.Params, ccShowResults) ||
  1937. FLAGSET(ACommand.Params, ccCopyResults) ||
  1938. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1939. TCaptureOutputEvent OutputEvent = NULL;
  1940. DebugAssert(FCapturedLog == NULL);
  1941. TObjectReleaser<TStrings> CapturedLogReleaser(FCapturedLog);
  1942. if (Capture)
  1943. {
  1944. CapturedLogReleaser.Set(new TStringList());
  1945. OutputEvent = TerminalCaptureLog;
  1946. }
  1947. if (!RemoteCustomCommand.IsFileCommand(Command))
  1948. {
  1949. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1950. OutputEvent);
  1951. }
  1952. else
  1953. {
  1954. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1955. }
  1956. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1957. {
  1958. if (FLAGSET(ACommand.Params, ccCopyResults))
  1959. {
  1960. CopyToClipboard(FCapturedLog);
  1961. }
  1962. if (FLAGSET(ACommand.Params, ccShowResults))
  1963. {
  1964. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1965. }
  1966. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1967. {
  1968. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. //---------------------------------------------------------------------------
  1974. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1975. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1976. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1977. {
  1978. DebugAssert(!IsLocalBrowserMode());
  1979. TStrings * LocalFileList = NULL;
  1980. TStrings * RemoteFileList = NULL;
  1981. TStrings * RemoteFileListFull = NULL;
  1982. try
  1983. {
  1984. if (LocalFileCommand)
  1985. {
  1986. if (ALocalFileList == NULL)
  1987. {
  1988. DebugAssert(HasDirView[osLocal]);
  1989. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1990. // directly (instead of EnableSelectedOperation) to pass
  1991. // false to FocusedFileOnlyWhenFocused
  1992. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1993. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1994. }
  1995. else
  1996. {
  1997. LocalFileList = ALocalFileList;
  1998. }
  1999. if (FileListCommand)
  2000. {
  2001. if (LocalFileList->Count != 1)
  2002. {
  2003. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2004. }
  2005. }
  2006. else
  2007. {
  2008. if ((LocalFileList->Count != 1) &&
  2009. (FileList->Count != 1) &&
  2010. (LocalFileList->Count != FileList->Count))
  2011. {
  2012. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2013. }
  2014. }
  2015. }
  2016. UnicodeString RootTempDir;
  2017. UnicodeString TempDir;
  2018. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2019. if (!RemoteFiles)
  2020. {
  2021. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, true, true);
  2022. DebugAssert(RootTempDir == TempDir);
  2023. }
  2024. try
  2025. {
  2026. TDateTimes RemoteFileTimes;
  2027. if (RemoteFiles)
  2028. {
  2029. RemoteFileList = FileList;
  2030. }
  2031. else
  2032. {
  2033. RemoteFileList = new TStringList();
  2034. TMakeLocalFileListParams MakeFileListParam;
  2035. MakeFileListParam.FileList = RemoteFileList;
  2036. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2037. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2038. MakeFileListParam.Recursive =
  2039. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2040. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2041. if (!MakeFileListParam.Recursive)
  2042. {
  2043. RemoteFileTimes.clear();
  2044. RemoteFileListFull = new TStringList();
  2045. MakeFileListParam.FileList = RemoteFileListFull;
  2046. MakeFileListParam.Recursive = true;
  2047. MakeFileListParam.IncludeDirs = false;
  2048. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2049. }
  2050. else
  2051. {
  2052. RemoteFileListFull = RemoteFileList;
  2053. }
  2054. }
  2055. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2056. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2057. if (!NonBlocking)
  2058. {
  2059. int Count;
  2060. if (FileListCommand)
  2061. {
  2062. Count = 1;
  2063. }
  2064. else if (LocalFileCommand)
  2065. {
  2066. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2067. }
  2068. else
  2069. {
  2070. Count = RemoteFileList->Count;
  2071. }
  2072. Progress.Start(foCustomCommand, osRemote, Count);
  2073. DebugAssert(FProgressForm != NULL);
  2074. FProgressForm->ReadOnly = true;
  2075. }
  2076. try
  2077. {
  2078. if (FileListCommand)
  2079. {
  2080. UnicodeString LocalFile;
  2081. // MakeFileList does not delimit filenames
  2082. UnicodeString FileList = MakeFileList(RemoteFileList);
  2083. if (LocalFileCommand)
  2084. {
  2085. DebugAssert(LocalFileList->Count == 1);
  2086. LocalFile = LocalFileList->Strings[0];
  2087. }
  2088. TLocalCustomCommand CustomCommand(Data,
  2089. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2090. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2091. if (NonBlocking)
  2092. {
  2093. DebugAssert(!POutput);
  2094. ExecuteShellChecked(ShellCommand);
  2095. }
  2096. else
  2097. {
  2098. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2099. }
  2100. }
  2101. else if (LocalFileCommand)
  2102. {
  2103. if (LocalFileList->Count == 1)
  2104. {
  2105. UnicodeString LocalFile = LocalFileList->Strings[0];
  2106. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2107. {
  2108. UnicodeString FileName = RemoteFileList->Strings[Index];
  2109. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2110. Progress.SetFile(FileNameForProgress);
  2111. TLocalCustomCommand CustomCommand(Data,
  2112. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2113. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2114. TOnceDoneOperation OnceDoneOperation;
  2115. // Do not unselect anything, as it won't work with two panels anyway
  2116. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2117. }
  2118. }
  2119. else if (RemoteFileList->Count == 1)
  2120. {
  2121. UnicodeString FileName = RemoteFileList->Strings[0];
  2122. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2123. {
  2124. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2125. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2126. Progress.SetFile(LocalFileNameOnly);
  2127. TLocalCustomCommand CustomCommand(
  2128. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2129. FileName, LocalFileName, L"");
  2130. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2131. TOnceDoneOperation OnceDoneOperation;
  2132. // Do not unselect anything, as it won't work with two panels anyway
  2133. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2134. }
  2135. }
  2136. else
  2137. {
  2138. if (LocalFileList->Count != RemoteFileList->Count)
  2139. {
  2140. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2141. }
  2142. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2143. {
  2144. UnicodeString FileName = RemoteFileList->Strings[Index];
  2145. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2146. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2147. Progress.SetFile(LocalFileNameOnly); // sic
  2148. TLocalCustomCommand CustomCommand(
  2149. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2150. FileName, LocalFileName, L"");
  2151. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2152. TOnceDoneOperation OnceDoneOperation;
  2153. // Do not unselect anything, as it won't work with two panels anyway
  2154. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2155. }
  2156. }
  2157. }
  2158. else
  2159. {
  2160. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2161. {
  2162. UnicodeString FileName = RemoteFileList->Strings[Index];
  2163. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2164. Progress.SetFile(FileNameForProgress);
  2165. TLocalCustomCommand CustomCommand(Data,
  2166. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2167. FileName, L"", L"");
  2168. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2169. TOnceDoneOperation OnceDoneOperation;
  2170. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2171. }
  2172. }
  2173. }
  2174. __finally
  2175. {
  2176. if (!NonBlocking)
  2177. {
  2178. Progress.Stop();
  2179. }
  2180. }
  2181. DebugAssert(!FAutoOperation);
  2182. if (!RemoteFiles)
  2183. {
  2184. TempDir = IncludeTrailingBackslash(TempDir);
  2185. typedef std::map<UnicodeString, UnicodeString> TTempNameMap;
  2186. TTempNameMap TempNameMap;
  2187. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2188. {
  2189. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2190. TSearchRecSmart SearchRec;
  2191. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2192. FileSearchRec(FileName, SearchRec) &&
  2193. // Skip directories, process only nested files.
  2194. !SearchRec.IsDirectory() &&
  2195. (SearchRec.GetLastWriteTime() != RemoteFileTimes[Index]))
  2196. {
  2197. if (TempNameMap.empty()) // optimization (create map only once it is really needed)
  2198. {
  2199. TCopyParamType CopyParam = TemporaryFileCopyParam();
  2200. for (int Index2 = 0; Index2 < FileList->Count; Index2++)
  2201. {
  2202. UnicodeString RemotePath = FileList->Strings[Index2];
  2203. UnicodeString TempName = GetTempLocalName(RemotePath, CopyParam);
  2204. TempNameMap.insert(std::make_pair(TempName.UpperCase(), RemotePath));
  2205. }
  2206. }
  2207. UnicodeString RelPath = MidStr(FileName, TempDir.Length() + 1);
  2208. UnicodeString TempName = CutToChar(RelPath, L'\\', false).UpperCase();
  2209. TTempNameMap::const_iterator TempNameI = TempNameMap.find(TempName);
  2210. if (DebugAlwaysTrue(TempNameI != TempNameMap.end()))
  2211. {
  2212. TCopyParamType CopyParam = TemporaryFileCopyParam();
  2213. CopyParam.FileMask = L"";
  2214. FAutoOperation = true;
  2215. FMoveToQueue = false;
  2216. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2217. TemporaryFilesList->Add(FileName);
  2218. UnicodeString RemoteDir = UnixExtractFileDir(UnixCombinePathsSmart(TempNameI->second, ToUnixPath(RelPath)));
  2219. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2220. }
  2221. }
  2222. }
  2223. }
  2224. }
  2225. __finally
  2226. {
  2227. FAutoOperation = false;
  2228. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2229. {
  2230. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2231. }
  2232. }
  2233. }
  2234. __finally
  2235. {
  2236. if (RemoteFileList != FileList)
  2237. {
  2238. delete RemoteFileList;
  2239. }
  2240. if (LocalFileList != ALocalFileList)
  2241. {
  2242. delete LocalFileList;
  2243. }
  2244. if (RemoteFileListFull != RemoteFileList)
  2245. {
  2246. delete RemoteFileListFull;
  2247. }
  2248. }
  2249. }
  2250. //---------------------------------------------------------------------------
  2251. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2252. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2253. bool FileListCommand, UnicodeString * POutput)
  2254. {
  2255. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2256. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2257. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2258. {
  2259. UnicodeString FileName = SelectedFileList->Strings[Index];
  2260. if (DirectoryExists(FileName))
  2261. {
  2262. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2263. {
  2264. LocalFileList->Add(FileName);
  2265. }
  2266. if (FLAGSET(ACommand.Params, ccRecursive))
  2267. {
  2268. TMakeLocalFileListParams MakeFileListParam;
  2269. MakeFileListParam.FileList = LocalFileList.get();
  2270. MakeFileListParam.FileTimes = NULL;
  2271. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2272. MakeFileListParam.Recursive = true;
  2273. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2274. }
  2275. }
  2276. else
  2277. {
  2278. LocalFileList->Add(FileName);
  2279. }
  2280. }
  2281. UnicodeString RemotePath;
  2282. if (Terminal != NULL)
  2283. {
  2284. RemotePath = Terminal->CurrentDirectory;
  2285. }
  2286. if (FileListCommand)
  2287. {
  2288. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2289. TLocalCustomCommand CustomCommand(
  2290. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2291. L"", L"", FileList);
  2292. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2293. }
  2294. else
  2295. {
  2296. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2297. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2298. DebugAssert(FProgressForm != NULL);
  2299. FProgressForm->ReadOnly = true;
  2300. try
  2301. {
  2302. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2303. {
  2304. UnicodeString FileName = LocalFileList->Strings[Index];
  2305. Progress.SetFile(FileName);
  2306. TLocalCustomCommand CustomCommand(
  2307. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2308. FileName, L"", L"");
  2309. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2310. TOnceDoneOperation OnceDoneOperation;
  2311. Progress.Finish(FileName, true, OnceDoneOperation);
  2312. }
  2313. }
  2314. __finally
  2315. {
  2316. Progress.Stop();
  2317. }
  2318. }
  2319. }
  2320. //---------------------------------------------------------------------------
  2321. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2322. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2323. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2324. {
  2325. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2326. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2327. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2328. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2329. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2330. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2331. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2332. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2333. std::unique_ptr<UnicodeString> POutput;
  2334. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2335. FLAGSET(ACommand.Params, ccCopyResults))
  2336. {
  2337. POutput.reset(new UnicodeString());
  2338. }
  2339. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  2340. if (!LocalCustomCommand.IsFileCommand(Command))
  2341. {
  2342. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2343. }
  2344. // remote files?
  2345. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2346. {
  2347. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2348. }
  2349. // local files
  2350. else
  2351. {
  2352. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2353. }
  2354. if (POutput.get() != NULL)
  2355. {
  2356. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2357. int P = POutput->Pos(sLineBreak);
  2358. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2359. {
  2360. POutput->SetLength(P - 1);
  2361. }
  2362. // Copy even empty output to clipboard
  2363. if (FLAGSET(ACommand.Params, ccCopyResults))
  2364. {
  2365. CopyToClipboard(*POutput);
  2366. }
  2367. // But do not show an empty message box.
  2368. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2369. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2370. !POutput->IsEmpty())
  2371. {
  2372. TClipboardHandler ClipboardHandler;
  2373. ClipboardHandler.Text = *POutput;
  2374. TMessageParams Params;
  2375. TQueryButtonAlias Aliases[1];
  2376. Aliases[0].Button = qaRetry;
  2377. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2378. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2379. Params.Aliases = Aliases;
  2380. Params.AliasesCount = LENOF(Aliases);
  2381. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2382. }
  2383. }
  2384. }
  2385. //---------------------------------------------------------------------------
  2386. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2387. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2388. {
  2389. TCustomCommandData Data;
  2390. UnicodeString Site;
  2391. UnicodeString RemotePath;
  2392. if (HasAvailableTerminal())
  2393. {
  2394. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2395. Data = TCustomCommandData(SessionData.get());
  2396. Site = Terminal->SessionData->SessionKey;
  2397. RemotePath = Terminal->CurrentDirectory;
  2398. }
  2399. UnicodeString HelpKeyword = ACommand.HomePage;
  2400. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2401. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2402. {
  2403. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2404. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2405. {
  2406. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2407. }
  2408. else
  2409. {
  2410. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2411. }
  2412. if (!DoCustomCommandOptionsDialog(
  2413. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2414. {
  2415. Abort();
  2416. }
  2417. }
  2418. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2419. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2420. {
  2421. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2422. }
  2423. else
  2424. {
  2425. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2426. }
  2427. }
  2428. //---------------------------------------------------------------------------
  2429. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2430. const TCustomCommandType & Command)
  2431. {
  2432. DebugAssert(FCustomCommandLocalFileList != NULL);
  2433. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2434. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2435. TStrings * LocalFileList = new TStringList();
  2436. TStrings * RemoteFileList = new TStringList();
  2437. try
  2438. {
  2439. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2440. {
  2441. LocalFileList->Clear();
  2442. LocalFileList->AddObject(
  2443. FCustomCommandLocalFileList->Strings[Index],
  2444. FCustomCommandLocalFileList->Objects[Index]);
  2445. RemoteFileList->Clear();
  2446. RemoteFileList->AddObject(
  2447. FCustomCommandRemoteFileList->Strings[Index],
  2448. FCustomCommandRemoteFileList->Objects[Index]);
  2449. CustomCommand(RemoteFileList, Command, LocalFileList);
  2450. }
  2451. }
  2452. __finally
  2453. {
  2454. delete LocalFileList;
  2455. delete RemoteFileList;
  2456. }
  2457. }
  2458. //---------------------------------------------------------------------------
  2459. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2460. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2461. {
  2462. delete FCustomCommandLocalFileList;
  2463. delete FCustomCommandRemoteFileList;
  2464. // takeover ownership,
  2465. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2466. FCustomCommandLocalFileList = LocalFileList;
  2467. FCustomCommandRemoteFileList = RemoteFileList;
  2468. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2469. if (Button != NULL)
  2470. {
  2471. FCustomCommandMenu->Items->Clear();
  2472. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2473. MenuPopup(FCustomCommandMenu, Button);
  2474. }
  2475. else
  2476. {
  2477. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2478. }
  2479. }
  2480. //---------------------------------------------------------------------------
  2481. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2482. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2483. {
  2484. DebugAssert(FCapturedLog != NULL);
  2485. if ((OutputType == cotOutput) || (OutputType == cotError))
  2486. {
  2487. FCapturedLog->Add(AddedLine);
  2488. }
  2489. }
  2490. //---------------------------------------------------------------------------
  2491. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2492. TOperationSide Side)
  2493. {
  2494. return
  2495. (Side == osOther) &&
  2496. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2497. }
  2498. //---------------------------------------------------------------------------
  2499. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2500. TOperationSide Side, TTBXCustomItem * Item,
  2501. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2502. {
  2503. TCustomDirView * DView = DirView(Side);
  2504. bool IsDefault = false;
  2505. if (DView->ItemFocused != NULL)
  2506. {
  2507. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2508. TResolvedDoubleClickAction DefaultAction =
  2509. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2510. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2511. }
  2512. TTBItemOptions O = Item->Options;
  2513. if (IsDefault)
  2514. {
  2515. Item->Options = O << tboDefault;
  2516. }
  2517. else
  2518. {
  2519. Item->Options = O >> tboDefault;
  2520. }
  2521. }
  2522. //---------------------------------------------------------------------------
  2523. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2524. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2525. {
  2526. TCustomDirView * DView = DirView(Side);
  2527. TListItem * Item = DView->ItemFocused;
  2528. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2529. EnableFocusedOperation[Side])
  2530. {
  2531. TPoint ClientPoint;
  2532. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2533. TPoint(0, 0) : MousePos;
  2534. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2535. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2536. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2537. }
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2541. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2542. {
  2543. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2544. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2545. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2546. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2547. Handled = true;
  2548. }
  2549. //---------------------------------------------------------------------------
  2550. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString DebugUsedArg(Directory))
  2551. {
  2552. }
  2553. //---------------------------------------------------------------------------
  2554. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2555. {
  2556. DebugAssert(FErrorList == NULL);
  2557. if (WinConfiguration->ContinueOnError)
  2558. {
  2559. FErrorList = new TStringList();
  2560. Configuration->Usage->Inc(L"ContinuationsOnError");
  2561. }
  2562. NonVisualDataModule->StartBusy();
  2563. }
  2564. //---------------------------------------------------------------------------
  2565. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2566. {
  2567. NonVisualDataModule->EndBusy();
  2568. if (FErrorList)
  2569. {
  2570. HandleErrorList(FErrorList);
  2571. }
  2572. }
  2573. //---------------------------------------------------------------------------
  2574. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2575. const TCopyParamType & CopyParam)
  2576. {
  2577. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2578. {
  2579. Configuration->Usage->Inc(L"FileMaskUses");
  2580. }
  2581. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2582. {
  2583. Configuration->Usage->Inc(L"OperationMaskUses");
  2584. }
  2585. }
  2586. //---------------------------------------------------------------------------
  2587. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2588. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2589. {
  2590. DebugAssert(!IsLocalBrowserMode());
  2591. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2592. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2593. TTransferOperationParam DefaultParam;
  2594. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2595. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2596. switch (Param.Queue)
  2597. {
  2598. case asOn:
  2599. CopyParam.Queue = true;
  2600. break;
  2601. case asOff:
  2602. CopyParam.Queue = false;
  2603. break;
  2604. case asAuto:
  2605. default:
  2606. // keep default
  2607. break;
  2608. }
  2609. bool Result =
  2610. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2611. if (Result)
  2612. {
  2613. DebugAssert(Terminal);
  2614. bool SelectionRestored = false;
  2615. TCustomDirView * DView = NULL;
  2616. if (HasDirView[Side])
  2617. {
  2618. DView = DirView(Side);
  2619. DView->SaveSelection();
  2620. DView->SaveSelectedNames();
  2621. }
  2622. UpdateCopyParamCounters(CopyParam);
  2623. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2624. DebugAssert(FTransferResumeList == NULL);
  2625. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2626. FMoveToQueue = false;
  2627. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2628. try
  2629. {
  2630. TStrings * PermanentFileList;
  2631. std::unique_ptr<TStrings> PermanentFileListOwner;
  2632. try
  2633. {
  2634. if (Side == osLocal)
  2635. {
  2636. PermanentFileList = FileList;
  2637. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2638. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2639. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2640. if (Operation == foMove)
  2641. {
  2642. ReloadLocalDirectory();
  2643. if (DView != NULL)
  2644. {
  2645. DView->RestoreSelection();
  2646. }
  2647. SelectionRestored = true;
  2648. }
  2649. }
  2650. else
  2651. {
  2652. // Clone the file list as it may refer to current directory files,
  2653. // which get destroyed, when the source directory is reloaded after foMove operation.
  2654. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2655. // But for a hotfix, we are not going to do such a big change.
  2656. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2657. PermanentFileList = PermanentFileListOwner.get();
  2658. try
  2659. {
  2660. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2661. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2662. }
  2663. __finally
  2664. {
  2665. if (Operation == foMove)
  2666. {
  2667. if (DView != NULL)
  2668. {
  2669. DView->RestoreSelection();
  2670. }
  2671. SelectionRestored = true;
  2672. }
  2673. ReloadLocalDirectory(Param.TargetDirectory);
  2674. }
  2675. }
  2676. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2677. if (FMoveToQueue)
  2678. {
  2679. Abort();
  2680. }
  2681. }
  2682. catch (EAbort &)
  2683. {
  2684. if (FMoveToQueue)
  2685. {
  2686. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2687. DebugAssert(CopyParam.TransferSkipList == NULL);
  2688. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2689. if (TransferResumeList->Count > 0)
  2690. {
  2691. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2692. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2693. }
  2694. CopyParam.TransferSkipList = TransferResumeList.release();
  2695. // not really needed, just to keep it consistent with TransferResumeList
  2696. FTransferResumeList = NULL;
  2697. FMoveToQueue = false;
  2698. Configuration->Usage->Inc("MovesToBackground");
  2699. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2700. ClearTransferSourceSelection(Direction);
  2701. }
  2702. throw;
  2703. }
  2704. }
  2705. __finally
  2706. {
  2707. if (!SelectionRestored && (DView != NULL))
  2708. {
  2709. DView->DiscardSavedSelection();
  2710. }
  2711. FTransferResumeList = NULL;
  2712. }
  2713. }
  2714. return Result;
  2715. }
  2716. //---------------------------------------------------------------------------
  2717. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2718. TOperationSide Side, TStrings * FileList, void * Param)
  2719. {
  2720. DebugAssert(FileList->Count);
  2721. // We deliberately do not toggle alternative flag (Param), but use OR,
  2722. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2723. // shortcut of CurrentDeleteAlternativeAction
  2724. bool Alternative =
  2725. bool(Param) || UseAlternativeFunction();
  2726. bool Recycle;
  2727. if (IsSideLocalBrowser(Side))
  2728. {
  2729. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2730. }
  2731. else
  2732. {
  2733. Recycle =
  2734. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2735. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2736. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2737. }
  2738. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2739. if (!Result)
  2740. {
  2741. UnicodeString Query;
  2742. if (FileList->Count == 1)
  2743. {
  2744. if (IsSideLocalBrowser(Side))
  2745. {
  2746. Query = ExtractFileName(FileList->Strings[0]);
  2747. }
  2748. else
  2749. {
  2750. Query = UnixExtractFileName(FileList->Strings[0]);
  2751. }
  2752. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2753. }
  2754. else
  2755. {
  2756. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2757. }
  2758. TMessageParams Params(mpNeverAskAgainCheck);
  2759. Params.ImageName = L"Delete file";
  2760. unsigned int Answer =
  2761. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2762. if (Answer == qaNeverAskAgain)
  2763. {
  2764. Result = true;
  2765. if (Recycle)
  2766. {
  2767. WinConfiguration->ConfirmRecycling = false;
  2768. }
  2769. else
  2770. {
  2771. WinConfiguration->ConfirmDeleting = false;
  2772. }
  2773. }
  2774. else
  2775. {
  2776. Result = (Answer == qaOK);
  2777. }
  2778. }
  2779. if (Result)
  2780. {
  2781. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2782. }
  2783. return Result;
  2784. }
  2785. //---------------------------------------------------------------------------
  2786. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2787. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2788. {
  2789. TAutoBatch AutoBatch(this);
  2790. bool Result;
  2791. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2792. {
  2793. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2794. }
  2795. else if (Operation == foRename)
  2796. {
  2797. DebugAssert(DirView(Side)->ItemFocused);
  2798. DirView(Side)->ItemFocused->EditCaption();
  2799. Result = true;
  2800. }
  2801. else if (Operation == foDelete)
  2802. {
  2803. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2804. }
  2805. else if (Operation == foSetProperties)
  2806. {
  2807. DirView(osRemote)->SaveSelectedNames();
  2808. Result = SetProperties(Side, FileList);
  2809. }
  2810. else if (Operation == foCustomCommand)
  2811. {
  2812. DebugAssert(Param);
  2813. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2814. DirView(osRemote)->SaveSelectedNames();
  2815. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2816. CustomCommand(FileList, *Command, NULL);
  2817. Result = true;
  2818. }
  2819. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2820. {
  2821. DebugAssert(!IsSideLocalBrowser(Side));
  2822. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2823. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2824. }
  2825. else if (Operation == foLock)
  2826. {
  2827. DebugAssert(!IsSideLocalBrowser(Side));
  2828. LockFiles(FileList, true);
  2829. Result = true;
  2830. }
  2831. else if (Operation == foUnlock)
  2832. {
  2833. DebugAssert(!IsSideLocalBrowser(Side));
  2834. LockFiles(FileList, false);
  2835. Result = true;
  2836. }
  2837. else
  2838. {
  2839. DebugFail();
  2840. Result = false; // shut up
  2841. }
  2842. return Result;
  2843. }
  2844. //---------------------------------------------------------------------------
  2845. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2846. {
  2847. if (Side == osCurrent)
  2848. {
  2849. Side = FCurrentSide;
  2850. }
  2851. return Side;
  2852. }
  2853. //---------------------------------------------------------------------------
  2854. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2855. {
  2856. TOperationSide Result;
  2857. switch (GetSide(Side))
  2858. {
  2859. case osLocal:
  2860. Result = osOther;
  2861. break;
  2862. case osOther:
  2863. Result = osLocal;
  2864. break;
  2865. default:
  2866. Result = osCurrent; // shut up
  2867. DebugFail();
  2868. Abort();
  2869. }
  2870. return Result;
  2871. }
  2872. //---------------------------------------------------------------------------
  2873. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2874. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2875. {
  2876. Side = GetSide(Side);
  2877. bool FullPath = IsSideLocalBrowser(Side);
  2878. TCustomDirView * ADirView = DirView(Side);
  2879. std::unique_ptr<TStringList> FileList(new TStringList());
  2880. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2881. bool ReloadProperties =
  2882. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2883. DebugAlwaysTrue(HasAvailableTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2884. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2885. if (Result && ReloadProperties)
  2886. {
  2887. std::unique_ptr<TStringList> FileList2(new TStringList());
  2888. FileList->CaseSensitive = true;
  2889. FileList->Sort();
  2890. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2891. {
  2892. TListItem * Item = ADirView->Items->Item[Index];
  2893. UnicodeString FileName = ADirView->ItemFileName(Item);
  2894. int Index2;
  2895. if (FileList->Find(FileName, Index2))
  2896. {
  2897. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2898. }
  2899. }
  2900. LoadFilesProperties(FileList2.get());
  2901. }
  2902. return Result;
  2903. }
  2904. //---------------------------------------------------------------------------
  2905. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2906. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2907. bool NoConfirmation, void * Param)
  2908. {
  2909. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2910. {
  2911. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2912. {
  2913. DebugAssert(!IsLocalBrowserMode());
  2914. if (GetSide(Side) == osLocal)
  2915. {
  2916. Configuration->Usage->Inc(L"UploadsCommand");
  2917. }
  2918. else
  2919. {
  2920. Configuration->Usage->Inc(L"DownloadsCommand");
  2921. }
  2922. }
  2923. }
  2924. }
  2925. //---------------------------------------------------------------------------
  2926. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2927. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2928. {
  2929. TTransferOperationParam Param;
  2930. if ((WinConfiguration->Interface != ifCommander) ||
  2931. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2932. {
  2933. Flags &= ~cocShortCutHint;
  2934. }
  2935. TCustomDirView * DView = DirView(Side);
  2936. Param.Options =
  2937. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2938. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2939. if (FLAGSET(Flags, cocQueue))
  2940. {
  2941. Param.Queue = asOn;
  2942. }
  2943. else if (FLAGSET(Flags, cocNonQueue))
  2944. {
  2945. Param.Queue = asOff;
  2946. }
  2947. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2948. }
  2949. //---------------------------------------------------------------------------
  2950. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2951. {
  2952. int Count = ErrorList->Count;
  2953. try
  2954. {
  2955. if (ErrorList->Count)
  2956. {
  2957. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2958. if (MessageDialog(Message, qtError,
  2959. qaOK | qaCancel, HELP_NONE) == qaOK)
  2960. {
  2961. unsigned int Answer;
  2962. int Index = 0;
  2963. do
  2964. {
  2965. DebugAssert(Index >= 0 && Index < Count);
  2966. TQueryButtonAlias Aliases[2];
  2967. Aliases[0].Button = qaYes;
  2968. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2969. Aliases[1].Button = qaNo;
  2970. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2971. TMessageParams Params;
  2972. Params.Aliases = Aliases;
  2973. Params.AliasesCount = LENOF(Aliases);
  2974. int No = Index + 1;
  2975. UnicodeString Message = ErrorList->Strings[Index];
  2976. UnicodeString AMainInstructions;
  2977. UnicodeString Details;
  2978. if (ExtractMainInstructions(Message, AMainInstructions))
  2979. {
  2980. Details = Message;
  2981. Message = AMainInstructions;
  2982. }
  2983. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2984. Answer = MoreMessageDialog(
  2985. Message,
  2986. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2987. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2988. qaOK, HELP_NONE, &Params);
  2989. if (Answer == qaNo)
  2990. {
  2991. Index++;
  2992. }
  2993. if (Answer == qaYes)
  2994. {
  2995. Index--;
  2996. }
  2997. }
  2998. while (Answer != qaOK);
  2999. }
  3000. }
  3001. }
  3002. __finally
  3003. {
  3004. TStrings * List = ErrorList;
  3005. ErrorList = NULL;
  3006. for (int i = 0; i < Count; i++)
  3007. {
  3008. delete List->Objects[i];
  3009. }
  3010. delete List;
  3011. }
  3012. }
  3013. //---------------------------------------------------------------------------
  3014. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3015. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3016. {
  3017. // needed for checking filemasks, as there's no directory object
  3018. // associated with the file object
  3019. File->FullFileName = FullFileName;
  3020. TFileMasks::TParams MaskParams;
  3021. MaskParams.Size = File->Size;
  3022. MaskParams.Modification = File->Modification;
  3023. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3024. }
  3025. //---------------------------------------------------------------------------
  3026. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3027. {
  3028. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3029. Side = GetSide(Side);
  3030. TCustomDirView * DView = DirView(Side);
  3031. TListItem * FocusedItem = DView->ItemFocused;
  3032. UnicodeString Name;
  3033. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3034. {
  3035. Name = DView->ItemFileName(FocusedItem);
  3036. }
  3037. else
  3038. {
  3039. Name = LoadStr(NEW_FILE);
  3040. }
  3041. UnicodeString Names = Name;
  3042. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3043. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3044. HELP_EDIT_NEW, History.get(), true, NULL, true, 444))
  3045. {
  3046. while (!Names.IsEmpty())
  3047. {
  3048. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3049. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3050. UnicodeString TargetFileName;
  3051. UnicodeString LocalFileName;
  3052. UnicodeString RootTempDir;
  3053. UnicodeString TempDir;
  3054. UnicodeString RemoteDirectory;
  3055. bool ExistingFile = false;
  3056. if (!IsSideLocalBrowser(Side))
  3057. {
  3058. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3059. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3060. if ((File.get() != NULL) &&
  3061. !File->IsDirectory)
  3062. {
  3063. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3064. ExistingFile = true;
  3065. }
  3066. File.reset(NULL);
  3067. if (!ExistingFile)
  3068. {
  3069. RemoteDirectory = UnixExtractFilePath(Name);
  3070. TemporaryDirectoryForRemoteFiles(
  3071. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3072. TargetFileName = UnixExtractFileName(Name);
  3073. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3074. LocalFileName = TempDir +
  3075. // We probably do not want to trim the VMS version here
  3076. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3077. }
  3078. }
  3079. else
  3080. {
  3081. if (ExtractFilePath(Name).IsEmpty())
  3082. {
  3083. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3084. }
  3085. else
  3086. {
  3087. LocalFileName = ExpandFileName(Name);
  3088. }
  3089. TargetFileName = ExtractFileName(Name);
  3090. }
  3091. if (!ExistingFile)
  3092. {
  3093. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3094. if (NewFile)
  3095. {
  3096. int File = FileCreate(ApiPath(LocalFileName));
  3097. if (File < 0)
  3098. {
  3099. if (!RootTempDir.IsEmpty())
  3100. {
  3101. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3102. }
  3103. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3104. }
  3105. else
  3106. {
  3107. FileClose(File);
  3108. }
  3109. }
  3110. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3111. const TEditorData * ExternalEditor = NULL;
  3112. TFileMasks::TParams MaskParams; // size not known
  3113. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3114. false, MaskParams);
  3115. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3116. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3117. }
  3118. }
  3119. }
  3120. }
  3121. //---------------------------------------------------------------------------
  3122. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3123. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3124. {
  3125. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3126. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3127. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3128. return
  3129. ((ExecuteFileBy == efInternalEditor)) ||
  3130. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3131. }
  3132. //---------------------------------------------------------------------------
  3133. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3134. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3135. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3136. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3137. {
  3138. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3139. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3140. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3141. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3142. Side = GetSide(Side);
  3143. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3144. if (!IsSideLocalBrowser(Side))
  3145. {
  3146. Data->Terminal = Terminal;
  3147. Data->SessionData = CloneCurrentSessionData();
  3148. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3149. Data->RemoteDirectory = RemoteDirectory;
  3150. Data->SessionName = Terminal->SessionData->SessionName;
  3151. Data->LocalRootDirectory = LocalRootDirectory;
  3152. Data->OriginalFileName = OriginalFileName;
  3153. Data->Command = L""; // will be changed later for external editor
  3154. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3155. if (WinConfiguration->EditorCheckNotModified)
  3156. {
  3157. Data->SourceTimestamp = SourceTimestamp;
  3158. }
  3159. }
  3160. if (ExecuteFileBy == efInternalEditor)
  3161. {
  3162. if (!IsSideLocalBrowser(Side))
  3163. {
  3164. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3165. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3166. TForm * Editor;
  3167. try
  3168. {
  3169. Editor =
  3170. ShowEditorForm(
  3171. FileName, this,
  3172. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3173. SaveAllInternalEditors, AnyInternalEditorModified,
  3174. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3175. }
  3176. catch(...)
  3177. {
  3178. if (!LocalRootDirectory.IsEmpty())
  3179. {
  3180. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3181. }
  3182. throw;
  3183. }
  3184. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3185. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3186. }
  3187. else
  3188. {
  3189. DebugAssert(!StandaloneOperation);
  3190. TForm * Editor =
  3191. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3192. SaveAllInternalEditors, AnyInternalEditorModified,
  3193. L"", false, SessionColor, -1, NewFile);
  3194. FLocalEditors->Add(Editor);
  3195. }
  3196. }
  3197. else
  3198. {
  3199. HANDLE Process;
  3200. if (ExecuteFileBy == efExternalEditor)
  3201. {
  3202. UnicodeString Program, Params, Dir;
  3203. Data->Command = ExternalEditor->ExternalEditor;
  3204. ReformatFileNameCommand(Data->Command);
  3205. SplitCommand(Data->Command, Program, Params, Dir);
  3206. Params = ExpandFileNameCommand(Params, FileName);
  3207. Program = ExpandEnvironmentVariables(Program);
  3208. if (!ExecuteShell(Program, Params, Process))
  3209. {
  3210. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3211. }
  3212. }
  3213. else
  3214. {
  3215. DebugAssert(!IsSideLocalBrowser(Side));
  3216. if (!ExecuteShell(FileName, L"", Process))
  3217. {
  3218. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3219. }
  3220. }
  3221. if (IsSideLocalBrowser(Side) ||
  3222. ((ExecuteFileBy == efShell) &&
  3223. !WinConfiguration->Editor.SDIShellEditor) ||
  3224. ((ExecuteFileBy == efExternalEditor) &&
  3225. !ExternalEditor->SDIExternalEditor))
  3226. {
  3227. // no need for handle
  3228. if (Process != NULL)
  3229. {
  3230. DebugCheck(CloseHandle(Process));
  3231. }
  3232. Process = INVALID_HANDLE_VALUE;
  3233. }
  3234. else
  3235. {
  3236. if (Process == NULL)
  3237. {
  3238. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3239. }
  3240. }
  3241. if (!IsSideLocalBrowser(Side))
  3242. {
  3243. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3244. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3245. }
  3246. }
  3247. }
  3248. //---------------------------------------------------------------------------
  3249. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3250. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3251. void * /*Arg*/)
  3252. {
  3253. if (Token != NULL)
  3254. {
  3255. EditorFormFileSave(static_cast<TForm *>(Token));
  3256. }
  3257. }
  3258. //---------------------------------------------------------------------------
  3259. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3260. {
  3261. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3262. {
  3263. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3264. }
  3265. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3266. }
  3267. //---------------------------------------------------------------------------
  3268. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3269. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3270. void * Arg)
  3271. {
  3272. if ((Token != NULL) &&
  3273. IsEditorFormModified(static_cast<TForm *>(Token)))
  3274. {
  3275. *static_cast<bool *>(Arg) = true;
  3276. }
  3277. }
  3278. //---------------------------------------------------------------------------
  3279. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3280. TObject * /*Sender*/, bool & Modified)
  3281. {
  3282. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3283. {
  3284. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3285. {
  3286. Modified = true;
  3287. }
  3288. }
  3289. if (!Modified)
  3290. {
  3291. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3292. }
  3293. }
  3294. //---------------------------------------------------------------------------
  3295. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3296. {
  3297. DebugCheckNotEqual(FLocalEditors->Extract(Sender), NULL);
  3298. }
  3299. //---------------------------------------------------------------------------
  3300. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3301. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3302. UnicodeString & Result, UnicodeString & RootDirectory)
  3303. {
  3304. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3305. {
  3306. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3307. Result = RootDirectory;
  3308. }
  3309. else
  3310. {
  3311. RootDirectory = L"";
  3312. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3313. Result = IncludeTrailingBackslash(Result);
  3314. }
  3315. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3316. {
  3317. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3318. }
  3319. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3320. {
  3321. UnicodeString ARemoteDirectory = RemoteDirectory;
  3322. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3323. {
  3324. ARemoteDirectory.Delete(1, 1);
  3325. }
  3326. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3327. }
  3328. if (!ForceDirectories(ApiPath(Result)))
  3329. {
  3330. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3331. }
  3332. }
  3333. //---------------------------------------------------------------------------
  3334. UnicodeString TCustomScpExplorerForm::GetTempLocalName(const UnicodeString & Path, const TCopyParamType & CopyParam)
  3335. {
  3336. return Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(Path), osRemote, false);
  3337. }
  3338. //---------------------------------------------------------------------------
  3339. void TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3340. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3341. bool AutoOperation, bool SimpleTempDir)
  3342. {
  3343. DebugAssert(!IsLocalBrowserMode());
  3344. TCopyParamType CopyParam = TemporaryFileCopyParam(ForceText);
  3345. if (TempDir.IsEmpty())
  3346. {
  3347. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3348. }
  3349. DebugAssert(!FAutoOperation);
  3350. FAutoOperation = AutoOperation;
  3351. FMoveToQueue = false;
  3352. Terminal->ExceptionOnFail = true;
  3353. try
  3354. {
  3355. try
  3356. {
  3357. // turn off confirmations, as for MDI editors we may possibly download
  3358. // the same file over
  3359. Terminal->CopyToLocal(
  3360. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3361. }
  3362. catch(...)
  3363. {
  3364. if (!RootTempDir.IsEmpty())
  3365. {
  3366. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3367. }
  3368. throw;
  3369. }
  3370. }
  3371. __finally
  3372. {
  3373. FAutoOperation = false;
  3374. Terminal->ExceptionOnFail = false;
  3375. }
  3376. }
  3377. //---------------------------------------------------------------------------
  3378. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3379. {
  3380. // Do not waste time checking for default editor list the next time,
  3381. // or testing if default editor is not notepad.
  3382. bool TryNextTime = false;
  3383. UnicodeString UsageState;
  3384. if (!WinConfiguration->EditorList->IsDefaultList())
  3385. {
  3386. UsageState = "H";
  3387. }
  3388. else
  3389. {
  3390. UnicodeString Executable;
  3391. UnicodeString ExecutableDescription;
  3392. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3393. {
  3394. UnicodeString Message =
  3395. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3396. unsigned int Answer =
  3397. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3398. if (Answer != qaOK)
  3399. {
  3400. UsageState = "R";
  3401. }
  3402. else
  3403. {
  3404. UsageState = "A";
  3405. TEditorData EditorData;
  3406. EditorData.Editor = edExternal;
  3407. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3408. EditorData.ExternalEditorOptionsAutodetect();
  3409. TEditorList EditorList;
  3410. EditorList = *WinConfiguration->EditorList;
  3411. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3412. WinConfiguration->EditorList = &EditorList;
  3413. }
  3414. }
  3415. }
  3416. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3417. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3418. }
  3419. //---------------------------------------------------------------------------
  3420. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3421. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3422. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3423. {
  3424. if (ExecuteFileBy == efDefaultEditor)
  3425. {
  3426. if (!WinConfiguration->OfferedEditorAutoConfig)
  3427. {
  3428. EditorAutoConfig();
  3429. }
  3430. const TEditorPreferences * Editor =
  3431. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3432. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3433. {
  3434. ExecuteFileBy = efInternalEditor;
  3435. ExternalEditor = NULL;
  3436. }
  3437. else if (Editor->Data->Editor == edOpen)
  3438. {
  3439. ExecuteFileBy = efShell;
  3440. ExternalEditor = NULL;
  3441. }
  3442. else
  3443. {
  3444. ExecuteFileBy = efExternalEditor;
  3445. ExternalEditor = Editor->Data;
  3446. }
  3447. }
  3448. }
  3449. //---------------------------------------------------------------------------
  3450. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3451. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3452. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3453. {
  3454. UnicodeString OriginalFileName;
  3455. UnicodeString LocalRootDirectory;
  3456. UnicodeString RemoteDirectory;
  3457. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3458. IsSideLocalBrowser(Side), MaskParams);
  3459. UnicodeString Counter;
  3460. UnicodeString LocalFileName;
  3461. bool Handled = false;
  3462. if (!IsSideLocalBrowser(Side))
  3463. {
  3464. // We need to trim VMS version here, so that we use name without version
  3465. // when uploading back to create a new version of the file
  3466. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3467. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3468. TObject * Token = NULL;
  3469. UnicodeString LocalDirectory;
  3470. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3471. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3472. LocalDirectory))
  3473. {
  3474. if (Token != NULL)
  3475. {
  3476. TForm * Form = dynamic_cast<TForm *>(Token);
  3477. if (Form->WindowState == wsMinimized)
  3478. {
  3479. ShowWindow(Form->Handle, SW_RESTORE);
  3480. }
  3481. else
  3482. {
  3483. Form->SetFocus();
  3484. }
  3485. Handled = true;
  3486. }
  3487. else
  3488. {
  3489. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3490. }
  3491. }
  3492. if (!Handled)
  3493. {
  3494. std::unique_ptr<TStrings> FileList1(new TStringList());
  3495. FileList1->AddObject(FullFileName, Object);
  3496. bool ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3497. TemporarilyDownloadFiles(FileList1.get(), ForceText, LocalRootDirectory, LocalDirectory, true, false);
  3498. LocalFileName = LocalDirectory + GetTempLocalName(FullFileName, TemporaryFileCopyParam(ForceText));
  3499. switch (ExecuteFileBy)
  3500. {
  3501. case efShell:
  3502. Counter = "RemoteFilesExecuted";
  3503. break;
  3504. case efInternalEditor:
  3505. Counter = "RemoteFilesOpenedInInternalEditor";
  3506. break;
  3507. case efExternalEditor:
  3508. Counter = "RemoteFilesOpenedInExternalEditor";
  3509. break;
  3510. default:
  3511. DebugFail();
  3512. }
  3513. }
  3514. }
  3515. else
  3516. {
  3517. LocalFileName = FullFileName;
  3518. OriginalFileName = ExtractFileName(FullFileName);
  3519. switch (ExecuteFileBy)
  3520. {
  3521. case efShell:
  3522. Counter = "LocalFilesExecuted";
  3523. break;
  3524. case efInternalEditor:
  3525. Counter = "LocalFilesOpenedInInternalEditor";
  3526. break;
  3527. case efExternalEditor:
  3528. Counter = "LocalFilesOpenedInExternalEditor";
  3529. break;
  3530. default:
  3531. DebugFail();
  3532. }
  3533. }
  3534. if (!Handled)
  3535. {
  3536. Configuration->Usage->Inc(Counter);
  3537. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3538. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3539. }
  3540. }
  3541. //---------------------------------------------------------------------------
  3542. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3543. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3544. bool AllSelected, bool OnFocused)
  3545. {
  3546. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3547. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3548. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3549. Side = GetSide(Side);
  3550. TCustomDirView * DView = DirView(Side);
  3551. TStrings * FileList =
  3552. AllSelected ?
  3553. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3554. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3555. try
  3556. {
  3557. DebugAssert(AllSelected || (FileList->Count == 1));
  3558. for (int i = 0; i < FileList->Count; i++)
  3559. {
  3560. UnicodeString ListFileName = FileList->Strings[i];
  3561. UnicodeString FileNameOnly =
  3562. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3563. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3564. if (!DView->ItemIsDirectory(Item))
  3565. {
  3566. UnicodeString FullFileName;
  3567. if (!IsSideLocalBrowser(Side))
  3568. {
  3569. FullFileName = DirView(Side)->Path + ListFileName;
  3570. }
  3571. else
  3572. {
  3573. FullFileName = ListFileName;
  3574. }
  3575. TObject * Object = FileList->Objects[i];
  3576. TFileMasks::TParams MaskParams;
  3577. MaskParams.Size = DView->ItemFileSize(Item);
  3578. TDateTimePrecision Precision;
  3579. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3580. std::unique_ptr<TRemoteFile> File;
  3581. if (!IsSideLocalBrowser(Side))
  3582. {
  3583. File.reset(Terminal->TryReadFile(FullFileName));
  3584. if (File.get() != NULL)
  3585. {
  3586. File->FullFileName = FullFileName;
  3587. Object = File.get();
  3588. MaskParams.Size = File->Size;
  3589. MaskParams.Modification = File->Modification;
  3590. }
  3591. }
  3592. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3593. }
  3594. }
  3595. }
  3596. __finally
  3597. {
  3598. delete FileList;
  3599. }
  3600. }
  3601. //---------------------------------------------------------------------------
  3602. TCopyParamType TCustomScpExplorerForm::TemporaryFileCopyParam(bool ForceText)
  3603. {
  3604. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3605. CopyParam.FileNameCase = ncNoChange;
  3606. CopyParam.PreserveRights = false;
  3607. CopyParam.PreserveReadOnly = false;
  3608. CopyParam.ReplaceInvalidChars = true;
  3609. CopyParam.IncludeFileMask = TFileMasks();
  3610. CopyParam.NewerOnly = false;
  3611. CopyParam.FileMask = L"";
  3612. if (ForceText)
  3613. {
  3614. CopyParam.TransferMode = tmAscii;
  3615. }
  3616. return CopyParam;
  3617. }
  3618. //---------------------------------------------------------------------------
  3619. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3620. {
  3621. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3622. }
  3623. //---------------------------------------------------------------------------
  3624. class TEditorUploadQueueItem : public TUploadQueueItem
  3625. {
  3626. public:
  3627. __fastcall TEditorUploadQueueItem(
  3628. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3629. const TCopyParamType * CopyParam, int Params) :
  3630. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, false)
  3631. {
  3632. }
  3633. protected:
  3634. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3635. {
  3636. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3637. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3638. }
  3639. };
  3640. //---------------------------------------------------------------------------
  3641. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3642. {
  3643. if (WinConfiguration->EditorCheckNotModified) // optimization
  3644. {
  3645. UnicodeString RemoteFilePath;
  3646. {
  3647. TGuard Guard(FEditorManager->Section);
  3648. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3649. if (DebugAlwaysTrue(Data != NULL) &&
  3650. EditorCheckNotModified(Data))
  3651. {
  3652. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3653. }
  3654. }
  3655. if (!RemoteFilePath.IsEmpty())
  3656. {
  3657. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3658. if (File.get() != NULL)
  3659. {
  3660. TGuard Guard(FEditorManager->Section);
  3661. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3662. if (DebugAlwaysTrue(Data != NULL))
  3663. {
  3664. Data->SourceTimestamp = File->Modification;
  3665. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3666. }
  3667. }
  3668. }
  3669. }
  3670. }
  3671. //---------------------------------------------------------------------------
  3672. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3673. const UnicodeString & FileName, const TDateTime & Timestamp, TEditedFileData * Data,
  3674. HANDLE UploadCompleteEvent, bool & Retry)
  3675. {
  3676. TTerminalManager * Manager = TTerminalManager::Instance();
  3677. bool IsInavailable = !IsAvailableTerminal(Data->Terminal);
  3678. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3679. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3680. {
  3681. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3682. Retry = true;
  3683. }
  3684. else if (Manager->IsReconnectingTerminal(Data->Terminal))
  3685. {
  3686. AppLog(L"Session is being reconnected, will retry the upload later");
  3687. Retry = true;
  3688. }
  3689. else if (IsInavailable &&
  3690. GUIConfiguration->SessionReopenAutoInactive &&
  3691. (Data->Terminal->NextInactiveReconnect != TDateTime()))
  3692. {
  3693. if (Data->Terminal->LastInactiveSave != Timestamp)
  3694. {
  3695. AppLog(L"Inactive session reconnect is pending, rescheduling it for as soon as possible to retry the upload");
  3696. Data->Terminal->NextInactiveReconnect = Now();
  3697. Data->Terminal->LastInactiveSave = Timestamp;
  3698. }
  3699. else
  3700. {
  3701. AppLog(L"Inactive session reconnect is pending, will retry the upload later");
  3702. }
  3703. Retry = true;
  3704. }
  3705. else if (IsInavailable)
  3706. {
  3707. if (!NonVisualDataModule->Busy)
  3708. {
  3709. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3710. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3711. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3712. if (Data->Terminal == NULL)
  3713. {
  3714. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3715. if (SameSiteTerminal != NULL)
  3716. {
  3717. UnicodeString Message =
  3718. FMTLOAD(EDIT_SESSION_REATTACH,
  3719. (FileNameOnly, Data->SessionName, FileNameOnly));
  3720. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3721. {
  3722. Data->Terminal = SameSiteTerminal;
  3723. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3724. // We might also overwrite session data
  3725. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3726. }
  3727. else
  3728. {
  3729. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3730. Abort();
  3731. }
  3732. }
  3733. }
  3734. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3735. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3736. {
  3737. UnicodeString Message =
  3738. MainInstructions(
  3739. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3740. TMessageParams Params(FLAGMASK(!GUIConfiguration->SessionReopenAutoInactive, mpNeverAskAgainCheck));
  3741. Params.NeverAskAgainTitle = LoadStr(ALWAYS_RECONNECT);
  3742. unsigned int Answer = MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_NONE, &Params);
  3743. if (Answer == qaNeverAskAgain)
  3744. {
  3745. GUIConfiguration->SessionReopenAutoInactive = true;
  3746. Answer = qaOK;
  3747. }
  3748. if (Answer == qaOK)
  3749. {
  3750. if (Terminal->Disconnected)
  3751. {
  3752. Manager->ActiveSession = Terminal;
  3753. ReconnectSession();
  3754. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3755. if (!IsAvailableTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3756. {
  3757. Abort();
  3758. }
  3759. }
  3760. else
  3761. {
  3762. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3763. }
  3764. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3765. }
  3766. else
  3767. {
  3768. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3769. Abort();
  3770. }
  3771. }
  3772. }
  3773. if (!IsAvailableTerminal(Data->Terminal))
  3774. {
  3775. Configuration->Usage->Inc(L"EditInactiveSession");
  3776. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3777. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3778. (ExtractFileName(FileName), Data->SessionName)));
  3779. }
  3780. }
  3781. if (!Retry && EditorCheckNotModified(Data))
  3782. {
  3783. if (NonVisualDataModule->Busy)
  3784. {
  3785. Retry = true;
  3786. }
  3787. else
  3788. {
  3789. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3790. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3791. if (File.get() != NULL)
  3792. {
  3793. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3794. if (File->Modification != Data->SourceTimestamp)
  3795. {
  3796. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3797. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3798. {
  3799. Abort();
  3800. }
  3801. }
  3802. }
  3803. }
  3804. }
  3805. if (!Retry)
  3806. {
  3807. TStrings * FileList = new TStringList();
  3808. try
  3809. {
  3810. FileList->Add(FileName);
  3811. // Consider using the same settings (preset) as when the file was downloaded.
  3812. // More over this does not reflect the actual session that will do the upload.
  3813. TCopyParamType CopyParam = TemporaryFileCopyParam(Data->ForceText);
  3814. // so i do not need to worry if masking algorithm works in all cases
  3815. // ("" means "copy file name", no masking is actually done)
  3816. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3817. {
  3818. CopyParam.FileMask = L"";
  3819. }
  3820. else
  3821. {
  3822. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3823. }
  3824. int Params = cpNoConfirmation | cpTemporary;
  3825. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3826. {
  3827. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3828. TQueueItem * QueueItem =
  3829. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3830. QueueItem->CompleteEvent = UploadCompleteEvent;
  3831. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3832. }
  3833. else
  3834. {
  3835. if (NonVisualDataModule->Busy)
  3836. {
  3837. Retry = true;
  3838. }
  3839. else
  3840. {
  3841. FMoveToQueue = false;
  3842. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3843. SetEvent(UploadCompleteEvent);
  3844. }
  3845. }
  3846. }
  3847. __finally
  3848. {
  3849. delete FileList;
  3850. }
  3851. }
  3852. }
  3853. //---------------------------------------------------------------------------
  3854. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3855. const UnicodeString & FileName, TEditedFileData * Data)
  3856. {
  3857. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3858. DebugAssert(!NonVisualDataModule->Busy);
  3859. if (!IsAvailableTerminal(Data->Terminal))
  3860. {
  3861. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3862. (ExtractFileName(FileName), Data->SessionName)));
  3863. }
  3864. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3865. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3866. NonVisualDataModule->StartBusy();
  3867. try
  3868. {
  3869. std::unique_ptr<TRemoteFile> File;
  3870. UnicodeString RemoteFileName =
  3871. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3872. Terminal->ExceptionOnFail = true;
  3873. try
  3874. {
  3875. File.reset(Terminal->ReadFile(RemoteFileName));
  3876. if (!File->HaveFullFileName)
  3877. {
  3878. File->FullFileName = RemoteFileName;
  3879. }
  3880. }
  3881. __finally
  3882. {
  3883. Terminal->ExceptionOnFail = false;
  3884. }
  3885. std::unique_ptr<TStrings> FileList(new TStringList());
  3886. FileList->AddObject(RemoteFileName, File.get());
  3887. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3888. UnicodeString TempDir = ExtractFilePath(FileName);
  3889. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, false);
  3890. if (EditorCheckNotModified(Data))
  3891. {
  3892. Data->SourceTimestamp = File->Modification;
  3893. }
  3894. }
  3895. __finally
  3896. {
  3897. NonVisualDataModule->EndBusy();
  3898. // it actually may not exist anymore...
  3899. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3900. }
  3901. }
  3902. //---------------------------------------------------------------------------
  3903. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3904. const TEditedFileData * Data, bool & KeepOpen)
  3905. {
  3906. // Command is set for external editors only (not for "shell" open).
  3907. if (!Data->Command.IsEmpty())
  3908. {
  3909. bool AnyFound = false;
  3910. bool AnyMDI = false;
  3911. bool AnyNonMDI = false;
  3912. bool AnyDetect = false;
  3913. TEditorList * EditorList = new TEditorList();
  3914. try
  3915. {
  3916. *EditorList = *WinConfiguration->EditorList;
  3917. for (int i = 0; i < EditorList->Count; i++)
  3918. {
  3919. const TEditorPreferences * Editor = EditorList->Editors[i];
  3920. if ((Editor->Data->Editor == edExternal) &&
  3921. (Editor->Data->ExternalEditor == Data->Command))
  3922. {
  3923. AnyFound = true;
  3924. if (Editor->Data->SDIExternalEditor)
  3925. {
  3926. AnyNonMDI = true;
  3927. if (Editor->Data->DetectMDIExternalEditor)
  3928. {
  3929. AnyDetect = true;
  3930. }
  3931. }
  3932. else
  3933. {
  3934. AnyMDI = true;
  3935. }
  3936. }
  3937. }
  3938. bool EnableMDI = false;
  3939. bool DisableDetect = false;
  3940. if (AnyMDI)
  3941. {
  3942. KeepOpen = true;
  3943. if (AnyNonMDI)
  3944. {
  3945. // there is at least one instance of the editor with MDI support enabled,
  3946. // and one with disabled, enable it for all instances
  3947. EnableMDI = true;
  3948. }
  3949. }
  3950. else if (AnyFound && !AnyDetect)
  3951. {
  3952. // at least once instance found but all have MDI autodetection disabled
  3953. // => close the file (default action)
  3954. }
  3955. else
  3956. {
  3957. // no instance of the editor has MDI support enabled
  3958. TMessageParams Params;
  3959. if (AnyFound)
  3960. {
  3961. // there is at least one instance of the editor
  3962. Params.Params |= mpNeverAskAgainCheck;
  3963. }
  3964. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3965. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3966. switch (Answer)
  3967. {
  3968. case qaNeverAskAgain:
  3969. DisableDetect = true;
  3970. break;
  3971. case qaNo:
  3972. EnableMDI = true;
  3973. KeepOpen = true;
  3974. break;
  3975. }
  3976. }
  3977. if (AnyFound && (EnableMDI || DisableDetect))
  3978. {
  3979. bool Changed = false;
  3980. for (int i = 0; i < EditorList->Count; i++)
  3981. {
  3982. const TEditorPreferences * Editor = EditorList->Editors[i];
  3983. if ((Editor->Data->Editor == edExternal) &&
  3984. (Editor->Data->ExternalEditor == Data->Command) &&
  3985. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3986. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3987. {
  3988. Changed = true;
  3989. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3990. if (EnableMDI)
  3991. {
  3992. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3993. }
  3994. if (DisableDetect)
  3995. {
  3996. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3997. }
  3998. EditorList->Change(i, UpdatedEditor);
  3999. }
  4000. }
  4001. if (Changed)
  4002. {
  4003. WinConfiguration->EditorList = EditorList;
  4004. }
  4005. }
  4006. }
  4007. __finally
  4008. {
  4009. delete EditorList;
  4010. }
  4011. }
  4012. else
  4013. {
  4014. // "open" case
  4015. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4016. qaOK, HELP_APP_EARLY_CLOSED);
  4017. }
  4018. }
  4019. //---------------------------------------------------------------------------
  4020. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4021. {
  4022. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4023. }
  4024. //---------------------------------------------------------------------------
  4025. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4026. {
  4027. SideEnter(osRemote);
  4028. }
  4029. //---------------------------------------------------------------------------
  4030. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4031. {
  4032. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4033. SideEnter(osRemote);
  4034. }
  4035. //---------------------------------------------------------------------------
  4036. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4037. {
  4038. FCurrentSide = Side;
  4039. if (Visible)
  4040. {
  4041. UpdateControls();
  4042. }
  4043. }
  4044. //---------------------------------------------------------------------------
  4045. void __fastcall TCustomScpExplorerForm::FileDeleted(
  4046. TOperationSide Side, const UnicodeString & FileName, bool Success, bool NotCancelled)
  4047. {
  4048. VisualiseOperationFinished(Side, FileName, Success && NotCancelled);
  4049. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4050. {
  4051. FDeletedFiles->Add(FileName);
  4052. }
  4053. }
  4054. //---------------------------------------------------------------------------
  4055. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4056. TStrings * FileList, bool Alternative)
  4057. {
  4058. TCustomDirView * DView = DirView(Side);
  4059. DView->SaveSelection();
  4060. DView->SaveSelectedNames();
  4061. DebugAssert(!FAlternativeDelete);
  4062. FAlternativeDelete = Alternative;
  4063. try
  4064. {
  4065. int Params = FLAGMASK(Alternative, dfAlternative);
  4066. bool Remote = !IsSideLocalBrowser(Side);
  4067. std::unique_ptr<TStringList> DeletedFiles;
  4068. std::unique_ptr<TStrings> PermanentFileList;
  4069. bool AllowMoveToQueue = (Terminal != NULL);
  4070. if (AllowMoveToQueue)
  4071. {
  4072. DeletedFiles.reset(new TStringList());
  4073. DeletedFiles->CaseSensitive = Remote;
  4074. }
  4075. try
  4076. {
  4077. DebugAssert(FDeletedFiles == NULL);
  4078. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles, DeletedFiles.get());
  4079. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4080. if (AllowMoveToQueue)
  4081. {
  4082. FOnFileOperationFinished = FileDeleted;
  4083. }
  4084. FMoveToQueue = false;
  4085. if (Remote)
  4086. {
  4087. DebugAssert(AllowMoveToQueue);
  4088. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4089. PermanentFileList.reset(TRemoteFileList::CloneStrings(FileList));
  4090. DebugAssert(Terminal != NULL);
  4091. Terminal->DeleteFiles(FileList, Params);
  4092. }
  4093. else
  4094. {
  4095. if (AllowMoveToQueue) // optimization)
  4096. {
  4097. PermanentFileList.reset(CloneStrings(FileList));
  4098. }
  4099. if (IsLocalBrowserMode())
  4100. {
  4101. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4102. }
  4103. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  4104. try
  4105. {
  4106. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, Params);
  4107. }
  4108. __finally
  4109. {
  4110. ReloadLocalDirectory();
  4111. }
  4112. }
  4113. // Probably not needed for deleting, just for consistency with transfer code
  4114. if (FMoveToQueue)
  4115. {
  4116. Abort();
  4117. }
  4118. }
  4119. catch (EAbort &)
  4120. {
  4121. if (FMoveToQueue && DebugAlwaysTrue(AllowMoveToQueue) && DebugAlwaysTrue(Terminal != NULL))
  4122. {
  4123. FMoveToQueue = false;
  4124. DeletedFiles->Sorted = true;
  4125. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4126. {
  4127. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4128. {
  4129. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4130. DebugAssert(Index == 0);
  4131. PermanentFileList->Delete(Index);
  4132. Index--;
  4133. }
  4134. }
  4135. if (Remote)
  4136. {
  4137. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4138. TQueueItem * QueueItem = new TRemoteDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4139. AddQueueItem(Queue, QueueItem, Terminal);
  4140. }
  4141. else
  4142. {
  4143. Configuration->Usage->Inc("MovesToBackgroundDeleteLocal");
  4144. TQueueItem * QueueItem = new TLocalDeleteQueueItem(PermanentFileList.get(), Params);
  4145. AddQueueItem(Queue, QueueItem, Terminal);
  4146. }
  4147. ClearOperationSelection(Side);
  4148. }
  4149. }
  4150. FAlternativeDelete = false;
  4151. }
  4152. catch(...)
  4153. {
  4154. FAlternativeDelete = false;
  4155. DView->DiscardSavedSelection();
  4156. throw;
  4157. }
  4158. DView->RestoreSelection();
  4159. }
  4160. //---------------------------------------------------------------------------
  4161. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4162. {
  4163. DebugAssert(Terminal);
  4164. DebugAssert(!IsLocalBrowserMode());
  4165. RemoteDirView->SaveSelection();
  4166. RemoteDirView->SaveSelectedNames();
  4167. try
  4168. {
  4169. if (Lock)
  4170. {
  4171. Terminal->LockFiles(FileList);
  4172. }
  4173. else
  4174. {
  4175. Terminal->UnlockFiles(FileList);
  4176. }
  4177. }
  4178. catch(...)
  4179. {
  4180. RemoteDirView->DiscardSavedSelection();
  4181. throw;
  4182. }
  4183. RemoteDirView->RestoreSelection();
  4184. }
  4185. //---------------------------------------------------------------------------
  4186. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4187. {
  4188. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4189. bool Result =
  4190. IsAvailableTerminal(ATerminal) &&
  4191. ATerminal->DirectoryExists(Directory);
  4192. return Result;
  4193. }
  4194. //---------------------------------------------------------------------------
  4195. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4196. {
  4197. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4198. return
  4199. !Terminal->IsCapable[fcRemoteCopy] ||
  4200. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4201. }
  4202. //---------------------------------------------------------------------------
  4203. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4204. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4205. bool NoConfirmation, bool Move)
  4206. {
  4207. DebugAssert(Terminal != NULL);
  4208. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4209. DebugAssert(!IsLocalBrowserMode());
  4210. if (Session == NULL)
  4211. {
  4212. Session = Terminal;
  4213. }
  4214. bool TargetConfirmed = false;
  4215. if (Session == Terminal)
  4216. {
  4217. if (RemoteDriveView->DropTarget != NULL)
  4218. {
  4219. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4220. TargetConfirmed = true;
  4221. }
  4222. else if (RemoteDirView->DropTarget != NULL)
  4223. {
  4224. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4225. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4226. TargetConfirmed = true;
  4227. }
  4228. else
  4229. {
  4230. Target = RemoteDirView->Path;
  4231. }
  4232. }
  4233. else
  4234. {
  4235. Target = GetSessionPath(Session, osRemote);
  4236. }
  4237. Target = UnixIncludeTrailingBackslash(Target);
  4238. if (FileList->Count == 1)
  4239. {
  4240. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4241. }
  4242. else
  4243. {
  4244. FileMask = AnyMask;
  4245. }
  4246. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4247. bool Result = true;
  4248. if (!NoConfirmation)
  4249. {
  4250. bool Multi = (FileList->Count > 1);
  4251. if (Move)
  4252. {
  4253. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4254. }
  4255. else
  4256. {
  4257. std::unique_ptr<TStrings> Sessions(new TStringList);
  4258. std::unique_ptr<TStrings> Directories(new TStringList);
  4259. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4260. for (int Index = 0; Index < SessionList->Count; Index++)
  4261. {
  4262. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4263. if (IsAvailableTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4264. {
  4265. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4266. Directories->Add(GetSessionPath(ASession, osRemote));
  4267. }
  4268. }
  4269. bool AnyDirectory = false;
  4270. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4271. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4272. {
  4273. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4274. {
  4275. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4276. }
  4277. }
  4278. TDirectRemoteCopy AllowDirectCopy;
  4279. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4280. {
  4281. DebugAssert(DirectCopy);
  4282. AllowDirectCopy = drcAllow;
  4283. }
  4284. else if (Terminal->IsCapable[fcSecondaryShell])
  4285. {
  4286. DebugAssert(DirectCopy);
  4287. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4288. }
  4289. else
  4290. {
  4291. DebugAssert(!DirectCopy);
  4292. AllowDirectCopy = drcDisallow;
  4293. }
  4294. void * ASession = Session;
  4295. Result = DoRemoteCopyDialog(
  4296. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4297. DoDirectoryExists, TargetConfirmed);
  4298. Session = static_cast<TManagedTerminal *>(ASession);
  4299. }
  4300. }
  4301. return Result;
  4302. }
  4303. //---------------------------------------------------------------------------
  4304. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4305. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4306. {
  4307. DebugAssert(!IsLocalBrowserMode());
  4308. bool DirectCopy;
  4309. UnicodeString Target, FileMask;
  4310. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4311. if (Result)
  4312. {
  4313. if (!Move && !DirectCopy)
  4314. {
  4315. Configuration->Usage->Inc("RemoteCopyTemp");
  4316. UnicodeString RootTempDir;
  4317. UnicodeString TempDir;
  4318. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true);
  4319. TStrings * TemporaryFilesList = new TStringList();
  4320. try
  4321. {
  4322. TMakeLocalFileListParams MakeFileListParam;
  4323. MakeFileListParam.FileList = TemporaryFilesList;
  4324. MakeFileListParam.FileTimes = NULL;
  4325. MakeFileListParam.IncludeDirs = true;
  4326. MakeFileListParam.Recursive = false;
  4327. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4328. TTerminalManager::Instance()->ActiveSession = Session;
  4329. if (TemporaryFilesList->Count > 0)
  4330. {
  4331. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4332. CopyParam.FileMask = FileMask;
  4333. DebugAssert(!FAutoOperation);
  4334. FAutoOperation = true;
  4335. FMoveToQueue = false;
  4336. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4337. }
  4338. }
  4339. __finally
  4340. {
  4341. delete TemporaryFilesList;
  4342. FAutoOperation = false;
  4343. if (!RootTempDir.IsEmpty())
  4344. {
  4345. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4346. }
  4347. }
  4348. }
  4349. else
  4350. {
  4351. RemoteDirView->SaveSelection();
  4352. RemoteDirView->SaveSelectedNames();
  4353. try
  4354. {
  4355. if (Move)
  4356. {
  4357. Configuration->Usage->Inc("RemoteMove");
  4358. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4359. }
  4360. else
  4361. {
  4362. Configuration->Usage->Inc("RemoteCopyDirect");
  4363. DebugAssert(DirectCopy);
  4364. DebugAssert(Session == Terminal);
  4365. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4366. Terminal->CommandSessionOpened ||
  4367. CommandSessionFallback())
  4368. {
  4369. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4370. }
  4371. }
  4372. }
  4373. catch(...)
  4374. {
  4375. RemoteDirView->DiscardSavedSelection();
  4376. throw;
  4377. }
  4378. RemoteDirView->RestoreSelection();
  4379. }
  4380. }
  4381. return Result;
  4382. }
  4383. //---------------------------------------------------------------------------
  4384. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4385. const UnicodeString & Path, TRemoteProperties & Properties)
  4386. {
  4387. DebugAssert(!IsLocalBrowserMode());
  4388. Properties.Valid = Properties.Valid << vpEncrypt;
  4389. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4390. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4391. }
  4392. //---------------------------------------------------------------------------
  4393. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4394. {
  4395. Side = GetSide(Side);
  4396. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4397. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4398. UnicodeString Name = LoadStr(NEW_FOLDER);
  4399. int AllowedChanges =
  4400. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4401. bool SaveSettings = false;
  4402. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4403. {
  4404. TWindowLock Lock(this);
  4405. if (!IsSideLocalBrowser(Side))
  4406. {
  4407. if (SaveSettings)
  4408. {
  4409. GUIConfiguration->NewDirectoryProperties = Properties;
  4410. }
  4411. CreateRemoteDirectory(Name, Properties);
  4412. }
  4413. else
  4414. {
  4415. DirView(Side)->CreateDirectory(Name);
  4416. }
  4417. }
  4418. }
  4419. //---------------------------------------------------------------------------
  4420. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4421. {
  4422. TWindowLock Lock(this);
  4423. DirView(Side)->ExecuteHomeDirectory();
  4424. }
  4425. //---------------------------------------------------------------------------
  4426. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4427. {
  4428. DoOpenDirectoryDialog(odBrowse, Side);
  4429. }
  4430. //---------------------------------------------------------------------------
  4431. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4432. {
  4433. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4434. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4435. bool Result = !Path.IsEmpty();
  4436. if (Result)
  4437. {
  4438. TryOpenDirectory(Side, Path);
  4439. }
  4440. return Result;
  4441. }
  4442. //---------------------------------------------------------------------------
  4443. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4444. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4445. bool & Close)
  4446. {
  4447. // terminal can be already closed (e.g. dropped connection)
  4448. if (Terminal != NULL)
  4449. {
  4450. try
  4451. {
  4452. TCalculateSizeParams Params;
  4453. Params.Stats = &Stats;
  4454. Terminal->CalculateFilesSize(FileList, Size, Params);
  4455. }
  4456. catch(...)
  4457. {
  4458. if (!Terminal->Active)
  4459. {
  4460. Close = true;
  4461. }
  4462. throw;
  4463. }
  4464. }
  4465. }
  4466. //---------------------------------------------------------------------------
  4467. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4468. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4469. bool & Close)
  4470. {
  4471. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4472. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4473. {
  4474. Configuration->Usage->Inc(L"ChecksumCalculated");
  4475. try
  4476. {
  4477. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4478. }
  4479. catch(...)
  4480. {
  4481. if (!Terminal->Active)
  4482. {
  4483. Close = true;
  4484. }
  4485. throw;
  4486. }
  4487. }
  4488. }
  4489. //---------------------------------------------------------------------------
  4490. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4491. {
  4492. if (Terminal->LoadFilesProperties(FileList))
  4493. {
  4494. RemoteDirView->Invalidate();
  4495. }
  4496. }
  4497. //---------------------------------------------------------------------------
  4498. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4499. {
  4500. return
  4501. Terminal->IsCapable[fcCalculatingChecksum] ||
  4502. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4503. }
  4504. //---------------------------------------------------------------------------
  4505. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4506. {
  4507. bool Result;
  4508. if (!IsSideLocalBrowser(Side))
  4509. {
  4510. TRemoteTokenList * GroupList = NULL;
  4511. TRemoteTokenList * UserList = NULL;
  4512. try
  4513. {
  4514. TRemoteProperties CurrentProperties;
  4515. LoadFilesProperties(FileList);
  4516. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4517. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4518. if (CapableGroupChanging || CapableOwnerChanging)
  4519. {
  4520. if (CapableGroupChanging)
  4521. {
  4522. GroupList = Terminal->Groups->Duplicate();
  4523. }
  4524. if (CapableOwnerChanging)
  4525. {
  4526. UserList = Terminal->Users->Duplicate();
  4527. }
  4528. TRemoteDirectory * Files = Terminal->Files;
  4529. int Count = Files->Count;
  4530. if (Count > 100)
  4531. {
  4532. Count = 100;
  4533. }
  4534. for (int Index = 0; Index < Count; Index++)
  4535. {
  4536. TRemoteFile * File = Files->Files[Index];
  4537. if (CapableGroupChanging)
  4538. {
  4539. GroupList->AddUnique(File->Group);
  4540. }
  4541. if (CapableOwnerChanging)
  4542. {
  4543. UserList->AddUnique(File->Owner);
  4544. }
  4545. }
  4546. // if we haven't collected tokens for all files in current directory,
  4547. // make sure we collect them at least for all selected files.
  4548. // (note that so far the files in FileList has to be from current direcotry)
  4549. if (Count < Files->Count)
  4550. {
  4551. for (int Index = 0; Index < FileList->Count; Index++)
  4552. {
  4553. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4554. if (CapableGroupChanging)
  4555. {
  4556. GroupList->AddUnique(File->Group);
  4557. }
  4558. if (CapableOwnerChanging)
  4559. {
  4560. UserList->AddUnique(File->Owner);
  4561. }
  4562. }
  4563. }
  4564. }
  4565. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4566. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4567. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4568. {
  4569. CapableAclChanging = false;
  4570. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4571. }
  4572. int Flags = 0;
  4573. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4574. if (CapableAclChanging) Flags |= cpAcl;
  4575. if (CapableOwnerChanging) Flags |= cpOwner;
  4576. if (CapableGroupChanging) Flags |= cpGroup;
  4577. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4578. if (CanCalculateChecksum())
  4579. {
  4580. CalculateChecksumEvent = CalculateChecksum;
  4581. }
  4582. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4583. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4584. int Options =
  4585. FLAGMASK(Terminal->IsCapable[fcGroupOwnerChangingByID], poUserGroupByID) |
  4586. FLAGMASK(Terminal->IsCapable[fcTags], poTags);
  4587. TRemoteProperties NewProperties = CurrentProperties;
  4588. Result =
  4589. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4590. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags, Options,
  4591. CalculateSize, CalculateChecksumEvent);
  4592. if (Result)
  4593. {
  4594. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4595. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4596. }
  4597. }
  4598. __finally
  4599. {
  4600. delete GroupList;
  4601. delete UserList;
  4602. }
  4603. }
  4604. else
  4605. {
  4606. DirView(Side)->DisplayPropertiesMenu();
  4607. Result = true;
  4608. }
  4609. return Result;
  4610. }
  4611. //---------------------------------------------------------------------------
  4612. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4613. {
  4614. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4615. {
  4616. FIgnoreNextDialogChar = Key;
  4617. }
  4618. Key = 0;
  4619. }
  4620. //---------------------------------------------------------------------------
  4621. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4622. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4623. {
  4624. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4625. if (Command != NULL)
  4626. {
  4627. KeyProcessed(Key, Shift);
  4628. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4629. {
  4630. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4631. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4632. false, false, const_cast<TCustomCommandType *>(Command));
  4633. }
  4634. }
  4635. }
  4636. //---------------------------------------------------------------------------
  4637. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4638. {
  4639. if (!NonVisualDataModule->Busy)
  4640. {
  4641. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4642. {
  4643. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4644. }
  4645. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4646. {
  4647. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4648. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4649. {
  4650. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4651. // But so far it's not a problem, as it does what we want.
  4652. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4653. if (((Action->ShortCut == KeyShortCut) ||
  4654. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4655. AllowedAction(Action, aaShortCut))
  4656. {
  4657. // Has to be called before the action as the dialog char is already in queue.
  4658. // So when the action consumes message queue, we already need to have the
  4659. // FIgnoreNextDialogChar set
  4660. KeyProcessed(Key, Shift);
  4661. // Reset reference to previous component (when menu/toolbar was clicked).
  4662. // Needed to detect that action was invoked by keyboard shortcut
  4663. // in TNonVisualDataModule::ExplorerActionsExecute
  4664. Action->ActionComponent = NULL;
  4665. Action->Execute();
  4666. return;
  4667. }
  4668. }
  4669. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4670. {
  4671. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4672. {
  4673. KeyProcessed(Key, Shift);
  4674. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4675. return;
  4676. }
  4677. }
  4678. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4679. {
  4680. KeyProcessed(Key, Shift);
  4681. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4682. }
  4683. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4684. if (IsCustomShortCut(CustomShortCut))
  4685. {
  4686. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4687. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4688. if (WinConfiguration->SharedBookmarks != NULL)
  4689. {
  4690. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4691. if ((Bookmark != NULL) &&
  4692. OpenBookmark(FCurrentSide, Bookmark))
  4693. {
  4694. KeyProcessed(Key, Shift);
  4695. }
  4696. }
  4697. }
  4698. }
  4699. }
  4700. TForm::KeyDown(Key, Shift);
  4701. }
  4702. //---------------------------------------------------------------------------
  4703. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4704. {
  4705. bool OpenedTerminal = false;
  4706. UnicodeString ProtocolName;
  4707. UnicodeString ProtocolNameHint;
  4708. UnicodeString SecurityProtocolName;
  4709. UnicodeString DurationHint;
  4710. // See the comment in TScpCommanderForm::UpdateControls()
  4711. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4712. if (ActiveTerminal != NULL)
  4713. {
  4714. // Active is not enough here
  4715. if (ActiveTerminal->Status == ssOpened)
  4716. {
  4717. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4718. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4719. if (FileSystemInfo.ProtocolName.IsEmpty())
  4720. {
  4721. ProtocolName = SessionInfo.ProtocolName;
  4722. }
  4723. else
  4724. {
  4725. ProtocolName = FileSystemInfo.ProtocolName;
  4726. }
  4727. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4728. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4729. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4730. OpenedTerminal = true;
  4731. }
  4732. else if (ActiveTerminal->Status > ssClosed)
  4733. {
  4734. ProtocolName = LoadStr(STATUS_CONNECTING);
  4735. }
  4736. else
  4737. {
  4738. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4739. }
  4740. }
  4741. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4742. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4743. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4744. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4745. if (ProtocolStatusPanel->Caption != ProtocolName)
  4746. {
  4747. ProtocolStatusPanel->Caption = ProtocolName;
  4748. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4749. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4750. }
  4751. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4752. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4753. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4754. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4755. SecurityStatusPanel->Enabled = SecurityEnabled;
  4756. UnicodeString SecurityProtocolHint;
  4757. if (SecurityEnabled)
  4758. {
  4759. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4760. }
  4761. else
  4762. {
  4763. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4764. }
  4765. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4766. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4767. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4768. DurationStatusPanel->Hint = DurationHint;
  4769. UpdateStatusBar();
  4770. }
  4771. //---------------------------------------------------------------------------
  4772. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4773. {
  4774. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4775. DebugAssert(SessionStatusBar != NULL);
  4776. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4777. if (!FNote.IsEmpty())
  4778. {
  4779. NoteStatusPanel->Caption = FNote;
  4780. }
  4781. else
  4782. {
  4783. UpdateStatusPanelText(NoteStatusPanel);
  4784. }
  4785. NoteStatusPanel->Hint = FNoteHints;
  4786. UnicodeString LoginTime;
  4787. // See the comment in TScpCommanderForm::UpdateControls()
  4788. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4789. // Active is not enough here
  4790. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4791. {
  4792. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4793. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4794. }
  4795. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4796. DurationStatusPanel->Caption = LoginTime;
  4797. }
  4798. //---------------------------------------------------------------------------
  4799. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4800. {
  4801. Panel->Caption = L"";
  4802. }
  4803. //---------------------------------------------------------------------------
  4804. void __fastcall TCustomScpExplorerForm::Idle()
  4805. {
  4806. if (FShowing ||
  4807. // Particularly for
  4808. // - Standalone editing
  4809. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4810. // while "keeping remote directory up to date".
  4811. StandaloneOperation)
  4812. {
  4813. FEditorManager->Check();
  4814. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4815. // that needs to know if queue view is visible (and it may be closed after queue update)
  4816. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4817. }
  4818. if (FShowing)
  4819. {
  4820. if (!NonVisualDataModule->Busy &&
  4821. // Menu is opened or drag&drop is going on
  4822. (Mouse->Capture == NULL))
  4823. {
  4824. if (FRefreshRemoteDirectory)
  4825. {
  4826. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4827. {
  4828. Terminal->RefreshDirectory();
  4829. }
  4830. FRefreshRemoteDirectory = false;
  4831. }
  4832. if (FRefreshLocalDirectory)
  4833. {
  4834. ReloadLocalDirectory();
  4835. FRefreshLocalDirectory = false;
  4836. }
  4837. if (WinConfiguration->RefreshRemotePanel)
  4838. {
  4839. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4840. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4841. {
  4842. RemoteDirView->ReloadDirectory();
  4843. }
  4844. }
  4845. }
  4846. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4847. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4848. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4849. // And the Alt key can be released even when other window or application is active, so handling the key up in explorer window won't do either.
  4850. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4851. MenuToolbar->Idle();
  4852. }
  4853. if (FShowing || StandaloneOperation)
  4854. {
  4855. if (FQueueStatusInvalidated)
  4856. {
  4857. UpdateQueueStatus(false);
  4858. }
  4859. RefreshQueueItems();
  4860. }
  4861. if (FShowing)
  4862. {
  4863. UpdateStatusBar();
  4864. }
  4865. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4866. {
  4867. FClipboardFakeMonitorsPendingReset = false;
  4868. FClipboardFakeMonitors.reset(NULL);
  4869. }
  4870. FIgnoreNextDialogChar = 0;
  4871. }
  4872. //---------------------------------------------------------------------------
  4873. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4874. {
  4875. try
  4876. {
  4877. FUserActionTimer->Enabled = false;
  4878. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4879. {
  4880. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4881. {
  4882. FPendingQueueActionItem->ProcessUserAction();
  4883. }
  4884. }
  4885. }
  4886. __finally
  4887. {
  4888. FPendingQueueActionItem = NULL;
  4889. }
  4890. }
  4891. //---------------------------------------------------------------------------
  4892. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4893. {
  4894. if (WinConfiguration->MinimizeToTray)
  4895. {
  4896. UpdateTrayIcon();
  4897. FTrayIcon->Visible = true;
  4898. if (Visible)
  4899. {
  4900. ShowWindow(Handle, SW_HIDE);
  4901. }
  4902. }
  4903. }
  4904. //---------------------------------------------------------------------------
  4905. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4906. {
  4907. // WORKAROUND
  4908. // When restoring maximized window from minimization,
  4909. // rarely some controls do not align properly.
  4910. // Two instances seen (both for Commander):
  4911. // - When restoring, window is temporarily narrower (not maximized),
  4912. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4913. // Once maximized already, top dock shinks back, but the session PageControl,
  4914. // do not align up, leaving space between TopDock and PageControl.
  4915. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4916. for (int Index = 0; Index < ControlCount; Index++)
  4917. {
  4918. RealignControl(Controls[Index]);
  4919. }
  4920. if (FTrayIcon->Visible)
  4921. {
  4922. FTrayIcon->Visible = false;
  4923. if (Visible)
  4924. {
  4925. ShowWindow(Handle, SW_SHOW);
  4926. }
  4927. }
  4928. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4929. {
  4930. FNeedSession = false;
  4931. NonVisualDataModule->StartBusy();
  4932. try
  4933. {
  4934. NeedSession(true);
  4935. }
  4936. __finally
  4937. {
  4938. NonVisualDataModule->EndBusy();
  4939. }
  4940. }
  4941. }
  4942. //---------------------------------------------------------------------------
  4943. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4944. {
  4945. FTrayIcon->Hint = GetMainForm()->Caption;
  4946. }
  4947. //---------------------------------------------------------------------------
  4948. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4949. {
  4950. UpdateTrayIcon();
  4951. }
  4952. //---------------------------------------------------------------------------
  4953. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4954. {
  4955. // workaround
  4956. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4957. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4958. // But WM_ACTIVATEAPP message can be received even when
  4959. // the main window is minimized to the tray and internal editor window is focused
  4960. // (after another application was previously active)
  4961. if (::IsIconic(Handle))
  4962. {
  4963. if (!IsAppIconic())
  4964. {
  4965. SetAppIconic(true);
  4966. }
  4967. }
  4968. ::ApplicationRestore();
  4969. Application->BringToFront();
  4970. }
  4971. //---------------------------------------------------------------------------
  4972. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4973. {
  4974. RestoreApp();
  4975. }
  4976. //---------------------------------------------------------------------------
  4977. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4978. {
  4979. if (OpenInNewWindow())
  4980. {
  4981. ExecuteNewInstance(SessionUrl);
  4982. }
  4983. else
  4984. {
  4985. TTerminalManager::Instance()->NewSession(SessionUrl);
  4986. }
  4987. }
  4988. //---------------------------------------------------------------------------
  4989. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4990. {
  4991. NewSession();
  4992. }
  4993. //---------------------------------------------------------------------------
  4994. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4995. {
  4996. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4997. StoredSessions->NewSession(SessionName, SessionData);
  4998. // modified only, explicit
  4999. StoredSessions->Save(false, true);
  5000. // encode session name because of slashes in hierarchical sessions
  5001. return EncodeUrlString(SessionName);
  5002. }
  5003. //---------------------------------------------------------------------------
  5004. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  5005. {
  5006. // current working directories become defaults here, what is not right
  5007. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5008. return SaveHiddenDuplicateSession(SessionData.get());
  5009. }
  5010. //---------------------------------------------------------------------------
  5011. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  5012. {
  5013. if (OpenInNewWindow())
  5014. {
  5015. ExecuteNewInstance(CreateHiddenDuplicateSession());
  5016. }
  5017. else
  5018. {
  5019. // current working directories become defaults here, what is not right
  5020. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5021. TTerminalManager * Manager = TTerminalManager::Instance();
  5022. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  5023. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  5024. // We definitely want these
  5025. ASession->Disconnected = ManagedSession->Disconnected;
  5026. // Not sure about these two
  5027. ASession->Permanent = ManagedSession->Permanent;
  5028. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  5029. Manager->ActiveSession = ASession;
  5030. }
  5031. }
  5032. //---------------------------------------------------------------------------
  5033. void __fastcall TCustomScpExplorerForm::RenameTab()
  5034. {
  5035. UnicodeString Name = ManagedSession->SessionData->SessionName;
  5036. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  5037. // When submitting the default name, do not fix it
  5038. (Name != ManagedSession->SessionData->SessionName))
  5039. {
  5040. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5041. TSessionData::ValidateName(Name);
  5042. // This is inconsistent with how color (for example) is handled.
  5043. ManagedSession->SessionData->Name = Name;
  5044. UpdateControls();
  5045. // Add/Remove distinguishing paths from sessions of the same name.
  5046. SessionListChanged();
  5047. }
  5048. }
  5049. //---------------------------------------------------------------------------
  5050. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5051. {
  5052. DebugAssert(Queue != NULL);
  5053. bool Result = Queue->IsEmpty;
  5054. if (!Result)
  5055. {
  5056. SetFocus();
  5057. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5058. }
  5059. return Result;
  5060. }
  5061. //---------------------------------------------------------------------------
  5062. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5063. {
  5064. return CanCloseQueue(FQueue);
  5065. }
  5066. //---------------------------------------------------------------------------
  5067. void __fastcall TCustomScpExplorerForm::CloseTab()
  5068. {
  5069. if (CanCloseQueue())
  5070. {
  5071. TTerminalManager::Instance()->FreeActiveTerminal();
  5072. }
  5073. }
  5074. //---------------------------------------------------------------------------
  5075. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5076. {
  5077. if (CanCloseQueue())
  5078. {
  5079. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5080. }
  5081. }
  5082. //---------------------------------------------------------------------------
  5083. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5084. {
  5085. DetachTerminal(Terminal);
  5086. RemoteDirView->Terminal = Terminal;
  5087. UpdateRemotePathComboBox(false);
  5088. InitStatusBar();
  5089. UpdateControls();
  5090. }
  5091. //---------------------------------------------------------------------------
  5092. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5093. {
  5094. InitStatusBar();
  5095. }
  5096. //---------------------------------------------------------------------------
  5097. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5098. {
  5099. if (DebugAlwaysTrue(!Terminal->Active))
  5100. {
  5101. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5102. }
  5103. }
  5104. //---------------------------------------------------------------------------
  5105. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5106. {
  5107. if (OpenInNewWindow())
  5108. {
  5109. // encode session name because of slashes in hierarchical sessions
  5110. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5111. }
  5112. else
  5113. {
  5114. TTerminalManager * Manager = TTerminalManager::Instance();
  5115. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5116. Manager->ActiveSession = Terminal;
  5117. }
  5118. }
  5119. //---------------------------------------------------------------------------
  5120. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5121. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5122. {
  5123. TTerminalManager * Manager = TTerminalManager::Instance();
  5124. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5125. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5126. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5127. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5128. {
  5129. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5130. // FirstSession can be null, if none of the workspace sites exist anymore
  5131. // or if all workspace sessions are not suported by the interface
  5132. // (when trying to open all local-local workspace in "explorer" interface)
  5133. if (FirstSession != NULL)
  5134. {
  5135. if (!ConnectFirstTerminal)
  5136. {
  5137. FirstSession->Disconnected = true;
  5138. FirstSession->DisconnectedTemporarily = true;
  5139. }
  5140. Manager->ActiveSession = FirstSession;
  5141. }
  5142. }
  5143. }
  5144. //---------------------------------------------------------------------------
  5145. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5146. {
  5147. if (OpenInNewWindow())
  5148. {
  5149. ExecuteNewInstance(Name);
  5150. }
  5151. else
  5152. {
  5153. DoOpenFolderOrWorkspace(Name, true, false);
  5154. }
  5155. }
  5156. //---------------------------------------------------------------------------
  5157. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5158. bool &CanClose)
  5159. {
  5160. AppLog(L"Windows close query");
  5161. // See the comment in CloseApp()
  5162. if (NonVisualDataModule->Busy)
  5163. {
  5164. CanClose = false;
  5165. }
  5166. else
  5167. {
  5168. TTerminalManager * Manager = TTerminalManager::Instance();
  5169. int ActiveSessions = 0;
  5170. for (int Index = 0; Index < Manager->Count; Index++)
  5171. {
  5172. if (Manager->Sessions[Index]->Active)
  5173. {
  5174. ActiveSessions++;
  5175. }
  5176. }
  5177. // Confirm, when there's at least one active remote session or
  5178. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5179. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5180. WinConfiguration->ConfirmClosingSession)
  5181. {
  5182. unsigned int Result;
  5183. TMessageParams Params(mpNeverAskAgainCheck);
  5184. UnicodeString Message;
  5185. int Answers = qaOK | qaCancel;
  5186. // The current session is the only active session
  5187. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5188. {
  5189. if (!WinConfiguration->AutoSaveWorkspace)
  5190. {
  5191. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5192. }
  5193. else
  5194. {
  5195. Message = LoadStr(CLOSE_SESSION);
  5196. }
  5197. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5198. }
  5199. // Multiple active sessions or one active session, but it's not the current one
  5200. else if (ActiveSessions > 0)
  5201. {
  5202. if (!WinConfiguration->AutoSaveWorkspace)
  5203. {
  5204. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5205. }
  5206. else
  5207. {
  5208. Message = LoadStr(CLOSE_SESSIONS);
  5209. }
  5210. }
  5211. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5212. else
  5213. {
  5214. DebugAssert(Manager->Count > 1);
  5215. DebugAssert(!WinConfiguration->AutoSaveWorkspace);
  5216. Message = LoadStr(CLOSE_WORKSPACE);
  5217. }
  5218. UnicodeString Note;
  5219. if (WinConfiguration->AutoSaveWorkspace)
  5220. {
  5221. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5222. }
  5223. else
  5224. {
  5225. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5226. Answers = qaYes | qaNo | qaCancel;
  5227. }
  5228. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5229. SetFocus();
  5230. Result = MessageDialog(Message, qtConfirmation,
  5231. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5232. if (Result == qaNeverAskAgain)
  5233. {
  5234. WinConfiguration->ConfirmClosingSession = false;
  5235. }
  5236. if (Result == qaNo)
  5237. {
  5238. CanClose = SaveWorkspace(true);
  5239. // note that the workspace will be saved redundatly again from FormClose
  5240. }
  5241. else
  5242. {
  5243. CanClose =
  5244. (Result == qaOK) ||
  5245. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5246. (Result == qaNeverAskAgain);
  5247. }
  5248. }
  5249. if (CanClose && HasAvailableTerminal())
  5250. {
  5251. CanClose = CanCloseQueue();
  5252. }
  5253. }
  5254. if (CanClose)
  5255. {
  5256. CanClose =
  5257. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5258. FEditorManager->CloseExternalFilesWithoutProcess();
  5259. if (CanClose)
  5260. {
  5261. while (CanClose && (FLocalEditors->Count > 0))
  5262. {
  5263. int PrevCount = FLocalEditors->Count;
  5264. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5265. CanClose = (FLocalEditors->Count < PrevCount);
  5266. }
  5267. if (CanClose)
  5268. {
  5269. CanClose = FEditorManager->Empty(true);
  5270. if (!CanClose)
  5271. {
  5272. SetFocus();
  5273. CanClose =
  5274. (MessageDialog(
  5275. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5276. }
  5277. }
  5278. }
  5279. }
  5280. }
  5281. //---------------------------------------------------------------------------
  5282. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5283. {
  5284. TForm * Form = dynamic_cast<TForm *>(Sender);
  5285. DebugAssert(Form != NULL);
  5286. Form->Close();
  5287. }
  5288. //---------------------------------------------------------------------------
  5289. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5290. {
  5291. TForm * Form = dynamic_cast<TForm *>(Sender);
  5292. delete Form;
  5293. }
  5294. //---------------------------------------------------------------------------
  5295. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5296. {
  5297. while (FLocalEditors->Count > 0)
  5298. {
  5299. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5300. }
  5301. }
  5302. //---------------------------------------------------------------------------
  5303. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5304. TObject *Sender)
  5305. {
  5306. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5307. try
  5308. {
  5309. SetProperties(osRemote, FileList);
  5310. }
  5311. __finally
  5312. {
  5313. delete FileList;
  5314. }
  5315. }
  5316. //---------------------------------------------------------------------------
  5317. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5318. {
  5319. if (value)
  5320. {
  5321. if (Component == fcCustomCommandsBand)
  5322. {
  5323. UpdateCustomCommandsToolbar();
  5324. }
  5325. if (Component == fcQueueFileList)
  5326. {
  5327. DebugAssert(!QueueFileListSplitter->Visible);
  5328. AdjustQueueLayout();
  5329. UpdateQueueFileList();
  5330. }
  5331. }
  5332. }
  5333. //---------------------------------------------------------------------------
  5334. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5335. {
  5336. int MinHeightLimit =
  5337. GetStaticQueuePanelComponentsHeight() +
  5338. QueueFileListSplitter->Height +
  5339. QueueFileList->Height +
  5340. GetMinQueueViewHeight();
  5341. if (QueuePanel->ClientHeight < MinHeightLimit)
  5342. {
  5343. QueuePanel->ClientHeight = MinHeightLimit;
  5344. }
  5345. }
  5346. //---------------------------------------------------------------------------
  5347. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5348. {
  5349. TControl * Control = GetComponent(Component);
  5350. DebugAssert(Control);
  5351. bool Changed = (Control->Visible != value);
  5352. if (Changed)
  5353. {
  5354. ComponentShowing(Component, value);
  5355. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5356. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5357. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5358. if (value)
  5359. {
  5360. int RemainingHeight = Control->Parent->ClientHeight;
  5361. int RemainingWidth = Control->Parent->ClientWidth;
  5362. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5363. {
  5364. TControl * ChildControl = Control->Parent->Controls[i];
  5365. if (ChildControl->Visible)
  5366. {
  5367. switch (ChildControl->Align)
  5368. {
  5369. case alTop:
  5370. case alBottom:
  5371. RemainingHeight -= ChildControl->Height;
  5372. break;
  5373. case alLeft:
  5374. case alRight:
  5375. RemainingWidth -= ChildControl->Width;
  5376. break;
  5377. }
  5378. }
  5379. }
  5380. int Reserve = ScaleByTextHeight(this, 32);
  5381. // queue in explorer, trees in commander
  5382. if (Control->Height > RemainingHeight - Reserve)
  5383. {
  5384. Control->Height = RemainingHeight / 2;
  5385. }
  5386. if (Control->Width > RemainingWidth - Reserve)
  5387. {
  5388. Control->Width = RemainingWidth / 2;
  5389. }
  5390. }
  5391. Control->Visible = value;
  5392. if (WasFocused && Visible)
  5393. {
  5394. DirView(osCurrent)->SetFocus();
  5395. }
  5396. FixControlsPlacement();
  5397. }
  5398. }
  5399. //---------------------------------------------------------------------------
  5400. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5401. {
  5402. TControl * Control = GetComponent(Component);
  5403. if (Control == NULL)
  5404. {
  5405. return false;
  5406. }
  5407. else
  5408. {
  5409. return Control->Visible;
  5410. }
  5411. }
  5412. //---------------------------------------------------------------------------
  5413. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5414. {
  5415. bool Result;
  5416. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5417. {
  5418. Result = !IsUWP();
  5419. }
  5420. else
  5421. {
  5422. Result = true;
  5423. }
  5424. return Result;
  5425. }
  5426. //---------------------------------------------------------------------------
  5427. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5428. {
  5429. if (DirView->ItemFocused != NULL)
  5430. {
  5431. DirView->ItemFocused->MakeVisible(false);
  5432. }
  5433. }
  5434. //---------------------------------------------------------------------------
  5435. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5436. {
  5437. MakeFocusedItemVisible(RemoteDirView);
  5438. QueueSplitter->Visible = QueuePanel->Visible;
  5439. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5440. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5441. TControl * TopControlsOrder[] =
  5442. { TopDock, MessageDock, SessionsPageControl };
  5443. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5444. TControl * QueueControlsOrder[] =
  5445. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5446. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5447. }
  5448. //---------------------------------------------------------------------------
  5449. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5450. {
  5451. switch (Component) {
  5452. case fcStatusBar: return RemoteStatusBar;
  5453. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5454. case fcQueueView: return QueuePanel;
  5455. case fcQueueToolbar: return QueueDock;
  5456. case fcRemoteTree: return RemoteDrivePanel;
  5457. case fcSessionsTabs: return SessionsPageControl;
  5458. case fcQueueFileList: return QueueFileList;
  5459. default: return NULL;
  5460. }
  5461. }
  5462. //---------------------------------------------------------------------------
  5463. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5464. TObject *Sender, TListColumn *Column, TPoint &Point)
  5465. {
  5466. DebugAssert(NonVisualDataModule && Column && Sender);
  5467. NonVisualDataModule->ListColumn = Column;
  5468. TPopupMenu * DirViewColumnMenu;
  5469. if (Sender == DirView(osOther))
  5470. {
  5471. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5472. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5473. bool SizeColumn = (Column->Index == uvSize);
  5474. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5475. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5476. }
  5477. else
  5478. {
  5479. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5480. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5481. bool SizeColumn = (Column->Index == dvSize);
  5482. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5483. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5484. }
  5485. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5486. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5487. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5488. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5489. }
  5490. //---------------------------------------------------------------------------
  5491. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5492. TObject *Sender, TListItem *Item, bool &AllowExec)
  5493. {
  5494. DoDirViewExecFile(Sender, Item, AllowExec);
  5495. }
  5496. //---------------------------------------------------------------------------
  5497. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5498. TListItem * Item, bool & AllowExec)
  5499. {
  5500. DebugAssert(Sender && Item && Configuration);
  5501. DebugAssert(AllowExec);
  5502. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5503. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5504. bool Remote = !IsSideLocalBrowser(Side);
  5505. DebugAssert(Item == ADirView->ItemFocused);
  5506. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5507. TResolvedDoubleClickAction Action;
  5508. if (FForceExecution)
  5509. {
  5510. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5511. }
  5512. else
  5513. {
  5514. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5515. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5516. }
  5517. if (Action == rdcaCopy)
  5518. {
  5519. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5520. UnlockWindow();
  5521. try
  5522. {
  5523. if (IsLocalBrowserMode())
  5524. {
  5525. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5526. }
  5527. else
  5528. {
  5529. if (HasAvailableTerminal())
  5530. {
  5531. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5532. }
  5533. }
  5534. }
  5535. __finally
  5536. {
  5537. LockWindow();
  5538. }
  5539. AllowExec = false;
  5540. }
  5541. else if (Action == rdcaEdit)
  5542. {
  5543. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5544. {
  5545. ExecuteFile(Side, efDefaultEditor);
  5546. AllowExec = false;
  5547. }
  5548. }
  5549. else if (Action == rdcaOpen)
  5550. {
  5551. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5552. {
  5553. ExecuteFile(osRemote, efShell);
  5554. AllowExec = false;
  5555. }
  5556. }
  5557. }
  5558. //---------------------------------------------------------------------------
  5559. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5560. {
  5561. return ((Side == osRemote) || (Side == osCurrent));
  5562. }
  5563. //---------------------------------------------------------------------------
  5564. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5565. {
  5566. DebugFail();
  5567. }
  5568. //---------------------------------------------------------------------------
  5569. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5570. {
  5571. DebugFail();
  5572. }
  5573. //---------------------------------------------------------------------------
  5574. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5575. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5576. {
  5577. TSynchronizeParamType Params;
  5578. Params.LocalDirectory = LocalDirectory;
  5579. Params.RemoteDirectory = RemoteDirectory;
  5580. int UnusedParams =
  5581. (GUIConfiguration->SynchronizeParams &
  5582. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5583. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5584. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5585. Params.Options = GUIConfiguration->SynchronizeOptions;
  5586. bool SaveSettings = false;
  5587. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5588. &DoSynchronizeTooManyDirectories);
  5589. DebugAssert(FSynchronizeController == NULL);
  5590. FSynchronizeController = &Controller;
  5591. bool Result;
  5592. try
  5593. {
  5594. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5595. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5596. int Options =
  5597. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5598. DebugAssert(FOnFeedSynchronizeError == NULL);
  5599. DebugAssert(FOnSynchronizeAbort == NULL);
  5600. DebugAssert(FSynchronizeTerminal == NULL);
  5601. FSynchronizeTerminal = Terminal;
  5602. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5603. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5604. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5605. if (Result)
  5606. {
  5607. if (SaveSettings)
  5608. {
  5609. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5610. GUIConfiguration->SynchronizeOptions = Params.Options;
  5611. }
  5612. else
  5613. {
  5614. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5615. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5616. FLAGSET(Params.Options, soSynchronize))
  5617. {
  5618. GUIConfiguration->SynchronizeOptions =
  5619. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5620. soSynchronize;
  5621. }
  5622. }
  5623. LocalDirectory = Params.LocalDirectory;
  5624. RemoteDirectory = Params.RemoteDirectory;
  5625. }
  5626. }
  5627. __finally
  5628. {
  5629. FSynchronizeController = NULL;
  5630. DebugAssert(FOnFeedSynchronizeError == NULL);
  5631. FOnFeedSynchronizeError = NULL;
  5632. DebugAssert(FOnSynchronizeAbort == NULL);
  5633. FOnSynchronizeAbort = NULL;
  5634. FSynchronizeTerminal = NULL;
  5635. }
  5636. return Result;
  5637. }
  5638. //---------------------------------------------------------------------------
  5639. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5640. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5641. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5642. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5643. TSynchronizeOptions * Options, bool Full)
  5644. {
  5645. // Keep-up-to-date mode
  5646. if (Terminal->Status == ssOpened)
  5647. {
  5648. try
  5649. {
  5650. int PParams = Params.Params;
  5651. if (!Full)
  5652. {
  5653. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5654. if (FLAGSET(Params.Options, soRecurse))
  5655. {
  5656. PParams |= TTerminal::spSubDirs;
  5657. }
  5658. }
  5659. else
  5660. {
  5661. // if keepuptodate is non-recursive,
  5662. // full sync before has to be non-recursive as well
  5663. if (FLAGCLEAR(Params.Options, soRecurse))
  5664. {
  5665. PParams |= TTerminal::spNoRecurse;
  5666. }
  5667. }
  5668. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5669. PParams, Checklist, Options);
  5670. }
  5671. catch (Exception & E)
  5672. {
  5673. if (!Terminal->Active)
  5674. {
  5675. ShowExtendedExceptionEx(Terminal, &E);
  5676. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5677. if (!Terminal->Active)
  5678. {
  5679. throw;
  5680. }
  5681. }
  5682. else
  5683. {
  5684. if (FLAGSET(Params.Options, soContinueOnError) &&
  5685. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5686. {
  5687. // noop, already logged in MoreMessageDialog
  5688. }
  5689. else
  5690. {
  5691. // We get mostly EAbort here, so this is noop.
  5692. // Exception is an error when listing directories while looking for differences.
  5693. ShowExtendedExceptionEx(Terminal, &E);
  5694. throw;
  5695. }
  5696. }
  5697. }
  5698. }
  5699. }
  5700. //---------------------------------------------------------------------------
  5701. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5702. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5703. const UnicodeString ErrorStr)
  5704. {
  5705. if (!Directory.IsEmpty())
  5706. {
  5707. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5708. }
  5709. else
  5710. {
  5711. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5712. }
  5713. }
  5714. //---------------------------------------------------------------------------
  5715. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5716. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5717. {
  5718. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5719. {
  5720. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5721. }
  5722. else
  5723. {
  5724. TMessageParams Params(mpNeverAskAgainCheck);
  5725. unsigned int Result = MessageDialog(
  5726. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5727. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5728. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5729. {
  5730. MaxDirectories *= 2;
  5731. if (Result == qaNeverAskAgain)
  5732. {
  5733. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5734. }
  5735. }
  5736. else
  5737. {
  5738. Abort();
  5739. }
  5740. }
  5741. }
  5742. //---------------------------------------------------------------------------
  5743. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5744. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5745. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5746. TSynchronizeOptions * Options)
  5747. {
  5748. // Keep-up-to-date mode
  5749. DebugAssert(!FAutoOperation);
  5750. void * BatchStorage;
  5751. BatchStart(BatchStorage);
  5752. FAutoOperation = true;
  5753. bool AnyOperation = false;
  5754. TDateTime StartTime = Now();
  5755. TSynchronizeChecklist * AChecklist = NULL;
  5756. TObjectReleaser<TSynchronizeProgressForm> SynchronizeProgressFormReleaser(FSynchronizeProgressForm, new TSynchronizeProgressForm(Application, true, -1));
  5757. try
  5758. {
  5759. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5760. {
  5761. FSynchronizeProgressForm->Start();
  5762. }
  5763. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5764. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5765. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5766. Options);
  5767. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5768. SAFE_DESTROY(FSynchronizeProgressForm);
  5769. AnyOperation = (AChecklist->CheckedCount > 0);
  5770. if (AnyOperation)
  5771. {
  5772. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5773. CreateProgressForm(&SynchronizeProgress);
  5774. try
  5775. {
  5776. Terminal->SynchronizeApply(
  5777. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5778. SynchronizeProcessedItem, NULL, NULL, NULL);
  5779. }
  5780. __finally
  5781. {
  5782. DestroyProgressForm();
  5783. }
  5784. }
  5785. }
  5786. __finally
  5787. {
  5788. if (Checklist == NULL)
  5789. {
  5790. delete AChecklist;
  5791. }
  5792. else
  5793. {
  5794. *Checklist = AChecklist;
  5795. }
  5796. FAutoOperation = false;
  5797. SynchronizeProgressFormReleaser.Reset();
  5798. BatchEnd(BatchStorage);
  5799. ReloadLocalDirectory();
  5800. if (AnyOperation)
  5801. {
  5802. OperationComplete(StartTime);
  5803. }
  5804. }
  5805. }
  5806. //---------------------------------------------------------------------------
  5807. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5808. {
  5809. // can be called from command line
  5810. return Visible &&
  5811. ((DirView(osRemote)->SelCount > 0) ||
  5812. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5813. }
  5814. //---------------------------------------------------------------------------
  5815. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5816. {
  5817. LogSynchronizeEvent(Terminal, Message);
  5818. }
  5819. //---------------------------------------------------------------------------
  5820. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5821. int Params, TSynchronizeOptions & Options)
  5822. {
  5823. DebugAssert(!IsLocalBrowserMode());
  5824. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5825. {
  5826. Options.Filter = new TStringList();
  5827. Options.Filter->CaseSensitive = false;
  5828. Options.Filter->Duplicates = Types::dupAccept;
  5829. if (DirView(osRemote)->SelCount > 0)
  5830. {
  5831. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5832. }
  5833. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5834. {
  5835. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5836. }
  5837. Options.Filter->Sort();
  5838. }
  5839. }
  5840. //---------------------------------------------------------------------------
  5841. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5842. {
  5843. TCopyParamType Defaults;
  5844. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5845. ConfigStorage->AccessMode = smRead;
  5846. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5847. {
  5848. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5849. }
  5850. ConfigStorage.reset(NULL);
  5851. std::unique_ptr<TStringList> Options(new TStringList());
  5852. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5853. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5854. UnicodeString Result;
  5855. if (Options->Count > 0)
  5856. {
  5857. Result =
  5858. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5859. }
  5860. return Result;
  5861. }
  5862. //---------------------------------------------------------------------------
  5863. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5864. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5865. {
  5866. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5867. UnicodeString AdditionalParams =
  5868. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5869. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5870. SerializeCopyParamForCommandLine(CopyParams),
  5871. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5872. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5873. ExecuteNewInstance(SessionName, AdditionalParams);
  5874. }
  5875. //---------------------------------------------------------------------------
  5876. struct TSynchronizeParams
  5877. {
  5878. UnicodeString LocalDirectory;
  5879. UnicodeString RemoteDirectory;
  5880. TSynchronizeMode Mode;
  5881. TSynchronizeChecklist * Checklist;
  5882. int Params;
  5883. TCopyParamType * CopyParam;
  5884. TDateTime CollectElapsed;
  5885. TDateTime * StartTime;
  5886. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5887. };
  5888. //---------------------------------------------------------------------------
  5889. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5890. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5891. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5892. {
  5893. DebugAssert(!FAutoOperation);
  5894. void * BatchStorage;
  5895. BatchStart(BatchStorage);
  5896. FAutoOperation = true;
  5897. TFileOperationStatistics Statistics;
  5898. TDateTime Start = Now();
  5899. try
  5900. {
  5901. Params.OnProcessedItem = OnProcessedItem;
  5902. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5903. CreateProgressForm(&SynchronizeProgress);
  5904. Terminal->SynchronizeApply(
  5905. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5906. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5907. &Statistics);
  5908. }
  5909. __finally
  5910. {
  5911. Params.OnProcessedItem = NULL;
  5912. FAutoOperation = false;
  5913. DestroyProgressForm();
  5914. BatchEnd(BatchStorage);
  5915. ReloadLocalDirectory();
  5916. }
  5917. if (WinConfiguration->SynchronizeSummary)
  5918. {
  5919. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5920. // The statistics should be 0 anyway in this case
  5921. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5922. {
  5923. Message += L"\n";
  5924. if (Statistics.FilesUploaded > 0)
  5925. {
  5926. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5927. }
  5928. if (Statistics.FilesDownloaded > 0)
  5929. {
  5930. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5931. }
  5932. if (Statistics.FilesDeletedLocal > 0)
  5933. {
  5934. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5935. }
  5936. if (Statistics.FilesDeletedRemote > 0)
  5937. {
  5938. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5939. }
  5940. }
  5941. TDateTime Elapsed = (Now() - Start);
  5942. Message +=
  5943. L"\n" +
  5944. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5945. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5946. TMessageParams Params(mpNeverAskAgainCheck);
  5947. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5948. if (Result == qaNeverAskAgain)
  5949. {
  5950. WinConfiguration->SynchronizeSummary = false;
  5951. }
  5952. }
  5953. }
  5954. //---------------------------------------------------------------------------
  5955. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5956. {
  5957. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5958. {
  5959. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5960. }
  5961. // Not set in keep-up-to-date mode - Synchronize() method
  5962. if (Token != NULL)
  5963. {
  5964. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5965. if (Params.OnProcessedItem != NULL)
  5966. {
  5967. Params.OnProcessedItem(NULL, ChecklistItem);
  5968. }
  5969. }
  5970. }
  5971. //---------------------------------------------------------------------------
  5972. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5973. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5974. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5975. {
  5976. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5977. *Params.StartTime = Now();
  5978. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5979. }
  5980. //---------------------------------------------------------------------------
  5981. void TCustomScpExplorerForm::DoQueueSynchronize(void * Token)
  5982. {
  5983. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5984. int CopyParams = TTerminal::GetSynchronizeCopyParams(Params.Params);
  5985. TCopyParamType SyncCopyParam = TTerminal::GetSynchronizeCopyParam(Params.CopyParam, Params.Params);
  5986. bool Parallel = GUIConfiguration->CurrentCopyParam.QueueParallel;
  5987. int Index = 0;
  5988. const TSynchronizeChecklist::TItem * ChecklistItem;
  5989. while (Params.Checklist->GetNextChecked(Index, ChecklistItem))
  5990. {
  5991. TQueueItem * QueueItem = Terminal->SynchronizeToQueue(ChecklistItem, &SyncCopyParam, CopyParams, Parallel);
  5992. AddQueueItem(Queue, QueueItem, Terminal);
  5993. }
  5994. }
  5995. //---------------------------------------------------------------------------
  5996. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5997. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5998. {
  5999. // terminal can be already closed (e.g. dropped connection)
  6000. if (Terminal != NULL)
  6001. {
  6002. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6003. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  6004. }
  6005. }
  6006. //---------------------------------------------------------------------------
  6007. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  6008. TOperationSide Side, TStrings * FileList, const UnicodeString & NewFileName, bool TargetIsDirectory, void * Token)
  6009. {
  6010. DebugAssert(!IsLocalBrowserMode());
  6011. TAutoBatch AutoBatch(this);
  6012. TAutoFlag AutoOperationFlag(FAutoOperation);
  6013. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6014. if (Side == osRemote)
  6015. {
  6016. UnicodeString Target;
  6017. UnicodeString FileMask;
  6018. if (TargetIsDirectory)
  6019. {
  6020. Target = NewFileName;
  6021. Terminal->CreateTargetDirectory(Target, faDirectory, Params.CopyParam);
  6022. }
  6023. else
  6024. {
  6025. Target = UnixExtractFileDir(NewFileName);
  6026. FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  6027. }
  6028. RemoteDirView->SaveSelection();
  6029. RemoteDirView->SaveSelectedNames();
  6030. try
  6031. {
  6032. Terminal->MoveFiles(FileList, Target, FileMask, false);
  6033. }
  6034. catch(...)
  6035. {
  6036. RemoteDirView->DiscardSavedSelection();
  6037. throw;
  6038. }
  6039. RemoteDirView->RestoreSelection();
  6040. }
  6041. else if (DebugAlwaysTrue(Side == osLocal))
  6042. {
  6043. std::unique_ptr<TStrings> Directories(CreateSortedStringList());
  6044. if (TargetIsDirectory)
  6045. {
  6046. if (!ForceDirectories(ApiPath(NewFileName)))
  6047. {
  6048. throw EOSExtException(FMTLOAD(CREATE_DIR_ERROR, (NewFileName)));
  6049. }
  6050. Directories->Add(NewFileName);
  6051. }
  6052. else
  6053. {
  6054. Directories->Add(ExtractFileDir(NewFileName));
  6055. }
  6056. for (int Index = 0; Index < FileList->Count; Index++)
  6057. {
  6058. UnicodeString FileName = FileList->Strings[Index];
  6059. UnicodeString Directory = ExtractFileDir(FileName);
  6060. Directories->Add(Directory);
  6061. UnicodeString NewFilePath = NewFileName;
  6062. if (TargetIsDirectory)
  6063. {
  6064. NewFilePath = TPath::Combine(NewFilePath, ExtractFileName(FileName));
  6065. }
  6066. if (!MoveFile(ApiPath(FileName).c_str(), ApiPath(NewFilePath).c_str()))
  6067. {
  6068. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFilePath)));
  6069. }
  6070. }
  6071. for (int Index = 0; Index < Directories->Count; Index++)
  6072. {
  6073. ReloadLocalDirectory(Directories->Strings[Index]);
  6074. }
  6075. }
  6076. }
  6077. //---------------------------------------------------------------------------
  6078. void __fastcall TCustomScpExplorerForm::DoSynchronizeExplore(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  6079. {
  6080. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  6081. if (Side == osLocal)
  6082. {
  6083. if (Action == TSynchronizeChecklist::saDownloadNew)
  6084. {
  6085. OpenFolderInExplorer(LocalPath);
  6086. }
  6087. else
  6088. {
  6089. OpenFileInExplorer(Item->ForceGetLocalPath());
  6090. }
  6091. }
  6092. else if (DebugAlwaysTrue(Side == osRemote))
  6093. {
  6094. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6095. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6096. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6097. if (!LocalPath.IsEmpty())
  6098. {
  6099. SessionData->LocalDirectory = LocalPath;
  6100. }
  6101. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6102. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(EXPLORE_SWITCH), Item->GetFileName())));
  6103. }
  6104. }
  6105. //---------------------------------------------------------------------------
  6106. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6107. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6108. const TCopyParamType * CopyParams)
  6109. {
  6110. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6111. UnicodeString AdditionalParams =
  6112. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6113. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6114. SerializeCopyParamForCommandLine(CopyParams),
  6115. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6116. LocalDirectory, RemoteDirectory, Mode, Params));
  6117. ExecuteNewInstance(SessionName, AdditionalParams);
  6118. }
  6119. //---------------------------------------------------------------------------
  6120. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6121. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6122. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6123. {
  6124. int Result;
  6125. bool SaveSettings = false;
  6126. int Options =
  6127. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6128. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6129. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6130. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6131. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6132. bool Continue =
  6133. ((UseDefaults == 0) ||
  6134. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6135. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6136. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6137. if (Continue)
  6138. {
  6139. Configuration->Usage->Inc(L"Synchronizations");
  6140. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6141. UpdateCopyParamCounters(CopyParam);
  6142. TSynchronizeOptions SynchronizeOptions;
  6143. GetSynchronizeOptions(Params, SynchronizeOptions);
  6144. if (SaveSettings)
  6145. {
  6146. GUIConfiguration->SynchronizeParams = Params;
  6147. }
  6148. else
  6149. {
  6150. SaveMode = false;
  6151. }
  6152. TDateTime StartTime = Now();
  6153. TSynchronizeChecklist * Checklist = NULL;
  6154. try
  6155. {
  6156. DebugAssert(!FAutoOperation);
  6157. FAutoOperation = true;
  6158. try
  6159. {
  6160. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6161. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6162. int Files = -1;
  6163. if (DataList->Count >= 1)
  6164. {
  6165. Files = StrToIntDef(DataList->Strings[0], Files);
  6166. }
  6167. else
  6168. {
  6169. DataList->Add(UnicodeString());
  6170. }
  6171. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6172. FSynchronizeProgressForm->Start();
  6173. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6174. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6175. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6176. &SynchronizeOptions);
  6177. if (Terminal->SessionData->CacheDirectories)
  6178. {
  6179. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6180. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6181. }
  6182. }
  6183. __finally
  6184. {
  6185. FAutoOperation = false;
  6186. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6187. SAFE_DESTROY(FSynchronizeProgressForm);
  6188. }
  6189. TSynchronizeParams SynchronizeParams;
  6190. SynchronizeParams.LocalDirectory = LocalDirectory;
  6191. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6192. SynchronizeParams.Mode = Mode;
  6193. SynchronizeParams.CopyParam = &CopyParam;
  6194. SynchronizeParams.Params = Params;
  6195. SynchronizeParams.Checklist = Checklist;
  6196. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6197. SynchronizeParams.StartTime = &StartTime;
  6198. SynchronizeParams.OnProcessedItem = NULL;
  6199. Result = Checklist->Count;
  6200. if (Checklist->Count > 0)
  6201. {
  6202. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6203. {
  6204. TQueueSynchronizeEvent OnQueueSynchronize = NULL;
  6205. if (Visible && FLAGCLEAR(Params, TTerminal::spTimestamp))
  6206. {
  6207. OnQueueSynchronize = DoQueueSynchronize;
  6208. }
  6209. if (!DoSynchronizeChecklistDialog(
  6210. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6211. OnQueueSynchronize, DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeExplore,
  6212. &SynchronizeParams))
  6213. {
  6214. Result = -1;
  6215. }
  6216. }
  6217. else
  6218. {
  6219. FullSynchronize(SynchronizeParams, NULL, NULL);
  6220. }
  6221. }
  6222. else
  6223. {
  6224. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6225. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6226. }
  6227. }
  6228. __finally
  6229. {
  6230. delete Checklist;
  6231. }
  6232. OperationComplete(StartTime);
  6233. }
  6234. else
  6235. {
  6236. Result = -1;
  6237. }
  6238. return Result;
  6239. }
  6240. //---------------------------------------------------------------------------
  6241. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6242. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6243. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6244. {
  6245. if (Collect)
  6246. {
  6247. DebugAssert(FSynchronizeProgressForm != NULL);
  6248. if (!FSynchronizeProgressForm->Started)
  6249. {
  6250. FSynchronizeProgressForm->Start();
  6251. }
  6252. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6253. SetTaskbarListProgressValue(CompareProgress);
  6254. }
  6255. else
  6256. {
  6257. DebugAssert(FSynchronizeProgressForm == NULL);
  6258. DebugAssert(FProgressForm != NULL);
  6259. }
  6260. }
  6261. //---------------------------------------------------------------------------
  6262. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6263. {
  6264. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6265. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6266. if (File.get() != NULL)
  6267. {
  6268. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6269. Application->ShowMainForm = false;
  6270. Application->Run();
  6271. }
  6272. }
  6273. //---------------------------------------------------------------------------
  6274. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6275. {
  6276. DebugFail();
  6277. }
  6278. //---------------------------------------------------------------------------
  6279. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6280. {
  6281. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6282. SessionData->Assign(ManagedSession->SessionData);
  6283. UpdateSessionData(SessionData.get());
  6284. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6285. if (IsAvailableTerminal(ManagedSession))
  6286. {
  6287. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6288. }
  6289. if (!ManagedSession->SessionData->HasSessionName())
  6290. {
  6291. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6292. // once IsWorkspace is cleared
  6293. SessionData->Name = UnicodeString();
  6294. }
  6295. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6296. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6297. SessionData->IsWorkspace = false;
  6298. return SessionData.release();
  6299. }
  6300. //---------------------------------------------------------------------------
  6301. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6302. {
  6303. TSessionData * SessionData = CloneCurrentSessionData();
  6304. try
  6305. {
  6306. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6307. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6308. }
  6309. __finally
  6310. {
  6311. delete SessionData;
  6312. }
  6313. }
  6314. //---------------------------------------------------------------------------
  6315. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6316. {
  6317. TTerminalManager * Manager = TTerminalManager::Instance();
  6318. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6319. if (DebugAlwaysTrue(ManagedSession != NULL))
  6320. {
  6321. // Update ManagedSession->StateData
  6322. UpdateSession(ManagedSession);
  6323. }
  6324. Manager->SaveWorkspace(DataList.get());
  6325. return DataList.release();
  6326. }
  6327. //---------------------------------------------------------------------------
  6328. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6329. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6330. {
  6331. WinConfiguration->LastWorkspace = Name;
  6332. if (!SavePasswords)
  6333. {
  6334. for (int Index = 0; Index < DataList->Count; Index++)
  6335. {
  6336. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6337. if (SessionData->Link.IsEmpty())
  6338. {
  6339. SessionData->ClearSessionPasswords();
  6340. }
  6341. }
  6342. }
  6343. StoredSessions->NewWorkspace(Name, DataList);
  6344. // modified only
  6345. StoredSessions->Save(false, Explicit);
  6346. }
  6347. //---------------------------------------------------------------------------
  6348. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6349. {
  6350. return
  6351. DefaultStr(WinConfiguration->LastWorkspace,
  6352. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6353. }
  6354. //---------------------------------------------------------------------------
  6355. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6356. {
  6357. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6358. bool AnyNonStoredSessionWithPassword = false;
  6359. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6360. bool AllNonStoredSessionsAnonymous = true;
  6361. TTerminalManager * Manager = TTerminalManager::Instance();
  6362. for (int Index = 0; Index < DataList->Count; Index++)
  6363. {
  6364. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6365. if (SessionData->Link.IsEmpty())
  6366. {
  6367. if (SessionData->HasAnySessionPassword())
  6368. {
  6369. AnyNonStoredSessionWithPassword = true;
  6370. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6371. {
  6372. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6373. }
  6374. }
  6375. if (!SameText(SessionData->UserName, AnonymousUserName))
  6376. {
  6377. AllNonStoredSessionsAnonymous = false;
  6378. }
  6379. }
  6380. }
  6381. bool SavePasswords;
  6382. bool * PSavePasswords;
  6383. bool NotRecommendedSavingPasswords =
  6384. !CustomWinConfiguration->UseMasterPassword &&
  6385. !AllNonStoredSessionsAnonymous;
  6386. if (Configuration->DisablePasswordStoring ||
  6387. !AnyNonStoredSessionWithPassword)
  6388. {
  6389. PSavePasswords = NULL;
  6390. SavePasswords = false;
  6391. }
  6392. else
  6393. {
  6394. PSavePasswords = &SavePasswords;
  6395. SavePasswords =
  6396. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6397. !NotRecommendedSavingPasswords;
  6398. }
  6399. UnicodeString Name = WorkspaceName();
  6400. bool CreateShortcut = false;
  6401. bool Result =
  6402. DoSaveWorkspaceDialog(
  6403. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6404. EnableAutoSave);
  6405. if (Result)
  6406. {
  6407. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6408. if (CreateShortcut)
  6409. {
  6410. TOperationVisualizer Visualizer;
  6411. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6412. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6413. }
  6414. if (EnableAutoSave)
  6415. {
  6416. WinConfiguration->AutoSaveWorkspace = true;
  6417. WinConfiguration->AutoWorkspace = Name;
  6418. if (PSavePasswords != NULL)
  6419. {
  6420. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6421. }
  6422. }
  6423. }
  6424. return Result;
  6425. }
  6426. //---------------------------------------------------------------------------
  6427. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6428. {
  6429. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6430. DebugAssert(Session == ManagedSession);
  6431. if (!IsLocalBrowserMode())
  6432. {
  6433. SAFE_DESTROY(Session->RemoteExplorerState);
  6434. if (WinConfiguration->PreservePanelState)
  6435. {
  6436. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6437. }
  6438. }
  6439. UpdateSessionData(Session->StateData);
  6440. }
  6441. //---------------------------------------------------------------------------
  6442. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6443. {
  6444. // Keep in sync with TSessionData::CopyStateData
  6445. DebugAssert(Data != NULL);
  6446. // This is inconsistent with how color (for example) is handled.
  6447. Data->Name = ManagedSession->SessionData->Name;
  6448. if (!IsLocalBrowserMode())
  6449. {
  6450. // cannot use RemoteDirView->Path, because it is empty if connection
  6451. // was already closed
  6452. // also only peek, we may not be connected at all atm
  6453. // so make sure we do not try retrieving current directory from the server
  6454. // (particularly with FTP)
  6455. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6456. if (!ACurrentDirectory.IsEmpty())
  6457. {
  6458. Data->RemoteDirectory = ACurrentDirectory;
  6459. }
  6460. }
  6461. Data->Color = SessionColor;
  6462. }
  6463. //---------------------------------------------------------------------------
  6464. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6465. {
  6466. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6467. DebugAssert(Toolbar != NULL);
  6468. for (int i = 0; i < Toolbar->Items->Count; i++)
  6469. {
  6470. TTBXCustomDropDownItem * DropDownItem;
  6471. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6472. if (DropDownItem != NULL)
  6473. {
  6474. ToolbarItemResize(DropDownItem,
  6475. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6476. Toolbar->NonClientWidth);
  6477. break;
  6478. }
  6479. }
  6480. }
  6481. //---------------------------------------------------------------------------
  6482. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6483. {
  6484. Item->EditWidth = Width;
  6485. }
  6486. //---------------------------------------------------------------------------
  6487. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6488. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6489. {
  6490. for (int i = 0; i < Toolbar->Items->Count; i++)
  6491. {
  6492. TTBXCustomDropDownItem * DropDownItem;
  6493. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6494. if (DropDownItem != NULL)
  6495. {
  6496. ASize.x -= DropDownItem->EditWidth;
  6497. TControl * Control = this;
  6498. ASize.x += ScaleByTextHeight(Control, 50) /* minimal combo width */;
  6499. }
  6500. }
  6501. }
  6502. //---------------------------------------------------------------------------
  6503. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6504. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6505. {
  6506. if (WinConfiguration->DDWarnLackOfTempSpace)
  6507. {
  6508. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6509. if (!ADrive.IsEmpty())
  6510. {
  6511. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6512. DebugAssert(RequiredSpace >= 0);
  6513. __int64 RequiredWithReserve;
  6514. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6515. if (FreeSpace < RequiredWithReserve)
  6516. {
  6517. unsigned int Result;
  6518. TMessageParams Params(mpNeverAskAgainCheck);
  6519. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6520. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6521. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6522. if (Result == qaNeverAskAgain)
  6523. {
  6524. WinConfiguration->DDWarnLackOfTempSpace = false;
  6525. }
  6526. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6527. }
  6528. }
  6529. }
  6530. }
  6531. //---------------------------------------------------------------------------
  6532. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6533. {
  6534. DoOpenDirectoryDialog(odAddBookmark, Side);
  6535. }
  6536. //---------------------------------------------------------------------------
  6537. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6538. {
  6539. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6540. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6541. try
  6542. {
  6543. TCustomDirView * DView = DirView(Side);
  6544. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6545. {
  6546. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6547. }
  6548. }
  6549. catch (...)
  6550. {
  6551. delete VisitedDirectories;
  6552. throw;
  6553. }
  6554. return VisitedDirectories;
  6555. }
  6556. //---------------------------------------------------------------------------
  6557. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6558. TOpenDirectoryMode Mode, TOperationSide Side)
  6559. {
  6560. bool Continue = true;
  6561. if (Mode == odAddBookmark)
  6562. {
  6563. TMessageParams Params(mpNeverAskAgainCheck);
  6564. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6565. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6566. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6567. unsigned int Answer =
  6568. MessageDialog(Message,
  6569. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6570. if (Answer == qaNeverAskAgain)
  6571. {
  6572. Continue = true;
  6573. WinConfiguration->UseSharedBookmarks = true;
  6574. }
  6575. else if (Answer == qaOK)
  6576. {
  6577. Continue = true;
  6578. WinConfiguration->UseSharedBookmarks = false;
  6579. }
  6580. else
  6581. {
  6582. Continue = false;
  6583. }
  6584. }
  6585. if (Continue)
  6586. {
  6587. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6588. try
  6589. {
  6590. UnicodeString Name = DirView(Side)->PathName;
  6591. bool Repeat;
  6592. do
  6593. {
  6594. Repeat = false;
  6595. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6596. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6597. // do not allow switching to location profiles,
  6598. // if we are not connected
  6599. HasDirView[osLocal] && IsAvailableTerminal(Terminal)))
  6600. {
  6601. TWindowLock Lock(this);
  6602. if (!TryOpenDirectory(Side, Name))
  6603. {
  6604. Repeat = true;
  6605. Mode = odBrowse;
  6606. }
  6607. }
  6608. }
  6609. while (Repeat);
  6610. }
  6611. __finally
  6612. {
  6613. delete VisitedDirectories;
  6614. }
  6615. }
  6616. }
  6617. //---------------------------------------------------------------------------
  6618. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6619. {
  6620. DebugAssert(!Terminal->CommandSessionOpened);
  6621. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6622. }
  6623. //---------------------------------------------------------------------------
  6624. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6625. {
  6626. bool Result = Terminal->IsCapable[Capability] ||
  6627. Terminal->CommandSessionOpened;
  6628. if (!Result)
  6629. {
  6630. // We might get here for example when "checksum" synchronization is requested from command-line
  6631. // on server that supports neither checksum nor shell
  6632. if (!Terminal->IsCapable[fcSecondaryShell])
  6633. {
  6634. NotSupported();
  6635. }
  6636. else if (!GUIConfiguration->ConfirmCommandSession)
  6637. {
  6638. Result = true;
  6639. }
  6640. else
  6641. {
  6642. TMessageParams Params(mpNeverAskAgainCheck);
  6643. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6644. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6645. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6646. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6647. if (Answer == qaNeverAskAgain)
  6648. {
  6649. GUIConfiguration->ConfirmCommandSession = false;
  6650. Result = true;
  6651. }
  6652. else if (Answer == qaOK)
  6653. {
  6654. Result = true;
  6655. }
  6656. }
  6657. if (Result)
  6658. {
  6659. Result = CommandSessionFallback();
  6660. }
  6661. }
  6662. return Result;
  6663. }
  6664. //---------------------------------------------------------------------------
  6665. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6666. {
  6667. if (EnsureCommandSessionFallback(fcAnyCommand))
  6668. {
  6669. DoConsoleDialog(Terminal, Command);
  6670. }
  6671. }
  6672. //---------------------------------------------------------------------------
  6673. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6674. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6675. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6676. {
  6677. if (!IsSideLocalBrowser(osRemote) &&
  6678. IsFileControl(DropSourceControl, osRemote) &&
  6679. (FDDExtMapFile != NULL))
  6680. {
  6681. Accept = true;
  6682. }
  6683. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6684. DebugAssert(FDDTargetControl != NULL);
  6685. }
  6686. //---------------------------------------------------------------------------
  6687. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6688. _di_IDataObject DataObj, int KeyState,
  6689. const TPoint & Point, int & Effect, bool & Accept)
  6690. {
  6691. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6692. }
  6693. //---------------------------------------------------------------------------
  6694. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6695. _di_IDataObject DataObj, int KeyState,
  6696. const TPoint & Point, int & Effect, bool & Accept)
  6697. {
  6698. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6699. }
  6700. //---------------------------------------------------------------------------
  6701. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6702. TObject * Sender)
  6703. {
  6704. DebugUsedParam(Sender);
  6705. DebugAssert(FDDTargetControl == Sender);
  6706. FDDTargetControl = NULL;
  6707. }
  6708. //---------------------------------------------------------------------------
  6709. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave(int)
  6710. {
  6711. FileControlDDDragLeave(SessionsPageControl);
  6712. }
  6713. //---------------------------------------------------------------------------
  6714. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave(int)
  6715. {
  6716. FileControlDDDragLeave(QueueView3);
  6717. }
  6718. //---------------------------------------------------------------------------
  6719. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6720. {
  6721. DebugAssert(!IsSideLocalBrowser(Side));
  6722. DebugUsedParam(Side);
  6723. bool Edit = false;
  6724. TRemoteFile * File = NULL;
  6725. UnicodeString FileName;
  6726. UnicodeString PointTo;
  6727. bool SymbolicLink = true;
  6728. if (RemoteDirView->ItemFocused)
  6729. {
  6730. DebugAssert(RemoteDirView->ItemFocused->Data);
  6731. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6732. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6733. if (Edit)
  6734. {
  6735. FileName = File->FileName;
  6736. PointTo = File->LinkTo;
  6737. }
  6738. else if (!File->IsParentDirectory)
  6739. {
  6740. PointTo = File->FileName;
  6741. }
  6742. }
  6743. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6744. Terminal->IsCapable[fcHardLink]))
  6745. {
  6746. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6747. if (Edit)
  6748. {
  6749. DebugAssert(File->FileName == FileName);
  6750. int Params = dfNoRecursive;
  6751. Terminal->ExceptionOnFail = true;
  6752. try
  6753. {
  6754. Terminal->DeleteFile(L"", File, &Params);
  6755. }
  6756. __finally
  6757. {
  6758. Terminal->ExceptionOnFail = false;
  6759. }
  6760. }
  6761. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6762. }
  6763. }
  6764. //---------------------------------------------------------------------------
  6765. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6766. {
  6767. return
  6768. (IsSideLocalBrowser(Side) ||
  6769. (HasAvailableTerminal() &&
  6770. Terminal->ResolvingSymlinks &&
  6771. Terminal->IsCapable[fcSymbolicLink]));
  6772. }
  6773. //---------------------------------------------------------------------------
  6774. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6775. {
  6776. return
  6777. !IsSideLocalBrowser(FCurrentSide) &&
  6778. (RemoteDirView->ItemFocused != NULL) &&
  6779. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6780. Terminal->SessionData->ResolveSymlinks;
  6781. }
  6782. //---------------------------------------------------------------------------
  6783. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6784. {
  6785. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6786. FForceExecution = true;
  6787. try
  6788. {
  6789. DirView(osCurrent)->ExecuteCurrentFile();
  6790. }
  6791. __finally
  6792. {
  6793. FForceExecution = false;
  6794. }
  6795. }
  6796. //---------------------------------------------------------------------------
  6797. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6798. {
  6799. TEditorData ExternalEditor;
  6800. ExternalEditor.Editor = edExternal;
  6801. bool Remember = false;
  6802. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6803. {
  6804. if (Remember)
  6805. {
  6806. TEditorList * EditorList = new TEditorList;
  6807. try
  6808. {
  6809. *EditorList = *WinConfiguration->EditorList;
  6810. bool Found = false;
  6811. int i = 0;
  6812. while (!Found && (i < EditorList->Count))
  6813. {
  6814. const TEditorPreferences * Editor = EditorList->Editors[i];
  6815. if ((Editor->Data->Editor == edExternal) &&
  6816. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6817. {
  6818. Found = true;
  6819. }
  6820. i++;
  6821. }
  6822. if (!Found)
  6823. {
  6824. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6825. WinConfiguration->EditorList = EditorList;
  6826. }
  6827. }
  6828. __finally
  6829. {
  6830. delete EditorList;
  6831. }
  6832. }
  6833. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6834. }
  6835. }
  6836. //---------------------------------------------------------------------------
  6837. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6838. {
  6839. if (FFileFindTerminal == ATerminal)
  6840. {
  6841. FFileFindTerminal = NULL;
  6842. HideFileFindDialog();
  6843. }
  6844. if (FClipboardTerminal == ATerminal)
  6845. {
  6846. ClipboardClear(); // implies ClipboardStop
  6847. }
  6848. if ((FOnSynchronizeAbort != NULL) &&
  6849. (ATerminal == FManagedSession))
  6850. {
  6851. FOnSynchronizeAbort(NULL);
  6852. }
  6853. }
  6854. //---------------------------------------------------------------------------
  6855. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6856. {
  6857. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6858. DetachTerminal(Sender);
  6859. }
  6860. //---------------------------------------------------------------------------
  6861. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6862. const UnicodeString DebugUsedArg(FileName), TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6863. {
  6864. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6865. if (Data->Terminal == Terminal)
  6866. {
  6867. Data->Terminal = ATerminal;
  6868. }
  6869. }
  6870. //---------------------------------------------------------------------------
  6871. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6872. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6873. {
  6874. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6875. DebugUsedParam(FileName);
  6876. DebugAssert(Terminal != NULL);
  6877. if (Data->Terminal == Terminal)
  6878. {
  6879. Data->Terminal = NULL;
  6880. }
  6881. }
  6882. //---------------------------------------------------------------------------
  6883. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6884. {
  6885. return NULL;
  6886. }
  6887. //---------------------------------------------------------------------------
  6888. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6889. {
  6890. UpdateControls();
  6891. SessionColor = TColor(0);
  6892. UpdateRemotePathComboBox(false);
  6893. NeedSession(false);
  6894. }
  6895. //---------------------------------------------------------------------------
  6896. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6897. {
  6898. try
  6899. {
  6900. // Cache, as the login dialog can change its value.
  6901. // See also DoShow. Also see TTerminalManager::NewSession.
  6902. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6903. try
  6904. {
  6905. if (ShowLogin)
  6906. {
  6907. bool ReloadSessions = !Startup;
  6908. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6909. }
  6910. }
  6911. __finally
  6912. {
  6913. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6914. // (so there was no chance for the user to open any session yet)
  6915. if ((ShowLogin || !Startup) &&
  6916. !WinConfiguration->KeepOpenWhenNoSession &&
  6917. // this rules out the implicit Commander's local-local browser
  6918. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6919. {
  6920. TerminateApplication();
  6921. }
  6922. }
  6923. }
  6924. catch (EAbort &)
  6925. {
  6926. // swallow
  6927. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6928. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6929. }
  6930. }
  6931. //---------------------------------------------------------------------------
  6932. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6933. {
  6934. TTerminalManager * Manager = TTerminalManager::Instance();
  6935. DebugAssert(!Manager->Updating);
  6936. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6937. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6938. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6939. SessionsPageControl->LockDrawing();
  6940. try
  6941. {
  6942. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6943. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6944. {
  6945. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6946. }
  6947. for (int Index = 0; Index <= Manager->Count; Index++)
  6948. {
  6949. TThemeTabSheet * TabSheet;
  6950. if (Index >= SessionsPageControl->PageCount)
  6951. {
  6952. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6953. TabSheet->PageControl = SessionsPageControl;
  6954. }
  6955. else
  6956. {
  6957. TabSheet = SessionsPageControl->Pages[Index];
  6958. }
  6959. bool IsSessionTab = (Index < Manager->Count);
  6960. if (IsSessionTab)
  6961. {
  6962. TTerminal * Terminal = Manager->Sessions[Index];
  6963. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6964. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  6965. UpdateSessionTab(TabSheet);
  6966. }
  6967. else
  6968. {
  6969. TabSheet->Tag = 0; // not really needed
  6970. TabSheet->Shadowed = false;
  6971. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6972. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  6973. // We know that we are at the last page, otherwise we could not call this (it assumes that new session tab is the last one)
  6974. UpdateNewTabTab();
  6975. }
  6976. }
  6977. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6978. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6979. {
  6980. SessionsPageControl->UpdateTabsCaptionTruncation();
  6981. }
  6982. }
  6983. __finally
  6984. {
  6985. SessionsPageControl->UnlockDrawing();
  6986. }
  6987. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6988. }
  6989. //---------------------------------------------------------------------------
  6990. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  6991. {
  6992. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  6993. }
  6994. //---------------------------------------------------------------------------
  6995. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6996. {
  6997. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6998. }
  6999. //---------------------------------------------------------------------------
  7000. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  7001. {
  7002. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  7003. }
  7004. //---------------------------------------------------------------------------
  7005. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  7006. {
  7007. TThemeTabSheet * TabSheet = GetNewTabTab();
  7008. UnicodeString TabCaption;
  7009. if (WinConfiguration->SelectiveToolbarText)
  7010. {
  7011. TabCaption = GetNewTabTabCaption();
  7012. }
  7013. TabSheet->BaseCaption = TabCaption;
  7014. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  7015. }
  7016. //---------------------------------------------------------------------------
  7017. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  7018. {
  7019. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  7020. }
  7021. //---------------------------------------------------------------------------
  7022. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  7023. {
  7024. DebugFail();
  7025. return UnicodeString();
  7026. }
  7027. //---------------------------------------------------------------------------
  7028. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  7029. {
  7030. if (DebugAlwaysTrue(TabSheet != NULL))
  7031. {
  7032. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  7033. if (DebugAlwaysTrue(ASession != NULL))
  7034. {
  7035. TColor Color = (ASession == Terminal) ? FSessionColor : static_cast<TColor>(ASession->StateData->Color);
  7036. if (ASession->LocalBrowser)
  7037. {
  7038. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  7039. }
  7040. else
  7041. {
  7042. TabSheet->ImageIndex = AddSessionColor(Color);
  7043. }
  7044. TTerminalManager * Manager = TTerminalManager::Instance();
  7045. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  7046. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  7047. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  7048. }
  7049. }
  7050. }
  7051. //---------------------------------------------------------------------------
  7052. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  7053. {
  7054. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  7055. }
  7056. //---------------------------------------------------------------------------
  7057. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  7058. {
  7059. DebugAssert(SessionsPageControl->ActivePage != NULL);
  7060. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  7061. bool Result = (Session != NULL);
  7062. if (Result)
  7063. {
  7064. TTerminalManager::Instance()->ActiveSession = Session;
  7065. }
  7066. else
  7067. {
  7068. try
  7069. {
  7070. NewTab();
  7071. }
  7072. __finally
  7073. {
  7074. SessionListChanged();
  7075. }
  7076. FSessionsPageControlNewTabTime = Now();
  7077. }
  7078. return Result;
  7079. }
  7080. //---------------------------------------------------------------------------
  7081. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  7082. {
  7083. TWindowLock Lock(this);
  7084. SessionTabSwitched();
  7085. }
  7086. //---------------------------------------------------------------------------
  7087. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  7088. {
  7089. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  7090. DebugAssert(TransferList != NULL);
  7091. UnicodeString Name;
  7092. if (TransferList->ItemIndex <= 0)
  7093. {
  7094. Name = L"";
  7095. }
  7096. else
  7097. {
  7098. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7099. }
  7100. if (FCopyParamAutoSelected.IsEmpty())
  7101. {
  7102. // if previous preset was not autoselected, make new preset the "default"
  7103. FCopyParamDefault = Name;
  7104. }
  7105. GUIConfiguration->CopyParamCurrent = Name;
  7106. }
  7107. //---------------------------------------------------------------------------
  7108. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7109. {
  7110. // sanity check
  7111. bool ExistingPreset =
  7112. (FTransferListHoverIndex >= 0) &&
  7113. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7114. DebugAssert(ExistingPreset);
  7115. if (ExistingPreset)
  7116. {
  7117. HDC DC = GetDC(0);
  7118. TCanvas * Canvas = new TCanvas();
  7119. try
  7120. {
  7121. Canvas->Handle = DC;
  7122. Canvas->Font = GetToolbarFont(this);
  7123. UnicodeString Name;
  7124. if (FTransferListHoverIndex == 0)
  7125. {
  7126. Name = L"";
  7127. }
  7128. else
  7129. {
  7130. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7131. }
  7132. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7133. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7134. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7135. static_cast<TObject*>(GetComponent(fcTransferList)));
  7136. UnicodeString InfoStr =
  7137. GUIConfiguration->CopyParamPreset[Name].
  7138. GetInfoStr(L"; ",
  7139. FLAGMASK(HasAvailableTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7140. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7141. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7142. {
  7143. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7144. {
  7145. InfoStr.SetLength(InfoStr.Length() - 1);
  7146. }
  7147. InfoStr += Ellipsis;
  7148. }
  7149. // UpdateCaption does not cause invalidation of whole submenu, while
  7150. // setting Caption property does.
  7151. // also it probably does not resize the label, even if necessary
  7152. // (we do not want that anyway)
  7153. TransferLabel->UpdateCaption(InfoStr);
  7154. }
  7155. __finally
  7156. {
  7157. Canvas->Handle = NULL;
  7158. ReleaseDC(0, DC);
  7159. delete Canvas;
  7160. }
  7161. }
  7162. }
  7163. //---------------------------------------------------------------------------
  7164. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7165. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7166. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7167. {
  7168. if (FTransferListHoverIndex != AHoverIndex)
  7169. {
  7170. FTransferListHoverIndex = AHoverIndex;
  7171. UpdateTransferLabel();
  7172. }
  7173. }
  7174. //---------------------------------------------------------------------------
  7175. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7176. {
  7177. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7178. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7179. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7180. {
  7181. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7182. {
  7183. if (!NonVisualDataModule->Busy)
  7184. {
  7185. OpenDirectory(GetSide(osCurrent));
  7186. }
  7187. Message.Result = 1;
  7188. }
  7189. else
  7190. {
  7191. TForm::Dispatch(&Message);
  7192. }
  7193. }
  7194. else
  7195. {
  7196. TForm::Dispatch(&Message);
  7197. }
  7198. }
  7199. //---------------------------------------------------------------------------
  7200. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7201. {
  7202. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7203. if ((FIgnoreNextDialogChar != 0) &&
  7204. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7205. {
  7206. Message.Result = 1;
  7207. }
  7208. else
  7209. {
  7210. TForm::Dispatch(&Message);
  7211. }
  7212. FIgnoreNextDialogChar = 0;
  7213. }
  7214. //---------------------------------------------------------------------------
  7215. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7216. {
  7217. // The four low-order bits are used internally by Windows
  7218. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7219. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7220. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7221. // 61730 - restore thru double click - undocumented
  7222. // 61490 - maximize thru double click - undocumented
  7223. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7224. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7225. {
  7226. SysResizing(Cmd);
  7227. }
  7228. TForm::Dispatch(&Message);
  7229. }
  7230. //---------------------------------------------------------------------------
  7231. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7232. {
  7233. AppLog(L"Windows session end query");
  7234. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7235. // Also there no point returning TRUE as we are not able to
  7236. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7237. // Hence the process termination might be safer :)
  7238. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7239. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7240. {
  7241. Message.Result = FALSE;
  7242. }
  7243. else
  7244. {
  7245. Message.Result = TRUE;
  7246. }
  7247. // Do not call default handling as that triggers OnCloseQuery,
  7248. // where our implementation will popup confirmation dialogs, what we do not want,
  7249. // as per Vista guidelines:
  7250. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7251. }
  7252. //---------------------------------------------------------------------------
  7253. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7254. {
  7255. AppLog(L"Windows session end");
  7256. if (Message.EndSession && IsApplicationMinimized())
  7257. {
  7258. // WORKAROUND
  7259. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7260. // when it receives WM_ENDSESSION,
  7261. // but that sometimes (particularly when application is minimized) cause crashes.
  7262. // Crash popups message that blocks log off.
  7263. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7264. // so we call ExitProcess() immediately, not even trying to cleanup.
  7265. // It still causes beep, so there's likely some popup, but it does not block
  7266. // log off.
  7267. ExitProcess(0);
  7268. }
  7269. TForm::Dispatch(&Message);
  7270. }
  7271. //---------------------------------------------------------------------------
  7272. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7273. {
  7274. }
  7275. //---------------------------------------------------------------------------
  7276. void __fastcall TCustomScpExplorerForm::DoShow()
  7277. {
  7278. // Called from TCustomScpExplorerForm::CMShowingChanged
  7279. // only now are the controls resized finally, so the size constraints
  7280. // will not conflict with possibly very small window size
  7281. RestoreFormParams();
  7282. // This indicates that the form was rescaled after parameters were loaded and
  7283. // as most probably the parameters were actually saved with the current form scaling
  7284. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7285. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7286. // and no rounding problems will occur.
  7287. // See also RestoreForm.
  7288. // (we should be safe to call RestoreParams unconditionally)
  7289. if (PixelsPerInch != Screen->PixelsPerInch)
  7290. {
  7291. RestoreParams();
  7292. }
  7293. FixControlsPlacement();
  7294. if (Position == poDefaultPosOnly)
  7295. {
  7296. CutFormToDesktop(this);
  7297. }
  7298. TForm::DoShow();
  7299. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7300. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7301. // This was previously in NeedSession, where other related code is.
  7302. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7303. // unpleasantly shows briefly.
  7304. if ((ManagedSession == NULL) &&
  7305. !WinConfiguration->ShowLoginWhenNoSession &&
  7306. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7307. // This detects if workspace was saved the last time the main widow was closed
  7308. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7309. {
  7310. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7311. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7312. }
  7313. // Before main window displays
  7314. if (ManagedSession == NULL)
  7315. {
  7316. StartingWithoutSession();
  7317. }
  7318. UpdatePixelsPerInchMainWindowCounter();
  7319. FShowing = true;
  7320. }
  7321. //---------------------------------------------------------------------------
  7322. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7323. {
  7324. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7325. }
  7326. //---------------------------------------------------------------------------
  7327. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7328. {
  7329. SessionListChanged();
  7330. InitStatusBar();
  7331. UpdateControls();
  7332. }
  7333. //---------------------------------------------------------------------------
  7334. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7335. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7336. TNotifyEvent OnBalloonClick, TObject * UserData)
  7337. {
  7338. bool Do;
  7339. UnicodeString Message;
  7340. if (E == NULL)
  7341. {
  7342. Message = Str;
  7343. Do = true;
  7344. }
  7345. else
  7346. {
  7347. Do = ExceptionMessage(E, Message);
  7348. }
  7349. if (Do && WinConfiguration->BalloonNotifications)
  7350. {
  7351. UnicodeString Title;
  7352. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7353. {
  7354. Message = TrimLeft(Message);
  7355. }
  7356. else
  7357. {
  7358. Message = UnformatMessage(Message);
  7359. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7360. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7361. Title = LoadResourceString(Captions[Type]);
  7362. if (Terminal != NULL)
  7363. {
  7364. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7365. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7366. }
  7367. }
  7368. if (Seconds == 0)
  7369. {
  7370. Seconds = WinConfiguration->NotificationsTimeout;
  7371. }
  7372. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7373. }
  7374. }
  7375. //---------------------------------------------------------------------------
  7376. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7377. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7378. UnicodeString HelpKeyword, const TMessageParams * Params,
  7379. TTerminal * Terminal)
  7380. {
  7381. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7382. (FOnFeedSynchronizeError != NULL)) &&
  7383. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7384. {
  7385. if (FOnFeedSynchronizeError != NULL)
  7386. {
  7387. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7388. }
  7389. else
  7390. {
  7391. DebugAssert(FErrorList != NULL);
  7392. TStringList * MoreMessagesCopy = NULL;
  7393. if (MoreMessages)
  7394. {
  7395. MoreMessagesCopy = new TStringList();
  7396. MoreMessagesCopy->Assign(MoreMessages);
  7397. }
  7398. FErrorList->AddObject(Message, MoreMessagesCopy);
  7399. }
  7400. PopupTrayBalloon(Terminal, Message, Type);
  7401. return ContinueAnswer(Answers);
  7402. }
  7403. else
  7404. {
  7405. bool UseBalloon = FTrayIcon->Visible;
  7406. if (UseBalloon)
  7407. {
  7408. PopupTrayBalloon(Terminal, Message, Type);
  7409. }
  7410. unsigned int Result;
  7411. try
  7412. {
  7413. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7414. }
  7415. __finally
  7416. {
  7417. // cancel only balloon we popped up, otherwise we may cancel notification
  7418. // balloon that was there before the message dialog
  7419. // (such as "dd confirmation opt in balloon)
  7420. if (UseBalloon)
  7421. {
  7422. FTrayIcon->CancelBalloon();
  7423. }
  7424. }
  7425. return Result;
  7426. }
  7427. }
  7428. //---------------------------------------------------------------------------
  7429. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7430. TTerminal * Terminal, Exception * E)
  7431. {
  7432. if (FTrayIcon->Visible)
  7433. {
  7434. PopupTrayBalloon(Terminal, L"", qtError, E);
  7435. }
  7436. // particularly prevent opening new session from jump list,
  7437. // while exception is shown
  7438. NonVisualDataModule->StartBusy();
  7439. try
  7440. {
  7441. ShowExtendedExceptionEx(Terminal, E);
  7442. }
  7443. __finally
  7444. {
  7445. NonVisualDataModule->EndBusy();
  7446. FTrayIcon->CancelBalloon();
  7447. }
  7448. }
  7449. //---------------------------------------------------------------------------
  7450. void __fastcall TCustomScpExplorerForm::SessionReady()
  7451. {
  7452. InitStatusBar();
  7453. // cannot rely on active page being page for active terminal,
  7454. // as it can happen that active page is the "new session" page
  7455. // (e.g. when reconnecting active terminal, while login dialog
  7456. // invoked from "new session" page is modal)
  7457. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7458. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7459. }
  7460. //---------------------------------------------------------------------------
  7461. void TCustomScpExplorerForm::InactiveTerminalNotify(
  7462. TManagedTerminal * Terminal, const UnicodeString & Message, TQueryType Type, Exception * E)
  7463. {
  7464. Notify(Terminal, Message, Type, false, NULL, NULL, E);
  7465. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7466. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7467. {
  7468. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7469. }
  7470. }
  7471. //---------------------------------------------------------------------------
  7472. void TCustomScpExplorerForm::Notify(
  7473. TManagedTerminal * Terminal, const UnicodeString & AMessage, TQueryType Type,
  7474. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7475. {
  7476. UnicodeString Message = AMessage;
  7477. if ((E == NULL) ||
  7478. ExceptionMessage(E, Message))
  7479. {
  7480. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7481. if (Important)
  7482. {
  7483. Seconds *= 5;
  7484. }
  7485. UnicodeString NoteMessage(UnformatMessage(Message));
  7486. if (Terminal != NULL)
  7487. {
  7488. NoteMessage = TTerminalManager::Instance()->FormatTerminalNoteMessage(Terminal, NoteMessage);
  7489. }
  7490. if (WinConfiguration->BalloonNotifications)
  7491. {
  7492. AddNote(NoteMessage);
  7493. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7494. }
  7495. else
  7496. {
  7497. FlashOnBackground();
  7498. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7499. }
  7500. }
  7501. }
  7502. //---------------------------------------------------------------------------
  7503. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7504. {
  7505. RestoreApp();
  7506. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7507. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7508. !NonVisualDataModule->Busy)
  7509. {
  7510. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7511. TTerminalManager::Instance()->ActiveSession = Terminal;
  7512. if (!ComponentVisible[fcQueueView])
  7513. {
  7514. ToggleQueueVisibility();
  7515. GoToQueue();
  7516. }
  7517. }
  7518. }
  7519. //---------------------------------------------------------------------------
  7520. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7521. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7522. {
  7523. UnicodeString Message;
  7524. TNotifyEvent OnClick = NULL;
  7525. TObject * UserData = NULL;
  7526. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7527. switch (Event)
  7528. {
  7529. case qeEmptyButMonitored:
  7530. if ((ATerminal != Terminal) || QueueInvisible)
  7531. {
  7532. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7533. OnClick = QueueEmptyNoteClicked;
  7534. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7535. TerminalNoteData->Terminal = ATerminal;
  7536. UserData = TerminalNoteData;
  7537. }
  7538. break;
  7539. case qeEmpty:
  7540. OperationComplete(ATerminal->QueueOperationStart);
  7541. break;
  7542. case qePendingUserAction:
  7543. if ((ATerminal != Terminal) ||
  7544. (QueueInvisible && !IsQueueAutoPopup()))
  7545. {
  7546. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7547. }
  7548. break;
  7549. default:
  7550. DebugFail();
  7551. }
  7552. if (!Message.IsEmpty())
  7553. {
  7554. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7555. }
  7556. }
  7557. //---------------------------------------------------------------------------
  7558. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7559. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7560. {
  7561. if (FDDExtMapFile != NULL)
  7562. {
  7563. CloseHandle(FDDExtMapFile);
  7564. FDDExtMapFile = NULL;
  7565. }
  7566. if (WinConfiguration->DDFakeFile)
  7567. {
  7568. DDFakeFileInitDrag(FileList, Created);
  7569. }
  7570. }
  7571. //---------------------------------------------------------------------------
  7572. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7573. {
  7574. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7575. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7576. {
  7577. FFakeFileDropTarget = FileName;
  7578. }
  7579. }
  7580. //---------------------------------------------------------------------------
  7581. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7582. {
  7583. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7584. if (!ForceDirectories(ApiPath(Result)))
  7585. {
  7586. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7587. }
  7588. FileSetAttr(ApiPath(Result), faHidden);
  7589. return Result;
  7590. }
  7591. //---------------------------------------------------------------------------
  7592. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7593. bool & Created)
  7594. {
  7595. FFakeFileDropTarget = UnicodeString();
  7596. FDragFakeDirectory = CreateFakeTransferDirectory();
  7597. FileList->AddItem(NULL, FDragFakeDirectory);
  7598. Created = true;
  7599. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7600. {
  7601. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7602. }
  7603. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7604. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7605. {
  7606. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7607. TDragExtCommStruct* CommStruct;
  7608. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7609. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7610. DebugAssert(CommStruct != NULL);
  7611. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7612. CommStruct->Dragging = true;
  7613. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7614. LENOF(CommStruct->DropDest));
  7615. NULL_TERMINATE(CommStruct->DropDest);
  7616. UnmapViewOfFile(CommStruct);
  7617. }
  7618. }
  7619. //---------------------------------------------------------------------------
  7620. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7621. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7622. {
  7623. bool Result;
  7624. DebugAssert(!IsLocalBrowserMode());
  7625. if (Sender == RemoteDirView)
  7626. {
  7627. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7628. }
  7629. else
  7630. {
  7631. DebugAssert(Sender == RemoteDriveView);
  7632. TStrings * FileList = RemoteDriveView->DragFileList();
  7633. try
  7634. {
  7635. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7636. }
  7637. __finally
  7638. {
  7639. delete FileList;
  7640. }
  7641. }
  7642. if (FDDTargetControl == RemoteDriveView)
  7643. {
  7644. RemoteDriveView->UpdateDropTarget();
  7645. }
  7646. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7647. // or from tree view to dir view.
  7648. // foMove happens when file/dir is dragged from remote tree view outside of
  7649. // application via dragex
  7650. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7651. (DropSourceControl == RemoteDriveView))
  7652. {
  7653. RemoteDriveView->UpdateDropSource();
  7654. }
  7655. return Result;
  7656. }
  7657. //---------------------------------------------------------------------------
  7658. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7659. {
  7660. DebugAssert(!IsLocalBrowserMode());
  7661. // This also handles drops of remote files to queue.
  7662. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7663. SAFE_DESTROY(FDDFileList);
  7664. if (!FFakeFileDropTarget.IsEmpty())
  7665. {
  7666. RemoveDir(ApiPath(FFakeFileDropTarget));
  7667. }
  7668. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7669. {
  7670. try
  7671. {
  7672. TDragResult DDResult = (Sender == RemoteDirView) ?
  7673. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7674. // Focus is moved to the target application,
  7675. // but as we are going to present the UI, we need to steal the focus back.
  7676. // This most likely won't work though (windows does not allow application
  7677. // to steal focus most of the time)
  7678. Application->BringToFront();
  7679. // On older version of Windows we never got drMove here, see also comment below.
  7680. // On Windows 10, we get the "move".
  7681. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7682. {
  7683. UnicodeString TargetDirectory;
  7684. TFileOperation Operation;
  7685. // drInvalid may mean drMove, see comment below
  7686. switch (DDResult)
  7687. {
  7688. case drCopy:
  7689. Operation = foCopy;
  7690. break;
  7691. case drMove:
  7692. Operation = foMove;
  7693. break;
  7694. default:
  7695. DebugFail();
  7696. case drInvalid:
  7697. // prefer "copy" for safety
  7698. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7699. break;
  7700. }
  7701. TTransferOperationParam Param;
  7702. UnicodeString CounterName;
  7703. bool ForceQueue;
  7704. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7705. {
  7706. // we get drInvalid both if d&d was intercepted by ddext,
  7707. // and when users drops on no-drop location.
  7708. // we tell the difference by existence of response from ddext,
  7709. // so we ignore absence of response in this case
  7710. if (DDResult != drInvalid)
  7711. {
  7712. // here we know that the extension is installed,
  7713. // as it is checked as soon as drag&drop starts from
  7714. // RemoteFileControlDDCreateDragFileList
  7715. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7716. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7717. {
  7718. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7719. }
  7720. else
  7721. {
  7722. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7723. }
  7724. }
  7725. }
  7726. else
  7727. {
  7728. // download using fake file
  7729. Param.Temp = false;
  7730. Param.DragDrop = true;
  7731. if (ForceQueue)
  7732. {
  7733. Param.Queue = asOn;
  7734. }
  7735. if (Sender == RemoteDirView)
  7736. {
  7737. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7738. }
  7739. if (RemoteFileControlFileOperation(Sender, Operation,
  7740. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7741. {
  7742. Configuration->Usage->Inc(CounterName);
  7743. }
  7744. }
  7745. }
  7746. }
  7747. __finally
  7748. {
  7749. CloseHandle(FDDExtMapFile);
  7750. FDDExtMapFile = NULL;
  7751. delete FDragFakeMonitors;
  7752. FDragFakeMonitors = NULL;
  7753. RemoveDir(ApiPath(FDragFakeDirectory));
  7754. FDragFakeDirectory = L"";
  7755. FFakeFileDropTarget = UnicodeString();
  7756. }
  7757. }
  7758. if (FDragDropSshTerminate.get() != NULL)
  7759. {
  7760. FDragDropSshTerminate->Rethrow();
  7761. }
  7762. }
  7763. //---------------------------------------------------------------------------
  7764. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7765. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7766. {
  7767. // Remember drop effect so we know (when user drops files), if we copy or move
  7768. FLastDropEffect = dwEffect;
  7769. }
  7770. //---------------------------------------------------------------------------
  7771. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7772. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7773. {
  7774. bool Result;
  7775. if (FDDTargetControl == QueueView3)
  7776. {
  7777. Directory = DefaultDownloadTargetDirectory();
  7778. Result = true;
  7779. CounterName = L"DownloadsDragDropQueue";
  7780. ForceQueue = true;
  7781. }
  7782. else if (!FFakeFileDropTarget.IsEmpty())
  7783. {
  7784. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7785. Result = true;
  7786. ForceQueue = false;
  7787. CounterName = L"DownloadsDragDropFakeFile";
  7788. }
  7789. else
  7790. {
  7791. ForceQueue = false;
  7792. Enabled = false;
  7793. try
  7794. {
  7795. int Timer = 0;
  7796. Result = false;
  7797. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7798. {
  7799. {
  7800. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7801. TDragExtCommStruct* CommStruct;
  7802. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7803. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7804. DebugAssert(CommStruct != NULL);
  7805. Result = !CommStruct->Dragging;
  7806. if (Result)
  7807. {
  7808. Directory = ExtractFilePath(CommStruct->DropDest);
  7809. CounterName = L"DownloadsDragDropExternalExt";
  7810. }
  7811. UnmapViewOfFile(CommStruct);
  7812. }
  7813. if (!Result)
  7814. {
  7815. Sleep(50);
  7816. Timer += 50;
  7817. Application->ProcessMessages();
  7818. }
  7819. }
  7820. }
  7821. __finally
  7822. {
  7823. Enabled = true;
  7824. }
  7825. }
  7826. return Result;
  7827. }
  7828. //---------------------------------------------------------------------------
  7829. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7830. const UnicodeString TempDir, int SecDelay)
  7831. {
  7832. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7833. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7834. if (FDelayedDeletionTimer == NULL)
  7835. {
  7836. DebugAssert(HandleAllocated());
  7837. FDelayedDeletionTimer = new TTimer(this);
  7838. FDelayedDeletionTimer->Interval = 10000;
  7839. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7840. }
  7841. else
  7842. {
  7843. FDelayedDeletionTimer->Enabled = true;
  7844. }
  7845. }
  7846. //---------------------------------------------------------------------------
  7847. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7848. {
  7849. DebugAssert(FDelayedDeletionList != NULL);
  7850. TDateTime N = Now();
  7851. TDateTime Alert;
  7852. UnicodeString Directory;
  7853. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7854. {
  7855. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7856. if ((N >= Alert) || (Sender == NULL))
  7857. {
  7858. Directory = FDelayedDeletionList->Strings[Index];
  7859. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7860. {
  7861. FDelayedDeletionList->Delete(Index);
  7862. }
  7863. }
  7864. }
  7865. if (FDelayedDeletionList->Count == 0)
  7866. {
  7867. FDelayedDeletionTimer->Enabled = false;
  7868. }
  7869. }
  7870. //---------------------------------------------------------------------------
  7871. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7872. {
  7873. DebugAssert(!IsLocalBrowserMode());
  7874. if (IsFileControl(FDDTargetControl, osRemote) ||
  7875. (FDDTargetControl == SessionsPageControl))
  7876. {
  7877. TManagedTerminal * TargetTerminal = NULL;
  7878. TFileOperation Operation = foNone;
  7879. if (FDDTargetControl == SessionsPageControl)
  7880. {
  7881. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7882. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7883. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7884. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7885. if (IsAvailableTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7886. {
  7887. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7888. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7889. {
  7890. Operation = foRemoteMove;
  7891. }
  7892. else
  7893. {
  7894. Operation = foRemoteCopy;
  7895. }
  7896. }
  7897. }
  7898. else
  7899. {
  7900. if (FLastDropEffect == DROPEFFECT_MOVE)
  7901. {
  7902. Operation = foRemoteMove;
  7903. }
  7904. else if (FLastDropEffect == DROPEFFECT_COPY)
  7905. {
  7906. Operation = foRemoteCopy;
  7907. }
  7908. }
  7909. if (Operation != foNone)
  7910. {
  7911. RemoteFileControlFileOperation(DropSourceControl,
  7912. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7913. }
  7914. // abort drag&drop
  7915. Abort();
  7916. }
  7917. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7918. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7919. (FDDTargetControl != QueueView3))
  7920. {
  7921. DebugAssert(!FDragTempDir.IsEmpty());
  7922. TTransferType Type;
  7923. UnicodeString TempDir = FDragTempDir;
  7924. // We clear FDragTempDir before calling
  7925. // just in case it fail (raises exception)
  7926. FDragTempDir = L"";
  7927. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7928. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7929. // empty directory parameter means temp directory -> don't display it!
  7930. UnicodeString TargetDir = L"";
  7931. int Options = 0;
  7932. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7933. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7934. {
  7935. Abort();
  7936. }
  7937. // TargetDir is set when dropped on local file control
  7938. // (this was workaround for legacy dirview event handling, now it should be
  7939. // made prettier)
  7940. if (TargetDir.IsEmpty())
  7941. {
  7942. TargetDir = TempDir;
  7943. if (ForceDirectories(ApiPath(TargetDir)))
  7944. {
  7945. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7946. FPendingTempSpaceWarn = true;
  7947. try
  7948. {
  7949. FDragDropOperation = true;
  7950. int Params = cpTemporary |
  7951. (Type == ttMove ? cpDelete : 0);
  7952. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7953. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7954. }
  7955. __finally
  7956. {
  7957. FDragDropOperation = false;
  7958. FPendingTempSpaceWarn = false;
  7959. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7960. }
  7961. }
  7962. else
  7963. {
  7964. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7965. }
  7966. }
  7967. }
  7968. }
  7969. //---------------------------------------------------------------------------
  7970. void __fastcall TCustomScpExplorerForm::DDDownload(
  7971. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7972. {
  7973. DebugAssert(!IsLocalBrowserMode());
  7974. TAutoBatch AutoBatch(this);
  7975. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7976. UpdateCopyParamCounters(*CopyParam);
  7977. FMoveToQueue = false;
  7978. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7979. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7980. {
  7981. RemoteDriveView->UpdateDropSource();
  7982. }
  7983. }
  7984. //---------------------------------------------------------------------------
  7985. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7986. {
  7987. public:
  7988. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7989. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7990. {
  7991. }
  7992. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7993. {
  7994. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7995. TDataObjectFilesEx::AllowData(FormatEtc);
  7996. }
  7997. };
  7998. //---------------------------------------------------------------------------
  7999. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  8000. TObject * Sender, TDataObject *& DataObject)
  8001. {
  8002. if (FDDExtMapFile != NULL)
  8003. {
  8004. TFileList * FileList = DragDropFiles(Sender)->FileList;
  8005. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  8006. {
  8007. Abort();
  8008. }
  8009. if (FileList->Count > 0)
  8010. {
  8011. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  8012. if (!FilesObject->IsValid(true, true))
  8013. {
  8014. FilesObject->_Release();
  8015. }
  8016. else
  8017. {
  8018. DataObject = FilesObject;
  8019. }
  8020. }
  8021. }
  8022. }
  8023. //---------------------------------------------------------------------------
  8024. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  8025. {
  8026. DebugFail();
  8027. }
  8028. //---------------------------------------------------------------------------
  8029. void __fastcall TCustomScpExplorerForm::GoToTree()
  8030. {
  8031. ComponentVisible[fcRemoteTree] = true;
  8032. DriveView(osRemote)->SetFocus();
  8033. }
  8034. //---------------------------------------------------------------------------
  8035. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  8036. TPanelExport Export)
  8037. {
  8038. TCustomDirView * DirView = this->DirView(Side);
  8039. std::unique_ptr<TStrings> ExportData(new TStringList());
  8040. switch (Export)
  8041. {
  8042. case pePath:
  8043. ExportData->Add(DirView->PathName);
  8044. break;
  8045. case peFileList:
  8046. case peFullFileList:
  8047. {
  8048. bool FullPath = (Export == peFullFileList);
  8049. DirView->CreateFileList(false, FullPath, ExportData.get());
  8050. for (int Index = 0; Index < ExportData->Count; Index++)
  8051. {
  8052. if (ExportData->Strings[Index].Pos(L" ") > 0)
  8053. {
  8054. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  8055. }
  8056. }
  8057. }
  8058. break;
  8059. default:
  8060. DebugFail();
  8061. }
  8062. return ExportData.release();
  8063. }
  8064. //---------------------------------------------------------------------------
  8065. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  8066. TPanelExport Export, TPanelExportDestination Destination)
  8067. {
  8068. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  8069. PanelExportStore(Side, Export, Destination, ExportData.get());
  8070. }
  8071. //---------------------------------------------------------------------------
  8072. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  8073. TPanelExport /*Export*/, TPanelExportDestination Destination,
  8074. TStrings * ExportData)
  8075. {
  8076. if (Destination == pedClipboard)
  8077. {
  8078. TInstantOperationVisualizer Visualizer;
  8079. CopyToClipboard(ExportData);
  8080. }
  8081. else
  8082. {
  8083. DebugFail();
  8084. }
  8085. }
  8086. //---------------------------------------------------------------------------
  8087. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8088. {
  8089. TCustomDirView * DirView = this->DirView(Side);
  8090. UnicodeString Mask = DirView->Mask;
  8091. if (DoFilterMaskDialog(DirView, Mask))
  8092. {
  8093. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8094. Configuration->Usage->Inc(L"Filters");
  8095. }
  8096. }
  8097. //---------------------------------------------------------------------------
  8098. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8099. {
  8100. return FQueueController->DefaultOperation();
  8101. }
  8102. //---------------------------------------------------------------------------
  8103. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8104. TQueueOperation Operation, unsigned long * Param)
  8105. {
  8106. switch (Operation)
  8107. {
  8108. case qoPreferences:
  8109. return true;
  8110. case qoGoTo:
  8111. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8112. case qoOnceEmpty:
  8113. return IsAnythingQueued();
  8114. default:
  8115. return FQueueController->AllowOperation(Operation, Param);
  8116. }
  8117. }
  8118. //---------------------------------------------------------------------------
  8119. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8120. {
  8121. if (DebugAlwaysTrue(QueueView3->Visible))
  8122. {
  8123. QueueView3->SetFocus();
  8124. }
  8125. }
  8126. //---------------------------------------------------------------------------
  8127. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8128. TQueueOperation Operation, unsigned long Param)
  8129. {
  8130. if (Operation == qoGoTo)
  8131. {
  8132. GoToQueue();
  8133. }
  8134. else if (Operation == qoPreferences)
  8135. {
  8136. PreferencesDialog(pmQueue);
  8137. }
  8138. else
  8139. {
  8140. FQueueController->ExecuteOperation(Operation, Param);
  8141. }
  8142. }
  8143. //---------------------------------------------------------------------------
  8144. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8145. {
  8146. return (Queue != NULL) && Queue->Enabled;
  8147. }
  8148. //---------------------------------------------------------------------------
  8149. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8150. {
  8151. DebugAssert(Queue != NULL);
  8152. if (Queue != NULL)
  8153. {
  8154. Queue->Enabled = !Queue->Enabled;
  8155. }
  8156. }
  8157. //---------------------------------------------------------------------------
  8158. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8159. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8160. {
  8161. FQueueActedItem = QueueView3->ItemFocused;
  8162. }
  8163. //---------------------------------------------------------------------------
  8164. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8165. {
  8166. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8167. }
  8168. //---------------------------------------------------------------------------
  8169. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8170. {
  8171. return
  8172. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8173. (QueueDock->Visible ? QueueDock->Height : 0) +
  8174. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8175. }
  8176. //---------------------------------------------------------------------------
  8177. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8178. {
  8179. return ScaleByTextHeight(this, 48);
  8180. }
  8181. //---------------------------------------------------------------------------
  8182. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8183. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8184. {
  8185. // when queue is hidden by double-clicking splitter, stray attempt to
  8186. // resize the panel with strange value arrives, make sure it is ignored
  8187. if (ComponentVisible[fcQueueView])
  8188. {
  8189. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8190. if (NewSize > MaxHeightLimit)
  8191. {
  8192. NewSize = MaxHeightLimit;
  8193. }
  8194. int MinHeightLimit =
  8195. GetStaticQueuePanelComponentsHeight() +
  8196. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8197. GetMinQueueViewHeight();
  8198. if (NewSize < MinHeightLimit)
  8199. {
  8200. NewSize = MinHeightLimit;
  8201. }
  8202. }
  8203. else
  8204. {
  8205. Accept = false;
  8206. }
  8207. }
  8208. //---------------------------------------------------------------------------
  8209. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8210. {
  8211. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8212. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8213. if (QueueViewHeight < GetMinQueueViewHeight())
  8214. {
  8215. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8216. }
  8217. }
  8218. //---------------------------------------------------------------------------
  8219. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8220. TDragObject *& /*DragObject*/)
  8221. {
  8222. FQueueActedItem = QueueView3->ItemFocused;
  8223. FQueueScrollOnDragOver->StartDrag();
  8224. }
  8225. //---------------------------------------------------------------------------
  8226. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8227. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8228. {
  8229. FQueueScrollOnDragOver->EndDrag();
  8230. }
  8231. //---------------------------------------------------------------------------
  8232. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8233. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8234. {
  8235. Accept = true;
  8236. if (Source == QueueView3)
  8237. {
  8238. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8239. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8240. if (Accept)
  8241. {
  8242. TQueueItemProxy * QueueItem;
  8243. TQueueItemProxy * DestQueueItem;
  8244. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8245. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8246. Accept = (QueueItem != DestQueueItem) &&
  8247. (QueueItem->Status == TQueueItem::qsPending) &&
  8248. (DestQueueItem->Status == TQueueItem::qsPending);
  8249. }
  8250. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8251. }
  8252. }
  8253. //---------------------------------------------------------------------------
  8254. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8255. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8256. {
  8257. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8258. {
  8259. TQueueItemProxy * QueueItem;
  8260. TQueueItemProxy * DestQueueItem;
  8261. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8262. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8263. QueueItem->Move(DestQueueItem);
  8264. }
  8265. }
  8266. //---------------------------------------------------------------------------
  8267. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8268. {
  8269. if ((QueueView3->ItemFocused == NULL) &&
  8270. (QueueView3->Items->Count > 0))
  8271. {
  8272. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8273. }
  8274. QueueLabelUpdateStatus();
  8275. }
  8276. //---------------------------------------------------------------------------
  8277. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8278. {
  8279. QueueLabelUpdateStatus();
  8280. }
  8281. //---------------------------------------------------------------------------
  8282. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8283. {
  8284. QueueLabel->UpdateStatus();
  8285. }
  8286. //---------------------------------------------------------------------------
  8287. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8288. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8289. {
  8290. if (Selected)
  8291. {
  8292. NonVisualDataModule->UpdateNonVisibleActions();
  8293. }
  8294. }
  8295. //---------------------------------------------------------------------------
  8296. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8297. {
  8298. TDragDropFilesEx * Result = NULL;
  8299. if (Sender == SessionsPageControl)
  8300. {
  8301. Result = FSessionsDragDropFilesEx;
  8302. }
  8303. else if (Sender == QueueView3)
  8304. {
  8305. Result = FQueueDragDropFilesEx;
  8306. }
  8307. else
  8308. {
  8309. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8310. if (DirView != NULL)
  8311. {
  8312. Result = DirView->DragDropFilesEx;
  8313. }
  8314. else
  8315. {
  8316. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8317. if (DriveView != NULL)
  8318. {
  8319. Result = DriveView->DragDropFilesEx;
  8320. }
  8321. }
  8322. }
  8323. DebugAssert(Result != NULL);
  8324. return Result;
  8325. }
  8326. //---------------------------------------------------------------------------
  8327. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8328. {
  8329. return (DView->SelCount == DView->FilesCount);
  8330. }
  8331. //---------------------------------------------------------------------------
  8332. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8333. {
  8334. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8335. }
  8336. //---------------------------------------------------------------------------
  8337. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8338. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8339. {
  8340. DebugAssert(!IsLocalBrowserMode());
  8341. TFileOperation Operation;
  8342. switch (Effect)
  8343. {
  8344. case DROPEFFECT_MOVE:
  8345. Operation = foMove;
  8346. break;
  8347. case DROPEFFECT_COPY:
  8348. // occures on WinXP (reported by user)
  8349. default:
  8350. Operation = foCopy;
  8351. break;
  8352. };
  8353. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8354. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8355. if (DragDropFilesEx->FileList->Count > 0)
  8356. {
  8357. TStrings * FileList = new TStringList();
  8358. try
  8359. {
  8360. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8361. {
  8362. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8363. }
  8364. FDragDropOperation = true;
  8365. TTransferOperationParam Param;
  8366. Param.TargetDirectory = TargetPath;
  8367. // upload, no temp dirs
  8368. Param.Temp = false;
  8369. Param.DragDrop = DragDrop;
  8370. Param.Options =
  8371. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8372. if (ForceQueue)
  8373. {
  8374. Param.Queue = asOn;
  8375. }
  8376. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8377. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8378. {
  8379. if (IsFileControl(DropSourceControl, osLocal))
  8380. {
  8381. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8382. }
  8383. else
  8384. {
  8385. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8386. }
  8387. }
  8388. }
  8389. __finally
  8390. {
  8391. FDragDropOperation = false;
  8392. delete FileList;
  8393. }
  8394. }
  8395. }
  8396. //---------------------------------------------------------------------------
  8397. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8398. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8399. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8400. {
  8401. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8402. }
  8403. //---------------------------------------------------------------------------
  8404. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8405. TObject * Sender, int grfKeyState, int & dwEffect)
  8406. {
  8407. DebugAssert(!IsLocalBrowserMode());
  8408. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8409. if ((dwEffect != DROPEFFECT_NONE) &&
  8410. IsFileControl(DropSourceControl, osRemote))
  8411. {
  8412. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8413. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8414. (RemoteDirView->DropTarget == NULL))
  8415. {
  8416. dwEffect = DROPEFFECT_NONE;
  8417. }
  8418. else
  8419. {
  8420. if (dwEffect == DROPEFFECT_COPY)
  8421. {
  8422. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8423. // currently we support copying always (at least via temporary directory);
  8424. // remove associated checks once this all proves stable and working
  8425. bool CopyCapable = true;
  8426. // if we do not support neither of operations, there's no discussion
  8427. if (!MoveCapable && !CopyCapable)
  8428. {
  8429. dwEffect = DROPEFFECT_NONE;
  8430. }
  8431. else
  8432. {
  8433. // The default effect inside remote panel is move,
  8434. // unless we do not support it, but support copy
  8435. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8436. {
  8437. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8438. }
  8439. else
  8440. {
  8441. // with ctrl-down, we want copy unless it is not supported
  8442. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8443. }
  8444. }
  8445. }
  8446. }
  8447. }
  8448. }
  8449. //---------------------------------------------------------------------------
  8450. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8451. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8452. {
  8453. DebugAssert(!IsLocalBrowserMode());
  8454. if (FDDTotalSize >= 0)
  8455. {
  8456. if (File->IsDirectory)
  8457. {
  8458. FDDTotalSize = -1;
  8459. }
  8460. else
  8461. {
  8462. FDDTotalSize += File->Size;
  8463. }
  8464. }
  8465. DebugAssert(!FDragTempDir.IsEmpty());
  8466. // TODO: this is quite ineffective
  8467. // TODO: what if invalid character replacement is disabled?
  8468. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8469. UnicodeString TransferFileName;
  8470. if (Sender == RemoteDriveView)
  8471. {
  8472. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8473. }
  8474. else
  8475. {
  8476. TransferFileName = File->FileName;
  8477. }
  8478. FDDFileList->AddObject(TransferFileName, File);
  8479. }
  8480. //---------------------------------------------------------------------------
  8481. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8482. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8483. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8484. {
  8485. // sometimes we do not get DDEnd so the list is not released
  8486. SAFE_DESTROY(FDDFileList);
  8487. FDDFileList = new TStringList();
  8488. FDragTempDir = WinConfiguration->TemporaryDir();
  8489. FDDTotalSize = 0;
  8490. FDragDropSshTerminate.reset(NULL);
  8491. }
  8492. //---------------------------------------------------------------------------
  8493. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8494. TObject * /*Sender*/, LongBool /*FEscapePressed*/, int /*grfKeyState*/,
  8495. HRESULT & Result)
  8496. {
  8497. if (Result == DRAGDROP_S_DROP)
  8498. {
  8499. try
  8500. {
  8501. GlobalDragImageList->HideDragImage();
  8502. try
  8503. {
  8504. RemoteFileControlDDTargetDrop();
  8505. }
  8506. catch(ESshTerminate & E)
  8507. {
  8508. FDragDropSshTerminate.reset(E.Clone());
  8509. }
  8510. }
  8511. catch (Exception &E)
  8512. {
  8513. // If downloading fails we need to cancel drag&drop, otherwise
  8514. // Explorer shows error
  8515. // But by the way exception probably never reach this point as
  8516. // it's catched on way.
  8517. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8518. Result = DRAGDROP_S_CANCEL;
  8519. ShowExtendedException(Terminal, &E);
  8520. }
  8521. }
  8522. }
  8523. //---------------------------------------------------------------------------
  8524. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8525. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8526. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8527. {
  8528. TFileMasks::TParams MaskParams;
  8529. MaskParams.Size = Size;
  8530. MaskParams.Modification = Modification;
  8531. // this does not re-parse the mask if it is the same as the last time
  8532. FDirViewMatchMask = Masks;
  8533. bool ImplicitMatch;
  8534. Matches =
  8535. // Local and RecurseInclude parameters have no effect as there's no path.
  8536. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8537. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8538. (AllowImplicitMatches || !ImplicitMatch);
  8539. }
  8540. //---------------------------------------------------------------------------
  8541. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8542. TObject * Sender, TListItem * Item, WORD & Indexes)
  8543. {
  8544. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8545. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8546. {
  8547. Indexes |= oiPartial;
  8548. }
  8549. }
  8550. //---------------------------------------------------------------------------
  8551. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8552. {
  8553. return
  8554. DirViewEnabled(osCurrent) &&
  8555. DirView(osCurrent)->CanPasteFromClipBoard();
  8556. }
  8557. //---------------------------------------------------------------------------
  8558. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8559. {
  8560. bool Result = false;
  8561. if (CanPasteToDirViewFromClipBoard())
  8562. {
  8563. Result = true;
  8564. }
  8565. else
  8566. {
  8567. UnicodeString ClipboardText;
  8568. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8569. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8570. {
  8571. if (StoredSessions->IsUrl(ClipboardText))
  8572. {
  8573. Result = true;
  8574. }
  8575. else
  8576. {
  8577. Result = DirViewEnabled(osCurrent);
  8578. }
  8579. }
  8580. }
  8581. return Result;
  8582. }
  8583. //---------------------------------------------------------------------------
  8584. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8585. {
  8586. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8587. if (DoesClipboardContainOurFiles())
  8588. {
  8589. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8590. {
  8591. DebugAssert(!IsLocalBrowserMode());
  8592. TTerminalManager * Manager = TTerminalManager::Instance();
  8593. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8594. Manager->ActiveSession = FClipboardTerminal;
  8595. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8596. }
  8597. }
  8598. else if (CanPasteToDirViewFromClipBoard())
  8599. {
  8600. DirView(osCurrent)->PasteFromClipBoard();
  8601. }
  8602. else
  8603. {
  8604. UnicodeString ClipboardText;
  8605. if (NonEmptyTextFromClipboard(ClipboardText))
  8606. {
  8607. if (StoredSessions->IsUrl(ClipboardText))
  8608. {
  8609. NewSession(ClipboardText);
  8610. }
  8611. else
  8612. {
  8613. DirView(osCurrent)->Path = ClipboardText;
  8614. }
  8615. }
  8616. }
  8617. }
  8618. //---------------------------------------------------------------------------
  8619. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8620. {
  8621. // TBD
  8622. }
  8623. //---------------------------------------------------------------------------
  8624. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8625. {
  8626. TCustomDirView * ADirView = DirView(Side);
  8627. ADirView->SelectAll(Mode);
  8628. ADirView->SetFocus();
  8629. }
  8630. //---------------------------------------------------------------------------
  8631. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8632. {
  8633. TCustomDirView * ADirView = DirView(Side);
  8634. TFileFilter Filter;
  8635. DefaultFileFilter(Filter);
  8636. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8637. {
  8638. Configuration->Usage->Inc(L"MaskSelections");
  8639. ADirView->SelectFiles(Filter, Select);
  8640. ADirView->SetFocus();
  8641. }
  8642. }
  8643. //---------------------------------------------------------------------------
  8644. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8645. {
  8646. TCustomDirView * ADirView = DirView(Side);
  8647. ADirView->RestoreSelectedNames();
  8648. ADirView->SetFocus();
  8649. }
  8650. //---------------------------------------------------------------------------
  8651. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8652. {
  8653. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8654. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8655. {
  8656. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8657. UnicodeString Ext;
  8658. if (!IsSideLocalBrowser(osCurrent))
  8659. {
  8660. Ext = UnixExtractFileExt(FileName);
  8661. }
  8662. else
  8663. {
  8664. Ext = ExtractFileExt(FileName);
  8665. }
  8666. if (Ext.IsEmpty())
  8667. {
  8668. Ext = L".";
  8669. }
  8670. TFileFilter Filter;
  8671. Filter.Masks = FORMAT(L"*%s", (Ext));
  8672. Filter.Directories = false;
  8673. CurrentDirView->SelectFiles(Filter, Select);
  8674. }
  8675. }
  8676. //---------------------------------------------------------------------------
  8677. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8678. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8679. {
  8680. UnicodeString Result;
  8681. if (FIncrementalSearchState.Searching && (Side == GetSide(osCurrent)))
  8682. {
  8683. Result = FormatIncrementalSearchStatus(FIncrementalSearchState);
  8684. }
  8685. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8686. {
  8687. // noop
  8688. }
  8689. else
  8690. {
  8691. Result =
  8692. FMTLOAD(FILE_INFO_FORMAT,
  8693. (FormatBytes(FileInfo.SelectedSize),
  8694. FormatBytes(FileInfo.FilesSize),
  8695. FormatNumber(FileInfo.SelectedCount),
  8696. FormatNumber(FileInfo.FilesCount)));
  8697. }
  8698. return Result;
  8699. }
  8700. //---------------------------------------------------------------------------
  8701. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8702. TTBXStatusPanel * Panel, TOperationSide Side)
  8703. {
  8704. if (Panel->Index == 1)
  8705. {
  8706. ToggleShowHiddenFiles();
  8707. }
  8708. else if (Panel->Index == 2)
  8709. {
  8710. Filter(Side);
  8711. }
  8712. }
  8713. //---------------------------------------------------------------------------
  8714. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8715. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8716. {
  8717. DebugAssert(!StatusBar->SimplePanel);
  8718. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8719. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8720. }
  8721. //---------------------------------------------------------------------------
  8722. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8723. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8724. {
  8725. DebugAssert(StatusBar->Panels->Count >= 3);
  8726. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8727. if (FileInfo.HiddenCount > 0)
  8728. {
  8729. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8730. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8731. }
  8732. else
  8733. {
  8734. HiddenFilesPanel->ViewPriority = 0;
  8735. // not really necessary, just to cleanup no-longer-valid data
  8736. HiddenFilesPanel->Caption = L"";
  8737. }
  8738. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8739. if (FileInfo.FilteredCount > 0)
  8740. {
  8741. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8742. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8743. }
  8744. else
  8745. {
  8746. FilteredFilesPanel->ViewPriority = 0;
  8747. // not really necessary, just to cleanup no-longer-valid data
  8748. FilteredFilesPanel->Caption = L"";
  8749. }
  8750. }
  8751. //---------------------------------------------------------------------------
  8752. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8753. TObject * /*Sender*/)
  8754. {
  8755. if (DirView(osOther)->Enabled)
  8756. {
  8757. DirView(osOther)->SetFocus();
  8758. }
  8759. }
  8760. //---------------------------------------------------------------------------
  8761. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8762. {
  8763. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8764. switch (Config.Show)
  8765. {
  8766. case qvShow:
  8767. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8768. {
  8769. Config.Show = qvHide;
  8770. }
  8771. else
  8772. {
  8773. Config.Show = Config.LastHideShow;
  8774. }
  8775. break;
  8776. case qvHideWhenEmpty:
  8777. if (ComponentVisible[fcQueueView])
  8778. {
  8779. Config.Show = qvHide;
  8780. }
  8781. else
  8782. {
  8783. Config.LastHideShow = Config.Show;
  8784. Config.Show = qvShow;
  8785. }
  8786. break;
  8787. case qvHide:
  8788. Config.LastHideShow = Config.Show;
  8789. Config.Show = qvShow;
  8790. break;
  8791. }
  8792. WinConfiguration->QueueView = Config;
  8793. }
  8794. //---------------------------------------------------------------------------
  8795. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8796. {
  8797. UnicodeString Result;
  8798. if (Terminal != NULL)
  8799. {
  8800. switch (WinConfiguration->PathInCaption)
  8801. {
  8802. case picShort:
  8803. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8804. break;
  8805. case picFull:
  8806. Result = Terminal->CurrentDirectory;
  8807. break;
  8808. }
  8809. }
  8810. return Result;
  8811. }
  8812. //---------------------------------------------------------------------------
  8813. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8814. {
  8815. TColor Result = GetWindowColor(FSessionColor);
  8816. return Result;
  8817. }
  8818. //---------------------------------------------------------------------------
  8819. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8820. {
  8821. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8822. return Result;
  8823. }
  8824. //---------------------------------------------------------------------------
  8825. void TCustomScpExplorerForm::UpdatePanelControls(TCustomDirView * ADirView, TCustomDriveView * ADriveView)
  8826. {
  8827. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8828. ADirView->DarkMode = UseDarkTheme;
  8829. ADriveView->DarkMode = UseDarkTheme;
  8830. }
  8831. //---------------------------------------------------------------------------
  8832. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8833. {
  8834. if (!FSessionChanging)
  8835. {
  8836. TTerminalManager::Instance()->UpdateAppTitle();
  8837. }
  8838. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8839. // background to gray on Windows 7 (works on Windows 10).
  8840. // See also EnableControl
  8841. if (Showing)
  8842. {
  8843. if (ManagedSession != NULL)
  8844. {
  8845. // Update path when it changes
  8846. if ((SessionsPageControl->ActivePage != NULL) &&
  8847. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8848. {
  8849. UpdateSessionTab(SessionsPageControl->ActivePage);
  8850. }
  8851. }
  8852. NonVisualDataModule->ReconnectSessionAction->Update();
  8853. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8854. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8855. CenterReconnectToolbar();
  8856. // The only place, where we use IsOpenedTerminal and not IsAvailableTerminal
  8857. // (i.e. not checking for reconnecting status)
  8858. // Otherwise it causes flicker [particularly in dark mode] during the short time
  8859. // between the authentication window is closed and FOpeningTerminal is cleared.
  8860. // Should be solved smarter.
  8861. bool HasTerminal = TTerminalManager::Instance()->IsOpenedTerminal(Terminal);
  8862. RemoteDirView->Enabled = HasTerminal;
  8863. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8864. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8865. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8866. RemoteDriveView->Color = RemoteDirView->Color;
  8867. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8868. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8869. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8870. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8871. QueueFileList->Enabled = QueueView3->Enabled;
  8872. QueueFileList->Color = QueueView3->Color;
  8873. QueueFileList->Font->Color = QueueView3->Font->Color;
  8874. QueueLabelUpdateStatus();
  8875. UpdatePanelControls(RemoteDirView, RemoteDriveView);
  8876. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8877. if (FImmersiveDarkMode != UseDarkTheme)
  8878. {
  8879. UpdateDarkMode();
  8880. }
  8881. SessionsPageControl->TabTheme = UseDarkTheme ? CurrentTheme : NULL;
  8882. QueueView3->DarkMode = UseDarkTheme;
  8883. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8884. bool HiContrast = WinConfiguration->HiContrast;
  8885. UnicodeString NewHiContrastThemeName = HiContrast ? GetThemeName(!UseDarkTheme) : EmptyStr;
  8886. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8887. {
  8888. ReleaseHiContrastTheme();
  8889. if (!NewHiContrastThemeName.IsEmpty())
  8890. {
  8891. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8892. }
  8893. }
  8894. SessionsPageControl->ActiveTabTheme = HiContrast ? DebugNotNull(FHiContrastTheme) : NULL;
  8895. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8896. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8897. }
  8898. }
  8899. //---------------------------------------------------------------------------
  8900. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8901. {
  8902. UpdateControls();
  8903. }
  8904. //---------------------------------------------------------------------------
  8905. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8906. TObject * Sender)
  8907. {
  8908. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8909. DebugAssert(DirView != NULL);
  8910. DoDirViewLoaded(DirView);
  8911. TransferPresetAutoSelect();
  8912. TUnixDirView * UnixDirView = dynamic_cast<TUnixDirView *>(DirView);
  8913. if (UnixDirView != NULL)
  8914. {
  8915. TManagedTerminal * ATerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(UnixDirView->Terminal));
  8916. TTerminalManager::Instance()->TerminalLoadedDirectory(ATerminal);
  8917. }
  8918. }
  8919. //---------------------------------------------------------------------------
  8920. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8921. {
  8922. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8923. // first run after installation
  8924. if (double(Updates.LastCheck) == 0)
  8925. {
  8926. AppLog(L"First run, scheduling updates check for the next run");
  8927. // make sure next time there will be an update (if enabled)
  8928. Updates.LastCheck = TDateTime(1);
  8929. WinConfiguration->Updates = Updates;
  8930. }
  8931. else
  8932. {
  8933. TDateTime Period;
  8934. if (IsUWP() && !IsOfficialPackage())
  8935. {
  8936. Period = DefaultUpdatesPeriod;
  8937. AppLog(L"Thirdparty UWP package, using default updates check period");
  8938. }
  8939. else
  8940. {
  8941. Period = Updates.Period;
  8942. }
  8943. AppLogFmt(L"Updates check period: %.2f", (DateTimeToVariant(Period)));
  8944. if (double(Period) > 0)
  8945. {
  8946. TDateTime Interval = Now() - Updates.LastCheck;
  8947. AppLogFmt(L"Interval since the last updates check: %.2f", (DateTimeToVariant(Interval)));
  8948. if (Interval >= Period)
  8949. {
  8950. StartUpdateThread(UpdatesChecked);
  8951. }
  8952. }
  8953. }
  8954. }
  8955. //---------------------------------------------------------------------------
  8956. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8957. {
  8958. AppLog(L"Updates check done");
  8959. UnicodeString Message;
  8960. bool New;
  8961. TQueryType Type;
  8962. GetUpdatesMessage(Message, New, Type, false);
  8963. if (!Message.IsEmpty())
  8964. {
  8965. AppLogFmt(L"Updates check message: %s", (Message));
  8966. if (New)
  8967. {
  8968. AppLog(L"New version detected");
  8969. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8970. }
  8971. if (!New && (Type != qtWarning))
  8972. {
  8973. AppLog(L"Posting non-critical updates note");
  8974. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked);
  8975. }
  8976. else
  8977. {
  8978. AppLog(L"Posting new version or critical message notification");
  8979. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8980. }
  8981. if (New)
  8982. {
  8983. Configuration->Usage->Inc(L"UpdateNotifications");
  8984. }
  8985. }
  8986. }
  8987. //---------------------------------------------------------------------------
  8988. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8989. {
  8990. RestoreApp();
  8991. bool CanDisplay = !NonVisualDataModule->Busy;
  8992. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8993. {
  8994. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8995. }
  8996. if (CanDisplay)
  8997. {
  8998. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8999. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  9000. NonVisualDataModule->StartBusy();
  9001. try
  9002. {
  9003. CheckForUpdates(true);
  9004. }
  9005. __finally
  9006. {
  9007. NonVisualDataModule->EndBusy();
  9008. }
  9009. }
  9010. else
  9011. {
  9012. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  9013. }
  9014. }
  9015. //---------------------------------------------------------------------------
  9016. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  9017. TCopyParamRuleData & Data)
  9018. {
  9019. DebugAssert(Terminal != NULL);
  9020. Data.HostName = Terminal->SessionData->HostNameExpanded;
  9021. Data.UserName = Terminal->SessionData->UserNameExpanded;
  9022. Data.RemoteDirectory = RemoteDirView->PathName;
  9023. }
  9024. //---------------------------------------------------------------------------
  9025. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  9026. {
  9027. // Terminal can be null when we are changing local directory implicitly,
  9028. // because it has been deleted, while no session is connected
  9029. // (Login dialog is open)
  9030. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  9031. {
  9032. DebugAssert(!IsLocalBrowserMode());
  9033. TCopyParamRuleData Data;
  9034. GetTransferPresetAutoSelectData(Data);
  9035. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  9036. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  9037. if (CopyParamIndex < 0)
  9038. {
  9039. // there is no preset that matches autoselection
  9040. // set preset that we consider "default"
  9041. FCopyParamAutoSelected = L""; // forget last autoselected preset
  9042. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  9043. }
  9044. else
  9045. {
  9046. // there is preset matching autoselection
  9047. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  9048. if (CopyParamName == FCopyParamAutoSelected)
  9049. {
  9050. // autoselected the same preset as the last time
  9051. // make no change (i.e. preserve custom user preset, if any)
  9052. }
  9053. else
  9054. {
  9055. // autoselected the different preset then the last time (or there
  9056. // was default preset set)
  9057. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  9058. GUIConfiguration->CopyParamCurrent = CopyParamName;
  9059. }
  9060. }
  9061. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  9062. {
  9063. if (CopyParamIndex >= 0)
  9064. {
  9065. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  9066. }
  9067. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  9068. try
  9069. {
  9070. int Fmt =
  9071. (CopyParamIndex < 0) ?
  9072. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  9073. COPY_PARAM_AUTOSELECTED;
  9074. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  9075. Data->Message = MainInstructions(Message);
  9076. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  9077. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  9078. CopyParamAttrs);
  9079. if (CopyParamIndex >= 0)
  9080. {
  9081. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  9082. Info = FORMAT(L"%s\n \n%s", (Info,
  9083. FMTLOAD(COPY_PARAM_RULE,
  9084. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  9085. }
  9086. Data->Message += L"\n\n" + Info;
  9087. if (WinConfiguration->CopyParamAutoSelectNotice)
  9088. {
  9089. TransferPresetNoteMessage(Data, true);
  9090. }
  9091. else
  9092. {
  9093. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  9094. Data = NULL; // ownership passed
  9095. }
  9096. }
  9097. __finally
  9098. {
  9099. delete Data;
  9100. }
  9101. }
  9102. }
  9103. }
  9104. //---------------------------------------------------------------------------
  9105. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9106. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9107. {
  9108. DebugAssert(NoteData != NULL);
  9109. DebugAssert(!IsLocalBrowserMode());
  9110. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9111. TQueryButtonAlias Aliases[1];
  9112. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9113. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9114. Params.Aliases = Aliases;
  9115. Params.AliasesCount = LENOF(Aliases);
  9116. unsigned int Result =
  9117. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9118. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9119. switch (Result)
  9120. {
  9121. case qaNeverAskAgain:
  9122. DebugAssert(AllowNeverAskAgain);
  9123. WinConfiguration->CopyParamAutoSelectNotice = false;
  9124. break;
  9125. case qaIgnore:
  9126. PreferencesDialog(pmPresets);
  9127. break;
  9128. }
  9129. }
  9130. //---------------------------------------------------------------------------
  9131. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9132. {
  9133. // as of now useless, as this is used for notes only, never for balloons, ...
  9134. RestoreApp();
  9135. // .. and we should never be busy here
  9136. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9137. {
  9138. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9139. }
  9140. }
  9141. //---------------------------------------------------------------------------
  9142. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9143. TPreferencesMode APreferencesMode)
  9144. {
  9145. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9146. TCopyParamRuleData Data;
  9147. if (Terminal != NULL)
  9148. {
  9149. PreferencesData.reset(new TPreferencesDialogData());
  9150. GetTransferPresetAutoSelectData(Data);
  9151. PreferencesData->CopyParamRuleData = &Data;
  9152. }
  9153. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9154. }
  9155. //---------------------------------------------------------------------------
  9156. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9157. const TCustomCommandType & Command)
  9158. {
  9159. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9160. {
  9161. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9162. }
  9163. }
  9164. //---------------------------------------------------------------------------
  9165. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9166. {
  9167. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9168. TCustomCommandType Command;
  9169. // make sure we use local custom command when remote are not supported
  9170. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9171. {
  9172. Command = FLastCustomCommand;
  9173. }
  9174. else
  9175. {
  9176. Command.Params = Command.Params | ccLocal;
  9177. }
  9178. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9179. FEditingFocusedAdHocCommand = OnFocused;
  9180. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9181. int Options =
  9182. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9183. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9184. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9185. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9186. {
  9187. FLastCustomCommand = Command;
  9188. UpdateCustomCommandsToolbar();
  9189. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9190. }
  9191. }
  9192. //---------------------------------------------------------------------------
  9193. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9194. {
  9195. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9196. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9197. DebugAssert(State > 0);
  9198. if (State <= 0)
  9199. {
  9200. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9201. }
  9202. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9203. }
  9204. //---------------------------------------------------------------------------
  9205. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9206. TCustomCommandType & Command, int & State)
  9207. {
  9208. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9209. if (Result)
  9210. {
  9211. Command = FLastCustomCommand;
  9212. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9213. }
  9214. return Result;
  9215. }
  9216. //---------------------------------------------------------------------------
  9217. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9218. {
  9219. ResetIncrementalSearch();
  9220. }
  9221. //---------------------------------------------------------------------------
  9222. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9223. {
  9224. DebugAssert(ComponentVisible[Component]);
  9225. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9226. }
  9227. //---------------------------------------------------------------------------
  9228. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9229. {
  9230. // when queue panel is resized here directly, the status bar is stretched
  9231. // over whole space the panel occupied
  9232. PostComponentHide(fcQueueView);
  9233. }
  9234. //---------------------------------------------------------------------------
  9235. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9236. {
  9237. ComponentVisible[fcQueueFileList] = false;
  9238. }
  9239. //---------------------------------------------------------------------------
  9240. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9241. {
  9242. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9243. // Scrollbars colors are refreshed by WM_THEMECHANGED.
  9244. RefreshColorMode();
  9245. ResetSysDarkTheme();
  9246. ConfigurationChanged();
  9247. ConfigureInterface();
  9248. // To update references to recreated/destroyed themes in SessionsPageControl
  9249. UpdateControls();
  9250. }
  9251. //---------------------------------------------------------------------------
  9252. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9253. {
  9254. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9255. if (!FInvalid &&
  9256. (Message.LParam != 0) &&
  9257. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9258. {
  9259. ThemeChanged();
  9260. }
  9261. TForm::Dispatch(&Message);
  9262. }
  9263. //---------------------------------------------------------------------------
  9264. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9265. {
  9266. TMessage * M = static_cast<TMessage*>(Message);
  9267. switch (M->Msg)
  9268. {
  9269. case CM_DIALOGCHAR:
  9270. CMDialogChar(*M);
  9271. break;
  9272. case WM_APPCOMMAND:
  9273. WMAppCommand(*M);
  9274. break;
  9275. case WM_SYSCOMMAND:
  9276. WMSysCommand(*M);
  9277. break;
  9278. case WM_QUERYENDSESSION:
  9279. WMQueryEndSession(*M);
  9280. break;
  9281. case WM_ENDSESSION:
  9282. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9283. break;
  9284. case WM_COMPONENT_HIDE:
  9285. {
  9286. Byte Component = static_cast<Byte>(M->WParam);
  9287. // sanity check
  9288. if (ComponentVisible[Component])
  9289. {
  9290. // special treatment
  9291. if (Component == fcQueueView)
  9292. {
  9293. ToggleQueueVisibility();
  9294. DebugAssert(!ComponentVisible[fcQueueView]);
  9295. }
  9296. else
  9297. {
  9298. ComponentVisible[Component] = false;
  9299. }
  9300. }
  9301. }
  9302. break;
  9303. case WM_COPYDATA:
  9304. WMCopyData(*M);
  9305. break;
  9306. case WM_MANAGES_CAPTION:
  9307. // caption managed in TTerminalManager::UpdateAppTitle()
  9308. M->Result = 1;
  9309. break;
  9310. case WM_WANTS_MOUSEWHEEL:
  9311. M->Result = 1;
  9312. break;
  9313. case CM_SHOWINGCHANGED:
  9314. CMShowingChanged(*M);
  9315. break;
  9316. case WM_CLOSE:
  9317. WMClose(*M);
  9318. break;
  9319. case WM_DPICHANGED:
  9320. WMDpiChanged(*M);
  9321. break;
  9322. case WM_SETTINGCHANGE:
  9323. WMSettingChange(*M);
  9324. break;
  9325. case CM_DIALOGKEY:
  9326. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9327. break;
  9328. case WM_PASTE_FILES:
  9329. PasteFiles();
  9330. break;
  9331. case WM_IS_HIDDEN:
  9332. // To treat master password prompt as a main window while showing it when workspace is loading while
  9333. // the exporer is showing up (Visible is true already)
  9334. M->Result = !FShowing;
  9335. break;
  9336. case WM_SHOWWINDOW:
  9337. if (M->WParam)
  9338. {
  9339. AddStartupSequence(L"J");
  9340. }
  9341. TForm::Dispatch(Message);
  9342. break;
  9343. case WM_QUEUE_CALLBACK:
  9344. WMQueueCallback(*M);
  9345. break;
  9346. default:
  9347. TForm::Dispatch(Message);
  9348. break;
  9349. }
  9350. }
  9351. //---------------------------------------------------------------------------
  9352. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9353. {
  9354. // noop
  9355. }
  9356. //---------------------------------------------------------------------------
  9357. void TCustomScpExplorerForm::RegenerateSessionColorsImageList()
  9358. {
  9359. FSessionColors->Clear();
  9360. AddFixedSessionImages();
  9361. ::RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9362. UpdateImages();
  9363. }
  9364. //---------------------------------------------------------------------------
  9365. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9366. {
  9367. TForm::Dispatch(&Message);
  9368. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9369. UpdatePixelsPerInchMainWindowCounter();
  9370. }
  9371. //---------------------------------------------------------------------------
  9372. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9373. {
  9374. AppLog(L"Main window WM_CLOSE");
  9375. // Cannot close window while we are busy.
  9376. // We cannot test this in FormCloseQuery as that is called also from
  9377. // Close(), which is called by CloseApplicationAction. So we can be busy
  9378. // there already even, when it is legitimate to close the application.
  9379. // Possibly a better place to handle this would be WMSysCommand.
  9380. if (NonVisualDataModule->Busy)
  9381. {
  9382. Message.Result = 1;
  9383. }
  9384. else
  9385. {
  9386. TForm::Dispatch(&Message);
  9387. }
  9388. }
  9389. //---------------------------------------------------------------------------
  9390. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9391. {
  9392. if (!FShowingChanged)
  9393. {
  9394. AddStartupSequence(L"D");
  9395. FShowingChanged = true;
  9396. }
  9397. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9398. bool NoSession = (ManagedSession == NULL);
  9399. // This calls TCustomScpExplorerForm::DoShow
  9400. TForm::Dispatch(&Message);
  9401. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9402. if (Showing && !FStarted)
  9403. {
  9404. FStarted = true;
  9405. InterfaceStarted();
  9406. }
  9407. if (Showing && NoSession)
  9408. {
  9409. // When we are starting minimized (i.e. from an installer),
  9410. // postpone showing Login dialog until we get restored.
  9411. // Otherwise the Login dialog (and Authentication window) show restored
  9412. // over invisible (minimized) main window.
  9413. if (WindowState == wsMinimized)
  9414. {
  9415. FNeedSession = true;
  9416. }
  9417. else
  9418. {
  9419. // This happens before application ever goes idle, so the toolbars would
  9420. // stay enabled (initial state) until the Login dialog is dismissed.
  9421. UpdateActions();
  9422. NonVisualDataModule->StartBusy();
  9423. try
  9424. {
  9425. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9426. // otherwise the dialog does not receive focus.
  9427. // With Commander interface the ProcessMessages is called already
  9428. // by TDriveView, but with Explorer interface, we need to call it explicily
  9429. Application->ProcessMessages();
  9430. // do not reload sessions, they have been loaded just now (optimization)
  9431. NeedSession(true);
  9432. }
  9433. __finally
  9434. {
  9435. NonVisualDataModule->EndBusy();
  9436. }
  9437. }
  9438. }
  9439. }
  9440. //---------------------------------------------------------------------------
  9441. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9442. {
  9443. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9444. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9445. }
  9446. //---------------------------------------------------------------------------
  9447. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9448. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9449. int & MaxHeight)
  9450. {
  9451. // workaround for bug in TWinControl.CalcConstraints
  9452. // Check for empty rect (restore from iconic state) is done there only after
  9453. // call to AdjustClientRect, which enlarges the rect (for forms).
  9454. TRect R = GetClientRect();
  9455. // when restoring from iconic state, place no restrictions
  9456. if (IsRectEmpty(R))
  9457. {
  9458. MinWidth = 0;
  9459. MinHeight = 0;
  9460. MaxWidth = 32000;
  9461. MaxHeight = 32000;
  9462. }
  9463. }
  9464. //---------------------------------------------------------------------------
  9465. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9466. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9467. {
  9468. // terminal can be already closed (e.g. dropped connection)
  9469. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9470. {
  9471. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9472. try
  9473. {
  9474. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9475. }
  9476. catch(...)
  9477. {
  9478. if (!Terminal->Active)
  9479. {
  9480. Close = true;
  9481. }
  9482. throw;
  9483. }
  9484. }
  9485. }
  9486. //---------------------------------------------------------------------------
  9487. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9488. {
  9489. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9490. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9491. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9492. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9493. {
  9494. OnGetSpaceAvailable = GetSpaceAvailable;
  9495. }
  9496. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9497. OnGetSpaceAvailable);
  9498. }
  9499. //---------------------------------------------------------------------------
  9500. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9501. {
  9502. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9503. Terminal->FillSessionDataForCode(Data.get());
  9504. return Data.release();
  9505. }
  9506. //---------------------------------------------------------------------------
  9507. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9508. {
  9509. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9510. DoGenerateUrlDialog(Data.get(), Paths);
  9511. }
  9512. //---------------------------------------------------------------------------
  9513. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9514. {
  9515. GenerateUrl(NULL);
  9516. }
  9517. //---------------------------------------------------------------------------
  9518. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9519. {
  9520. std::unique_ptr<TStrings> Paths(new TStringList());
  9521. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9522. GenerateUrl(Paths.get());
  9523. }
  9524. //---------------------------------------------------------------------------
  9525. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9526. {
  9527. FSessionColor = value;
  9528. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9529. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9530. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9531. DebugAssert(ColorItem != NULL);
  9532. ColorItem->Color = C;
  9533. NonVisualDataModule->ColorMenuItem->Color = C;
  9534. UpdateControls();
  9535. }
  9536. //---------------------------------------------------------------------------
  9537. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9538. {
  9539. if (value != FSessionColor)
  9540. {
  9541. UpdateSessionColor(value);
  9542. // Is null when called from LastTerminalClosed
  9543. if (Terminal != NULL)
  9544. {
  9545. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9546. }
  9547. }
  9548. }
  9549. //---------------------------------------------------------------------------
  9550. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9551. {
  9552. bool Result = FNoteTimer->Enabled;
  9553. if (Result)
  9554. {
  9555. // cannot cancel note too early
  9556. bool NotEarly =
  9557. (Now() - FNoteShown >
  9558. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9559. if (Force || NotEarly)
  9560. {
  9561. FNoteTimer->Enabled = false;
  9562. FNote = L"";
  9563. SAFE_DESTROY(FNoteData);
  9564. FOnNoteClick = NULL;
  9565. FNoteHints = FNotes->Text;
  9566. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9567. UpdateStatusBar();
  9568. }
  9569. }
  9570. return Result;
  9571. }
  9572. //---------------------------------------------------------------------------
  9573. void TCustomScpExplorerForm::CancelNote(const UnicodeString & Note)
  9574. {
  9575. if (FNote == Note)
  9576. {
  9577. CancelNote(true);
  9578. }
  9579. }
  9580. //---------------------------------------------------------------------------
  9581. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9582. {
  9583. DebugAssert(FNoteTimer->Enabled);
  9584. CancelNote(true);
  9585. }
  9586. //---------------------------------------------------------------------------
  9587. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9588. {
  9589. FNoteHints = FNotes->Text.TrimRight();
  9590. }
  9591. //---------------------------------------------------------------------------
  9592. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9593. {
  9594. int P = Note.Pos(L"\n");
  9595. if (P > 0)
  9596. {
  9597. Note.SetLength(P - 1);
  9598. }
  9599. FNotes->Add(FORMAT(L"[%s] %s",
  9600. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9601. while (FNotes->Count > 10)
  9602. {
  9603. FNotes->Delete(0);
  9604. }
  9605. if (UpdateNow)
  9606. {
  9607. UpdateNoteHints();
  9608. UpdateStatusBar();
  9609. }
  9610. }
  9611. //---------------------------------------------------------------------------
  9612. void TCustomScpExplorerForm::PostNote(
  9613. const UnicodeString & ANote, unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9614. {
  9615. UnicodeString Note = ANote;
  9616. int P = Note.Pos(L"\n");
  9617. if (P > 0)
  9618. {
  9619. Note.SetLength(P - 1);
  9620. }
  9621. UpdateNoteHints();
  9622. FNote = Note;
  9623. SAFE_DESTROY(FNoteData);
  9624. FNoteData = NoteData;
  9625. FOnNoteClick = OnNoteClick;
  9626. AddNote(Note, false);
  9627. UpdateStatusBar();
  9628. FNoteShown = Now();
  9629. FNoteTimer->Enabled = false;
  9630. if (Seconds == 0)
  9631. {
  9632. Seconds = WinConfiguration->NotificationsTimeout;
  9633. }
  9634. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9635. FNoteTimer->Enabled = true;
  9636. }
  9637. //---------------------------------------------------------------------------
  9638. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9639. {
  9640. PostNote(LoadStr(DIRECTORY_READING_CANCELLED));
  9641. }
  9642. //---------------------------------------------------------------------------
  9643. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9644. {
  9645. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9646. {
  9647. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9648. }
  9649. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9650. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9651. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))));
  9652. }
  9653. //---------------------------------------------------------------------------
  9654. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9655. {
  9656. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9657. UnicodeString Note =
  9658. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9659. PostNote(Note);
  9660. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9661. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9662. }
  9663. //---------------------------------------------------------------------------
  9664. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9665. {
  9666. WinConfiguration->FormatSizeBytes = Style;
  9667. }
  9668. //---------------------------------------------------------------------------
  9669. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9670. {
  9671. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9672. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9673. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9674. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))));
  9675. }
  9676. //---------------------------------------------------------------------------
  9677. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9678. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9679. {
  9680. if (Panel->Index == 0)
  9681. {
  9682. if (FOnNoteClick != NULL)
  9683. {
  9684. // prevent the user data from being freed by possible call
  9685. // to CancelNote or PostNote during call to OnNoteClick
  9686. std::unique_ptr<TObject> NoteData(FNoteData);
  9687. TNotifyEvent OnNoteClick = FOnNoteClick;
  9688. FNoteData = NULL;
  9689. // need to cancel the note as we are going to delete its user data
  9690. CancelNote(true);
  9691. OnNoteClick(NoteData.get());
  9692. }
  9693. }
  9694. if (HasAvailableTerminal() &&
  9695. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9696. {
  9697. FileSystemInfo();
  9698. }
  9699. }
  9700. //---------------------------------------------------------------------------
  9701. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9702. {
  9703. // workaround:
  9704. // 1) for unknown reason, disabling window, while minimized,
  9705. // prevents it from restoring, even if it was enabled again meanwhile
  9706. // 2) when disabling the main window, while another has focus
  9707. // minimize is no longer possible
  9708. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9709. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9710. // Shouldn't we use IsApplicationMinimized() here?
  9711. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9712. {
  9713. AppLog(L"Disabling window");
  9714. Enabled = false;
  9715. }
  9716. FLockLevel++;
  9717. }
  9718. //---------------------------------------------------------------------------
  9719. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9720. {
  9721. DebugAssert(FLockLevel > 0);
  9722. FLockLevel--;
  9723. if (FLockLevel == 0)
  9724. {
  9725. DebugAssert(FLockSuspendLevel == 0);
  9726. AppLog(L"Re-enabling window");
  9727. Enabled = true;
  9728. // VCL_COPY (TCustomForm.SetWindowFocus)
  9729. if (Active && (ActiveControl != NULL))
  9730. {
  9731. ::SetFocus(ActiveControl->Handle);
  9732. if (GetFocus() == ActiveControl->Handle)
  9733. {
  9734. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9735. }
  9736. }
  9737. }
  9738. }
  9739. //---------------------------------------------------------------------------
  9740. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9741. {
  9742. // We need to make sure that window is enabled when the last modal window closes
  9743. // otherwise focus is not restored correctly.
  9744. // So we re-enable the window when modal window opens and
  9745. // disable it back after is closes
  9746. if (FLockLevel > 0)
  9747. {
  9748. // while we have nesting counter, we know that we never be called
  9749. // recursivelly as Application->OnModalBegin is called only
  9750. // for the top-level modal window
  9751. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9752. {
  9753. // won't be disabled when conditions in LockWindow() were not satisfied
  9754. FDisabledOnLockSuspend = !Enabled;
  9755. // When minimized to tray (or actually when set to SW_HIDE),
  9756. // setting Enabled makes the window focusable even when there's
  9757. // modal window over it
  9758. if (!FTrayIcon->Visible)
  9759. {
  9760. Enabled = true;
  9761. }
  9762. }
  9763. FLockSuspendLevel++;
  9764. }
  9765. }
  9766. //---------------------------------------------------------------------------
  9767. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9768. {
  9769. if (FLockSuspendLevel > 0)
  9770. {
  9771. DebugAssert(FLockLevel > 0);
  9772. FLockSuspendLevel--;
  9773. // see comment in SuspendWindowLock
  9774. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9775. {
  9776. // Note that window can be enabled here, when we were minized to tray when
  9777. // was SuspendWindowLock() called.
  9778. // We should possibly do the same check as in LockWindow(),
  9779. // if it is ever possible that the consitions change between
  9780. // SuspendWindowLock() and ResumeWindowLock()
  9781. Enabled = !FDisabledOnLockSuspend;
  9782. }
  9783. }
  9784. }
  9785. //---------------------------------------------------------------------------
  9786. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9787. {
  9788. TTBXComboBoxItem * RemotePathComboBox =
  9789. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9790. if (!TextOnly)
  9791. {
  9792. TStrings * Items = RemotePathComboBox->Strings;
  9793. Items->BeginUpdate();
  9794. try
  9795. {
  9796. Items->Clear();
  9797. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9798. {
  9799. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9800. while (!IsUnixRootPath(APath))
  9801. {
  9802. int P = APath.LastDelimiter(L'/');
  9803. DebugAssert(P >= 0);
  9804. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9805. APath.SetLength(P - 1);
  9806. }
  9807. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9808. }
  9809. }
  9810. __finally
  9811. {
  9812. Items->EndUpdate();
  9813. }
  9814. }
  9815. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9816. // Setting ItemIndex to -1 does not reset its text
  9817. if (RemotePathComboBox->Strings->Count == 0)
  9818. {
  9819. RemotePathComboBox->Text = L"";
  9820. }
  9821. }
  9822. //---------------------------------------------------------------------------
  9823. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9824. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9825. {
  9826. if (AIndex < 0)
  9827. {
  9828. AIndex = Sender->ItemIndex;
  9829. }
  9830. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9831. }
  9832. //---------------------------------------------------------------------------
  9833. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9834. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9835. int & ImageIndex)
  9836. {
  9837. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9838. }
  9839. //---------------------------------------------------------------------------
  9840. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9841. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9842. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9843. {
  9844. if (!IsLocalBrowserMode())
  9845. {
  9846. ARect.Left += (10 * AIndex);
  9847. }
  9848. }
  9849. //---------------------------------------------------------------------------
  9850. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9851. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9852. {
  9853. AWidth += (10 * AIndex);
  9854. }
  9855. //---------------------------------------------------------------------------
  9856. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9857. {
  9858. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9859. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9860. int Index = RemotePathComboBox->ItemIndex;
  9861. while (Index < RemotePathComboBox->Strings->Count - 1)
  9862. {
  9863. APath = UnixExtractFileDir(APath);
  9864. Index++;
  9865. }
  9866. // VanDyke style paths
  9867. if (APath.IsEmpty())
  9868. {
  9869. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9870. APath = ROOTDIRECTORY;
  9871. }
  9872. if (RemoteDirView->Path != APath)
  9873. {
  9874. RemoteDirView->Path = APath;
  9875. }
  9876. }
  9877. //---------------------------------------------------------------------------
  9878. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9879. {
  9880. DoRemotePathComboBoxItemClick(Sender);
  9881. }
  9882. //---------------------------------------------------------------------------
  9883. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9884. {
  9885. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9886. DebugUsedParam(Sender);
  9887. UpdateRemotePathComboBox(true);
  9888. }
  9889. //---------------------------------------------------------------------------
  9890. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9891. {
  9892. DoRemotePathComboBoxCancel(Sender);
  9893. }
  9894. //---------------------------------------------------------------------------
  9895. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9896. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9897. {
  9898. ResetIncrementalSearch();
  9899. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9900. DebugAssert(DirView != NULL);
  9901. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9902. {
  9903. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9904. // OnEditing is called also from TCustomListView::CanEdit
  9905. if (Edit != NULL)
  9906. {
  9907. EditSelectBaseName(Edit);
  9908. }
  9909. }
  9910. }
  9911. //---------------------------------------------------------------------------
  9912. //---------------------------------------------------------------------------
  9913. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9914. {
  9915. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9916. Result->AutoDetectDnD = false;
  9917. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9918. Result->RenderDataOn = rdoEnterAndDropSync;
  9919. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9920. return Result;
  9921. }
  9922. //---------------------------------------------------------------------------
  9923. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9924. {
  9925. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9926. UseDarkMode(this);
  9927. }
  9928. //---------------------------------------------------------------------------
  9929. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9930. {
  9931. TForm::CreateWnd();
  9932. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9933. UpdateDarkMode();
  9934. if (FSessionsDragDropFilesEx == NULL)
  9935. {
  9936. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9937. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9938. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9939. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9940. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9941. }
  9942. if (FQueueDragDropFilesEx == NULL)
  9943. {
  9944. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9945. // No need to set OnDragOver as we do not have any restrictions
  9946. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9947. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9948. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9949. }
  9950. }
  9951. //---------------------------------------------------------------------------
  9952. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9953. {
  9954. TForm::DestroyWnd();
  9955. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9956. FQueueDragDropFilesEx->DragDropControl = NULL;
  9957. }
  9958. //---------------------------------------------------------------------------
  9959. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9960. {
  9961. SideEnter(FCurrentSide);
  9962. FEverShown = true;
  9963. }
  9964. //---------------------------------------------------------------------------
  9965. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9966. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9967. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9968. {
  9969. if (!NonVisualDataModule->Busy)
  9970. {
  9971. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9972. Configuration->Usage->Inc(L"FileFinds");
  9973. LockWindow(true);
  9974. NonVisualDataModule->StartBusy();
  9975. WinConfiguration->LockedInterface = true;
  9976. try
  9977. {
  9978. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9979. }
  9980. __finally
  9981. {
  9982. WinConfiguration->LockedInterface = false;
  9983. NonVisualDataModule->EndBusy();
  9984. UnlockWindow();
  9985. }
  9986. }
  9987. }
  9988. //---------------------------------------------------------------------------
  9989. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9990. {
  9991. if (!NonVisualDataModule->Busy)
  9992. {
  9993. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9994. SetFocus();
  9995. RemoteDirView->Path = UnixExtractFilePath(Path);
  9996. UnicodeString FileName = UnixExtractFileName(Path);
  9997. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9998. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9999. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  10000. if (Item == NULL)
  10001. {
  10002. ReloadDirectory(osRemote);
  10003. Item = RemoteDirView->FindFileItem(FileName);
  10004. }
  10005. if (Item != NULL)
  10006. {
  10007. RemoteDirView->ItemFocused = Item;
  10008. RemoteDirView->ItemFocused->MakeVisible(false);
  10009. RemoteDirView->SetFocus();
  10010. }
  10011. }
  10012. }
  10013. //---------------------------------------------------------------------------
  10014. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  10015. {
  10016. bool Result = !NonVisualDataModule->Busy;
  10017. if (Result)
  10018. {
  10019. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  10020. }
  10021. return Result;
  10022. }
  10023. //---------------------------------------------------------------------------
  10024. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  10025. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10026. {
  10027. if (CanOperateOnFoundFiles(ATerminal))
  10028. {
  10029. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished, OnFileOperationFinished);
  10030. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  10031. }
  10032. }
  10033. //---------------------------------------------------------------------------
  10034. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  10035. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10036. {
  10037. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  10038. }
  10039. //---------------------------------------------------------------------------
  10040. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  10041. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10042. {
  10043. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  10044. }
  10045. //---------------------------------------------------------------------------
  10046. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  10047. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10048. {
  10049. if (CanOperateOnFoundFiles(ATerminal))
  10050. {
  10051. for (int Index = 0; Index < FileList->Count; Index++)
  10052. {
  10053. UnicodeString FileName = FileList->Strings[Index];
  10054. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  10055. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  10056. OnFileOperationFinished(osRemote, FileName, true, true);
  10057. }
  10058. }
  10059. }
  10060. //---------------------------------------------------------------------------
  10061. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  10062. {
  10063. FFileFindTerminal = Terminal;
  10064. ShowFileFindDialog(
  10065. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  10066. DoDownloadFoundFiles, DoEditFoundFiles);
  10067. }
  10068. //---------------------------------------------------------------------------
  10069. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  10070. {
  10071. FTaskbarList = TaskbarList;
  10072. }
  10073. //---------------------------------------------------------------------------
  10074. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  10075. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  10076. {
  10077. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10078. if (Index >= 0)
  10079. {
  10080. if (Button == mbLeft)
  10081. {
  10082. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  10083. // If switching tab (switching session) takes long enough for user
  10084. // to actually release the button, "mouse down" is still raised,
  10085. // but we do not get "mouse up" event, so dragging is not cancelled,
  10086. // prevent that by not beginning dragging in the first place.
  10087. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  10088. if (IsKeyPressed(Key))
  10089. {
  10090. // when user clicks the "+", we get mouse down only after the session
  10091. // is closed, when new session tab is already on X:Y, so dragging
  10092. // starts, prevent that
  10093. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  10094. {
  10095. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10096. if (Terminal != NULL)
  10097. {
  10098. SessionsPageControl->BeginDrag(false);
  10099. }
  10100. }
  10101. }
  10102. }
  10103. else if (Button == mbMiddle)
  10104. {
  10105. // ignore middle-click for "New session tab" and the last local-local tab
  10106. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10107. if ((Session != NULL) && CanCloseSession(Session))
  10108. {
  10109. CloseSessionTab(Index);
  10110. }
  10111. }
  10112. }
  10113. }
  10114. //---------------------------------------------------------------------------
  10115. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10116. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10117. {
  10118. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10119. // do not allow dropping on the "+" tab
  10120. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10121. if ((TargetTerminal != NULL) &&
  10122. (SessionsPageControl->ActivePage->PageIndex != Index))
  10123. {
  10124. Configuration->Usage->Inc(L"SessionTabMoves");
  10125. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10126. // but we want to actually prevent that to avoid flicker
  10127. SessionsPageControl->ActivePage->PageIndex = Index;
  10128. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10129. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10130. }
  10131. }
  10132. //---------------------------------------------------------------------------
  10133. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10134. TObject * Sender, TObject * Source, int X, int Y,
  10135. TDragState /*State*/, bool & Accept)
  10136. {
  10137. Accept = (Sender == Source);
  10138. if (Accept)
  10139. {
  10140. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10141. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10142. // do not allow dragging to the "+" tab
  10143. Accept = (Terminal != NULL);
  10144. }
  10145. }
  10146. //---------------------------------------------------------------------------
  10147. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10148. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10149. {
  10150. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10151. if (Index < 0)
  10152. {
  10153. Effect = DROPEFFECT_NONE;
  10154. }
  10155. else
  10156. {
  10157. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10158. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10159. if (!IsAvailableTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10160. {
  10161. Effect = DROPEFFECT_NONE;
  10162. }
  10163. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10164. {
  10165. Effect = DROPEFFECT_COPY;
  10166. }
  10167. }
  10168. }
  10169. //---------------------------------------------------------------------------
  10170. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10171. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10172. {
  10173. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10174. // do not allow dropping on local-local, disconnected and the "+" tab
  10175. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10176. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10177. if (DebugAlwaysTrue(IsAvailableTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10178. {
  10179. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10180. if (!IsFileControl(DropSourceControl, osRemote))
  10181. {
  10182. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10183. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10184. // Why don't we use Terminal->CurrentDirectory directly?
  10185. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10186. // do not force queue, drag drop
  10187. false, true);
  10188. }
  10189. }
  10190. }
  10191. //---------------------------------------------------------------------------
  10192. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10193. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10194. {
  10195. // Downloads are handled in RemoteFileControlDDEnd
  10196. if (!IsFileControl(DropSourceControl, osRemote))
  10197. {
  10198. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10199. Terminal->CurrentDirectory,
  10200. // force queue, drag drop
  10201. true, true);
  10202. }
  10203. }
  10204. //---------------------------------------------------------------------------
  10205. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10206. {
  10207. FShowing = false;
  10208. // Do not save empty workspace
  10209. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10210. {
  10211. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10212. UnicodeString Name = WorkspaceName();
  10213. DoSaveWorkspace(
  10214. Name, DataList.get(),
  10215. !Configuration->DisablePasswordStoring &&
  10216. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10217. WinConfiguration->LastStoredSession = Name;
  10218. }
  10219. AppLog(L"Closing main window");
  10220. }
  10221. //---------------------------------------------------------------------------
  10222. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10223. {
  10224. TManagedTerminal * ManagedTerminal =
  10225. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10226. if (ManagedTerminal != NULL)
  10227. {
  10228. ManagedTerminal->DirectoryLoaded = Now();
  10229. }
  10230. }
  10231. //---------------------------------------------------------------------------
  10232. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10233. TListItem * /*Item*/, bool /*Selected*/)
  10234. {
  10235. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10236. switch (DirView->LastSelectMethod)
  10237. {
  10238. case smKeyboard:
  10239. Configuration->Usage->Inc(L"KeyboardSelections");
  10240. break;
  10241. case smMouse:
  10242. Configuration->Usage->Inc(L"MouseSelections");
  10243. break;
  10244. }
  10245. }
  10246. //---------------------------------------------------------------------------
  10247. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10248. {
  10249. if (Color != 0)
  10250. {
  10251. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10252. }
  10253. else
  10254. {
  10255. return FSessionTabImageIndex;
  10256. }
  10257. }
  10258. //---------------------------------------------------------------------------
  10259. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10260. {
  10261. TPngImageCollectionItem * Item =
  10262. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10263. FSessionColors->AddPng(Item->PngImage);
  10264. return FSessionColors->Count - 1;
  10265. }
  10266. //---------------------------------------------------------------------------
  10267. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10268. {
  10269. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10270. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10271. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10272. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10273. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10274. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10275. }
  10276. //---------------------------------------------------------------------------
  10277. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10278. {
  10279. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10280. }
  10281. //---------------------------------------------------------------------------
  10282. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10283. {
  10284. switch (Side)
  10285. {
  10286. case osLocal:
  10287. return FNewLocalTabTabImageIndex;
  10288. case osRemote:
  10289. case osCurrent:
  10290. return FNewRemoteTabTabImageIndex;
  10291. default:
  10292. DebugFail();
  10293. return -1;
  10294. }
  10295. }
  10296. //---------------------------------------------------------------------------
  10297. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10298. {
  10299. for (int Index = 0; Index < Control->ControlCount; Index++)
  10300. {
  10301. TControl * AControl = Control->Controls[Index];
  10302. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10303. if (WinControl != NULL)
  10304. {
  10305. CollectItemsWithTextDisplayMode(WinControl);
  10306. }
  10307. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10308. if (Toolbar != NULL)
  10309. {
  10310. // we care for top-level items only
  10311. TTBCustomItem * Items = Toolbar->Items;
  10312. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10313. {
  10314. TTBCustomItem * Item = Items->Items[ItemIndex];
  10315. if (((Item->DisplayMode == nbdmImageAndText) ||
  10316. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10317. EligibleForImageDisplayMode(Item))
  10318. {
  10319. FItemsWithTextDisplayMode.insert(Item);
  10320. }
  10321. }
  10322. }
  10323. }
  10324. }
  10325. //---------------------------------------------------------------------------
  10326. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10327. {
  10328. return true;
  10329. }
  10330. //---------------------------------------------------------------------------
  10331. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10332. {
  10333. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10334. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10335. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10336. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10337. bool Result = true;
  10338. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10339. {
  10340. TTBCustomItem * Item = *i;
  10341. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10342. if (Label != NULL)
  10343. {
  10344. // optimization
  10345. if (Label->Visible == SelectiveToolbarText)
  10346. {
  10347. Result = false;
  10348. }
  10349. else
  10350. {
  10351. Label->Visible = SelectiveToolbarText;
  10352. }
  10353. }
  10354. else
  10355. {
  10356. // optimization
  10357. if (Item->DisplayMode == DisplayMode)
  10358. {
  10359. Result = false;
  10360. }
  10361. else
  10362. {
  10363. Item->DisplayMode = DisplayMode;
  10364. }
  10365. }
  10366. ++i;
  10367. }
  10368. UpdateNewTabTab();
  10369. return Result;
  10370. }
  10371. //---------------------------------------------------------------------------
  10372. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10373. {
  10374. DebugFail();
  10375. }
  10376. //---------------------------------------------------------------------------
  10377. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10378. {
  10379. // Among other, a lock level is non zero, while directory is being loaded,
  10380. // even when it happens as a result of dirview navigation,
  10381. // i.e. when TNonVisualDataModule is NOT FBusy.
  10382. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10383. // Among other this prevents a panel auto update to occur while
  10384. // directory is changing.
  10385. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10386. }
  10387. //---------------------------------------------------------------------------
  10388. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10389. {
  10390. // While the window is disabled, we still seem to process menu shortcuts at least,
  10391. // so stop it at least here.
  10392. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10393. bool Result;
  10394. if (Allowed == aaUpdate)
  10395. {
  10396. Result = true;
  10397. }
  10398. else
  10399. {
  10400. Result = !NonVisualDataModule->Busy;
  10401. if (Result && (Allowed == aaShortCut))
  10402. {
  10403. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10404. Action->Update();
  10405. Result = Action->Enabled;
  10406. }
  10407. }
  10408. return Result;
  10409. }
  10410. //---------------------------------------------------------------------------
  10411. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10412. {
  10413. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10414. }
  10415. //---------------------------------------------------------------------------
  10416. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10417. {
  10418. // This is somewhat redundant to LockWindow() call from
  10419. // TTerminalManager::TerminalReadDirectoryProgress.
  10420. // But disabling window is known not to block keyboard shorcuts
  10421. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10422. if (Busy > 0)
  10423. {
  10424. if (NonVisualDataModule->Busy)
  10425. {
  10426. State = false;
  10427. }
  10428. else
  10429. {
  10430. NonVisualDataModule->StartBusy();
  10431. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10432. LockWindow();
  10433. }
  10434. }
  10435. else if (Busy < 0)
  10436. {
  10437. UnlockWindow();
  10438. NonVisualDataModule->EndBusy();
  10439. }
  10440. else
  10441. {
  10442. State = NonVisualDataModule->Busy;
  10443. }
  10444. }
  10445. //---------------------------------------------------------------------------
  10446. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10447. {
  10448. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10449. if (Index >= 0)
  10450. {
  10451. TPopupMenu * PopupMenu = NULL;
  10452. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10453. if (Session != NULL)
  10454. {
  10455. SessionsPageControl->ActivePageIndex = Index;
  10456. if (DebugAlwaysTrue(SessionTabSwitched()))
  10457. {
  10458. // copied from TControl.WMContextMenu
  10459. SendCancelMode(SessionsPageControl);
  10460. // explicit popup instead of using PopupMenu property
  10461. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10462. // while connecting yet not-connected session and hence
  10463. // allowing an access to commands over not-completely connected session
  10464. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10465. }
  10466. }
  10467. else
  10468. {
  10469. if (SupportsLocalBrowser())
  10470. {
  10471. PopupMenu = NonVisualDataModule->NewTabPopup;
  10472. }
  10473. }
  10474. if (PopupMenu != NULL)
  10475. {
  10476. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10477. PopupMenu->PopupComponent = SessionsPageControl;
  10478. PopupMenu->Popup(Point.x, Point.y);
  10479. }
  10480. }
  10481. Handled = true;
  10482. }
  10483. //---------------------------------------------------------------------------
  10484. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10485. {
  10486. return HasAvailableTerminal() && Terminal->IsCapable[fcChangePassword];
  10487. }
  10488. //---------------------------------------------------------------------------
  10489. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10490. {
  10491. Configuration->Usage->Inc(L"PasswordChanges");
  10492. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10493. ChangePasswordData->DisableAuthentationsExceptPassword();
  10494. ChangePasswordData->ChangePassword = true;
  10495. std::unique_ptr<TTerminal> ChangePasswordSession(
  10496. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10497. ChangePasswordSession->AutoReadDirectory = false;
  10498. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10499. {
  10500. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10501. }
  10502. else
  10503. {
  10504. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10505. }
  10506. }
  10507. //---------------------------------------------------------------------------
  10508. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10509. {
  10510. // No nice way to assert SSH2
  10511. return HasAvailableTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10512. }
  10513. //---------------------------------------------------------------------------
  10514. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10515. {
  10516. TOperationVisualizer OperationVisualizer;
  10517. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10518. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10519. }
  10520. //---------------------------------------------------------------------------
  10521. void __fastcall TCustomScpExplorerForm::FormAfterMonitorDpiChanged(TObject *, int OldDPI, int NewDPI)
  10522. {
  10523. DebugUsedParam(OldDPI);
  10524. DebugAssert(NewDPI == GetControlPixelsPerInch(this));
  10525. GlyphsModule->PixelsPerInch = NewDPI;
  10526. // Can be called too early when primary monitor has non-system dpi
  10527. if (FSessionColors != NULL)
  10528. {
  10529. RegenerateSessionColorsImageList();
  10530. }
  10531. UpdateTabsSize();
  10532. UpdateSessionsPageControlHeight();
  10533. QueueFileListColumnAutoSize();
  10534. }
  10535. //---------------------------------------------------------------------------
  10536. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10537. {
  10538. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10539. }
  10540. //---------------------------------------------------------------------
  10541. class TPublicControl : public TControl
  10542. {
  10543. friend class TCustomScpExplorerForm;
  10544. };
  10545. //---------------------------------------------------------------------------
  10546. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10547. {
  10548. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10549. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10550. }
  10551. //---------------------------------------------------------------------------
  10552. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10553. {
  10554. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10555. OpenBookmark(Side, Bookmark);
  10556. }
  10557. //---------------------------------------------------------------------------
  10558. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10559. {
  10560. DoBookmarkClick(osLocal, Sender);
  10561. }
  10562. //---------------------------------------------------------------------------
  10563. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10564. {
  10565. DoBookmarkClick(osRemote, Sender);
  10566. }
  10567. //---------------------------------------------------------------------------
  10568. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10569. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10570. {
  10571. if (BookmarkList != NULL)
  10572. {
  10573. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10574. if (IsLocalBrowserMode())
  10575. {
  10576. Side = osLocal;
  10577. }
  10578. if (!WinConfiguration->UseLocationProfiles)
  10579. {
  10580. std::unique_ptr<TStringList> Directories(new TStringList());
  10581. Directories->CaseSensitive = (Side == osRemote);
  10582. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10583. {
  10584. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10585. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10586. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10587. {
  10588. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10589. Item->Caption = EscapeHotkey(Directory);
  10590. Item->ShortCut = Bookmark->ShortCut;
  10591. Item->OnClick = OnBookmarkClick;
  10592. Item->Tag = reinterpret_cast<int>(Bookmark);
  10593. Directories->Add(Directory);
  10594. Menu->Add(Item.release());
  10595. }
  10596. }
  10597. }
  10598. else
  10599. {
  10600. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10601. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10602. {
  10603. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10604. if (!Bookmark->Node.IsEmpty())
  10605. {
  10606. Folders->Add(Bookmark->Node);
  10607. }
  10608. }
  10609. for (int Index = 0; Index < Folders->Count; Index++)
  10610. {
  10611. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10612. Item->Caption = Folders->Strings[Index];
  10613. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10614. Folders->Objects[Index] = Item.get();
  10615. Menu->Add(Item.release());
  10616. }
  10617. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10618. {
  10619. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10620. TTBCustomItem * Parent;
  10621. if (!Bookmark->Node.IsEmpty())
  10622. {
  10623. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10624. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10625. }
  10626. else
  10627. {
  10628. Parent = Menu;
  10629. }
  10630. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10631. Item->Caption = Bookmark->Name;
  10632. Item->ShortCut = Bookmark->ShortCut;
  10633. Item->OnClick = OnBookmarkClick;
  10634. Item->Tag = reinterpret_cast<int>(Bookmark);
  10635. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10636. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10637. {
  10638. // No hint for location profiles that are actually mere "bookmarks"
  10639. }
  10640. else
  10641. {
  10642. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10643. UnicodeString LongHint;
  10644. if (!Bookmark->Local.IsEmpty())
  10645. {
  10646. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10647. }
  10648. if (!Bookmark->Remote.IsEmpty())
  10649. {
  10650. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10651. }
  10652. AddToList(Hint, LongHint, L"|");
  10653. Item->Hint = Hint;
  10654. }
  10655. Parent->Add(Item.release());
  10656. }
  10657. }
  10658. AddMenuSeparator(Menu);
  10659. }
  10660. }
  10661. //---------------------------------------------------------------------------
  10662. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10663. {
  10664. Menu->Clear();
  10665. std::unique_ptr<TTBCustomItem> Item;
  10666. Item.reset(new TTBXItem(Owner));
  10667. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10668. Item->Options = Item->Options << tboDefault;
  10669. Menu->Add(Item.release());
  10670. AddMenuSeparator(Menu);
  10671. if (Terminal != NULL)
  10672. {
  10673. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10674. }
  10675. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10676. Item.reset(new TTBXItem(Owner));
  10677. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10678. Menu->Add(Item.release());
  10679. }
  10680. //---------------------------------------------------------------------------
  10681. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10682. {
  10683. bool Result = true;
  10684. bool Remote = !IsSideLocalBrowser(Side);
  10685. try
  10686. {
  10687. UnicodeString APath = Path;
  10688. if (Remote)
  10689. {
  10690. Terminal->ExceptionOnFail = true;
  10691. }
  10692. else
  10693. {
  10694. APath = ExpandEnvironmentVariables(Path);
  10695. }
  10696. try
  10697. {
  10698. DirView(Side)->Path = APath;
  10699. }
  10700. __finally
  10701. {
  10702. if (Remote)
  10703. {
  10704. Terminal->ExceptionOnFail = false;
  10705. }
  10706. }
  10707. }
  10708. catch (Exception & E)
  10709. {
  10710. if (!Remote || Terminal->Active)
  10711. {
  10712. ShowExtendedExceptionEx(Terminal, &E);
  10713. Result = false;
  10714. }
  10715. else
  10716. {
  10717. throw;
  10718. }
  10719. }
  10720. return Result;
  10721. }
  10722. //---------------------------------------------------------------------------
  10723. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10724. {
  10725. // Make sure there some feedback even when loading tiny local folders
  10726. TInstantOperationVisualizer Visualizer;
  10727. DirView(Side)->ReloadDirectory();
  10728. }
  10729. //---------------------------------------------------------------------------
  10730. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10731. {
  10732. if (Index == SessionsPageControl->TabIndex)
  10733. {
  10734. CloseTab();
  10735. }
  10736. else
  10737. {
  10738. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10739. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10740. TTerminalManager * Manager = TTerminalManager::Instance();
  10741. if (!Terminal->Active)
  10742. {
  10743. Manager->FreeTerminal(Terminal);
  10744. }
  10745. else
  10746. {
  10747. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10748. if (CanCloseQueue(Queue))
  10749. {
  10750. Manager->FreeTerminal(Terminal);
  10751. }
  10752. }
  10753. }
  10754. }
  10755. //---------------------------------------------------------------------------
  10756. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10757. {
  10758. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10759. if (Session == NULL)
  10760. {
  10761. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10762. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10763. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10764. //P = SessionsPageControl->ClientToScreen(P);
  10765. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10766. }
  10767. else
  10768. {
  10769. CloseSessionTab(Index);
  10770. }
  10771. }
  10772. //---------------------------------------------------------------------------
  10773. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10774. {
  10775. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10776. {
  10777. TInstantOperationVisualizer Visualizer;
  10778. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10779. // before we create a new data object
  10780. ClipboardClear();
  10781. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10782. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10783. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10784. // Intermediate variable to WORKAROUND a crash in compiler
  10785. TObjectList * ClipboardFakeMonitors =
  10786. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10787. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10788. if (FClipboardDragDropFilesEx.get() == NULL)
  10789. {
  10790. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10791. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10792. }
  10793. FClipboardDragDropFilesEx->FileList->Clear();
  10794. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10795. FClipboardDragDropFilesEx->CopyToClipboard();
  10796. FClipboardTerminal = Terminal;
  10797. // Need full paths, as cwd can be different once files are pasted
  10798. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10799. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10800. {
  10801. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10802. }
  10803. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10804. }
  10805. }
  10806. //---------------------------------------------------------------------------
  10807. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10808. {
  10809. if (OpenClipboard(0))
  10810. {
  10811. AppLog(L"Clearing clipboard");
  10812. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10813. CloseClipboard();
  10814. }
  10815. }
  10816. //---------------------------------------------------------------------------
  10817. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10818. {
  10819. return !FClipboardFakeDirectory.IsEmpty();
  10820. }
  10821. //---------------------------------------------------------------------------
  10822. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10823. {
  10824. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10825. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10826. FClipboardFakeDirectory = UnicodeString();
  10827. FClipboardTerminal = NULL;
  10828. if (FDownloadingFromClipboard)
  10829. {
  10830. // We are called by the monitor, so attempt to release it would deadlock
  10831. FClipboardFakeMonitorsPendingReset = true;
  10832. }
  10833. else
  10834. {
  10835. FClipboardFakeMonitors.reset(NULL);
  10836. }
  10837. }
  10838. //---------------------------------------------------------------------------
  10839. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10840. {
  10841. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10842. {
  10843. ClipboardStop();
  10844. }
  10845. }
  10846. //---------------------------------------------------------------------------
  10847. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10848. {
  10849. TTerminalManager * Manager = TTerminalManager::Instance();
  10850. Manager->ActiveSession = FClipboardTerminal;
  10851. TTransferOperationParam Params;
  10852. Params.TargetDirectory = TargetDirectory;
  10853. Params.DragDrop = DragDrop;
  10854. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10855. }
  10856. //---------------------------------------------------------------------------
  10857. void TCustomScpExplorerForm::PasteFilesCleanupRetry(const UnicodeString & Target)
  10858. {
  10859. bool Removed = RemoveDir(ApiPath(Target));
  10860. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10861. }
  10862. //---------------------------------------------------------------------------
  10863. void TCustomScpExplorerForm::PasteFiles()
  10864. {
  10865. // Guard against possible race conditions
  10866. if (!FClipboardPasteTarget.IsEmpty())
  10867. {
  10868. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10869. UnicodeString Target = FClipboardPasteTarget;
  10870. FClipboardPasteTarget = EmptyStr;
  10871. // Can fail as it can be e.g. locked by AV, so we retry that later
  10872. bool Removed = RemoveDir(ApiPath(Target));
  10873. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10874. try
  10875. {
  10876. if (NonVisualDataModule->Busy)
  10877. {
  10878. AppLog(L"Is busy, cannot paste");
  10879. }
  10880. else
  10881. {
  10882. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10883. FClipboardFakeMonitorsPendingReset = false;
  10884. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10885. TAutoFlag Flag(FDownloadingFromClipboard);
  10886. AppLog(L"Downloading to paste target...");
  10887. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10888. AppLog(L"Downloaded to paste target...");
  10889. }
  10890. }
  10891. __finally
  10892. {
  10893. if (!Removed)
  10894. {
  10895. PasteFilesCleanupRetry(Target);
  10896. }
  10897. }
  10898. }
  10899. }
  10900. //---------------------------------------------------------------------------
  10901. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10902. {
  10903. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10904. // (as it pumps a Windows message queue while being shutted down)
  10905. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10906. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10907. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10908. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10909. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10910. {
  10911. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10912. FClipboardPasteTarget = FileName;
  10913. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10914. // Postponing removing (or actually whole pasting operation) seems to help.
  10915. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10916. }
  10917. }
  10918. //---------------------------------------------------------------------------
  10919. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10920. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10921. {
  10922. TFileMasks::TParams MaskParams;
  10923. MaskParams.Size = Size;
  10924. MaskParams.Modification = Modification;
  10925. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10926. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10927. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10928. if (!Local && Directory)
  10929. {
  10930. FileName = UnixExcludeTrailingBackslash(FileName);
  10931. }
  10932. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10933. {
  10934. bool ImplicitMatch;
  10935. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10936. !ImplicitMatch)
  10937. {
  10938. Color = Iter->Color;
  10939. break;
  10940. }
  10941. }
  10942. }
  10943. //---------------------------------------------------------------------------
  10944. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10945. {
  10946. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10947. if (!DirView->IsEditing())
  10948. {
  10949. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10950. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10951. // while searching
  10952. if (Key == VK_BACK)
  10953. {
  10954. if (FIncrementalSearchState.Searching)
  10955. {
  10956. if (FIncrementalSearchState.Text.Length() <= 1)
  10957. {
  10958. ResetIncrementalSearch();
  10959. }
  10960. else
  10961. {
  10962. UnicodeString NewText = LeftStr(FIncrementalSearchState.Text, FIncrementalSearchState.Text.Length() - 1);
  10963. IncrementalSearch(NewText, false, false);
  10964. }
  10965. Key = 0;
  10966. }
  10967. }
  10968. }
  10969. }
  10970. //---------------------------------------------------------------------------
  10971. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10972. {
  10973. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10974. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10975. {
  10976. // Filter control sequences.
  10977. // When not searching yet, prefer use of the space for toggling file selection
  10978. // (so we cannot incrementally search for a string starting with a space).
  10979. if ((Key > VK_SPACE) ||
  10980. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && FIncrementalSearchState.Searching))
  10981. {
  10982. IncrementalSearch(FIncrementalSearchState.Text + Key, false, false);
  10983. Key = 0;
  10984. }
  10985. }
  10986. }
  10987. //---------------------------------------------------------------------------
  10988. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10989. {
  10990. if (FIncrementalSearchState.Searching)
  10991. {
  10992. FIncrementalSearchState.Reset();
  10993. DirView(osCurrent)->UpdateStatusBar();
  10994. }
  10995. }
  10996. //---------------------------------------------------------------------------
  10997. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10998. {
  10999. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  11000. if (Item == NULL)
  11001. {
  11002. MessageBeep(MB_ICONHAND);
  11003. }
  11004. else
  11005. {
  11006. TCustomDirView * ADirView = DirView(osCurrent);
  11007. {
  11008. TAutoNestingCounter Guard(FIncrementalSearching);
  11009. ADirView->FocusItem(Item);
  11010. if (ADirView->NortonLike == nlOff)
  11011. {
  11012. if ((ADirView->Selected != Item) ||
  11013. (ADirView->SelCount > 1))
  11014. {
  11015. ADirView->ClearSelection();
  11016. ADirView->Selected = Item;
  11017. }
  11018. }
  11019. }
  11020. FIncrementalSearchState.Searching = true;
  11021. FIncrementalSearchState.Text = Text;
  11022. Item->MakeVisible(false);
  11023. TListItem * NextItem = SearchFile(Text, true, Reverse);
  11024. FIncrementalSearchState.HaveNext = (NextItem != NULL) && (NextItem != Item);
  11025. ADirView->UpdateStatusBar();
  11026. }
  11027. }
  11028. //---------------------------------------------------------------------------
  11029. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  11030. {
  11031. int Index = Item->Index;
  11032. if (!Reverse)
  11033. {
  11034. Index++;
  11035. if (Index >= Item->Owner->Count)
  11036. {
  11037. Index = 0;
  11038. }
  11039. }
  11040. else
  11041. {
  11042. Index--;
  11043. if (Index < 0)
  11044. {
  11045. Index = Item->Owner->Count - 1;
  11046. }
  11047. }
  11048. return Item->Owner->Item[Index];
  11049. }
  11050. //---------------------------------------------------------------------------
  11051. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  11052. {
  11053. TCustomDirView * ADirView = DirView(osCurrent);
  11054. if (ADirView->Items->Count == 0)
  11055. {
  11056. return NULL;
  11057. }
  11058. else
  11059. {
  11060. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  11061. TListItem * Item = CurrentItem;
  11062. if (SkipCurrent)
  11063. {
  11064. Item = DebugNotNull(GetNextFile(Item, Reverse));
  11065. }
  11066. while (true)
  11067. {
  11068. bool Matches = false;
  11069. switch (WinConfiguration->PanelSearch)
  11070. {
  11071. case isNameStartOnly:
  11072. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  11073. break;
  11074. case isName:
  11075. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  11076. break;
  11077. case isAll:
  11078. int ColCount = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Count : 1;
  11079. int Index = 0;
  11080. while ((Index < ColCount) && !Matches)
  11081. {
  11082. bool Visible = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Visible[Index] : true;
  11083. if (Visible)
  11084. {
  11085. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  11086. }
  11087. Index++;
  11088. }
  11089. break;
  11090. }
  11091. if (Matches)
  11092. {
  11093. return Item;
  11094. }
  11095. Item = GetNextFile(Item, Reverse);
  11096. if (Item == CurrentItem)
  11097. {
  11098. return NULL;
  11099. }
  11100. }
  11101. }
  11102. }
  11103. //---------------------------------------------------------------------------
  11104. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  11105. {
  11106. ResetIncrementalSearch();
  11107. }
  11108. //---------------------------------------------------------------------------
  11109. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  11110. {
  11111. if (Message.CharCode == VK_TAB)
  11112. {
  11113. if (!FIncrementalSearchState.Text.IsEmpty())
  11114. {
  11115. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11116. bool Reverse = Shift.Contains(ssShift);
  11117. IncrementalSearch(FIncrementalSearchState.Text, true, Reverse);
  11118. Message.Result = 1;
  11119. return;
  11120. }
  11121. }
  11122. else if (Message.CharCode == VK_ESCAPE)
  11123. {
  11124. if (FIncrementalSearchState.Searching)
  11125. {
  11126. ResetIncrementalSearch();
  11127. Message.Result = 1;
  11128. return;
  11129. }
  11130. }
  11131. TForm::Dispatch(&Message);
  11132. }
  11133. //---------------------------------------------------------------------------
  11134. void __fastcall TCustomScpExplorerForm::Deactivate()
  11135. {
  11136. TForm::Deactivate();
  11137. // E.g. when switching to an internal editor window
  11138. ResetIncrementalSearch();
  11139. }
  11140. //---------------------------------------------------------------------------
  11141. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11142. {
  11143. // When switching to another application
  11144. ResetIncrementalSearch();
  11145. }
  11146. //---------------------------------------------------------------------------
  11147. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11148. {
  11149. ResetIncrementalSearch();
  11150. }
  11151. //---------------------------------------------------------------------------
  11152. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11153. {
  11154. if (FIncrementalSearching <= 0)
  11155. {
  11156. ResetIncrementalSearch();
  11157. }
  11158. }
  11159. //---------------------------------------------------------------------------
  11160. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11161. {
  11162. CountClicksForWindowPrint(this);
  11163. }
  11164. //---------------------------------------------------------------------------
  11165. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11166. {
  11167. CenterReconnectToolbar();
  11168. }
  11169. //---------------------------------------------------------------------------
  11170. void TCustomScpExplorerForm::DoExploreFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11171. {
  11172. if (!FileName.IsEmpty())
  11173. {
  11174. DirView->FocusByName(FileName);
  11175. if (DirView->ItemFocused != NULL)
  11176. {
  11177. DirView->ItemFocused->Selected = true;
  11178. }
  11179. }
  11180. }
  11181. //---------------------------------------------------------------------------
  11182. void __fastcall TCustomScpExplorerForm::ExploreFile(const UnicodeString & FileName)
  11183. {
  11184. DoExploreFile(RemoteDirView, FileName);
  11185. }
  11186. //---------------------------------------------------------------------------
  11187. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11188. {
  11189. if (!FQueueStatusUpdating)
  11190. {
  11191. bool Refresh;
  11192. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11193. {
  11194. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11195. }
  11196. else
  11197. {
  11198. Refresh = (FQueueFileList->GetCount() > 0);
  11199. if (Refresh)
  11200. {
  11201. FQueueFileList->Clear();
  11202. }
  11203. }
  11204. int Count = FQueueFileList->GetCount();
  11205. if (QueueFileList->Items->Count != Count)
  11206. {
  11207. DebugAssert(Refresh);
  11208. QueueFileList->Items->Count = Count;
  11209. }
  11210. if (Refresh)
  11211. {
  11212. QueueFileList->Invalidate();
  11213. }
  11214. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11215. }
  11216. }
  11217. //---------------------------------------------------------------------------
  11218. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11219. {
  11220. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11221. }
  11222. //---------------------------------------------------------------------------
  11223. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11224. {
  11225. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11226. // See TSynchronizeChecklistDialog::UpdateTimer
  11227. if (QueueFileList->Items->Count > 0)
  11228. {
  11229. QueueFileList->Items->Item[0]->MakeVisible(false);
  11230. }
  11231. UpdateQueueFileList();
  11232. }
  11233. //---------------------------------------------------------------------------
  11234. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11235. {
  11236. Active = QueueView3->Focused() || QueueFileList->Focused();
  11237. }
  11238. //---------------------------------------------------------------------------
  11239. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11240. {
  11241. QueueLabelUpdateStatus();
  11242. }
  11243. //---------------------------------------------------------------------------
  11244. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11245. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11246. {
  11247. int State = FQueueFileList->GetState(Item->Index);
  11248. if (State == qfsProcessed)
  11249. {
  11250. Sender->Canvas->Font->Color = clGrayText;
  11251. }
  11252. }
  11253. //---------------------------------------------------------------------------
  11254. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11255. {
  11256. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11257. QueueFileList->Column[0]->Width =
  11258. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11259. }
  11260. //---------------------------------------------------------------------------
  11261. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11262. {
  11263. QueueFileListColumnAutoSize();
  11264. }
  11265. //---------------------------------------------------------------------------
  11266. void __fastcall TCustomScpExplorerForm::CloseApp()
  11267. {
  11268. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11269. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11270. // So we clear the flag here.
  11271. DebugAssert(NonVisualDataModule->Busy);
  11272. NonVisualDataModule->EndBusy();
  11273. try
  11274. {
  11275. Close();
  11276. }
  11277. __finally
  11278. {
  11279. NonVisualDataModule->StartBusy();
  11280. }
  11281. }
  11282. //---------------------------------------------------------------------------
  11283. bool TCustomScpExplorerForm::IsAvailableTerminal(TTerminal * Terminal)
  11284. {
  11285. return TTerminalManager::Instance()->IsAvailableTerminal(Terminal);
  11286. }
  11287. //---------------------------------------------------------------------------
  11288. bool TCustomScpExplorerForm::HasAvailableTerminal()
  11289. {
  11290. return IsAvailableTerminal(Terminal);
  11291. }
  11292. //---------------------------------------------------------------------------
  11293. void TCustomScpExplorerForm::LocalLocalCopy(
  11294. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11295. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11296. {
  11297. DebugFail();
  11298. }
  11299. //---------------------------------------------------------------------------
  11300. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11301. {
  11302. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11303. }
  11304. //---------------------------------------------------------------------------
  11305. void TCustomScpExplorerForm::UpdateTabsSize()
  11306. {
  11307. // 1) Changing tab list triggers the OnResize.
  11308. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11309. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11310. {
  11311. // UpdateTabsCaptionTruncation should be enough
  11312. SessionListChanged(true);
  11313. }
  11314. }
  11315. //---------------------------------------------------------------------------
  11316. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11317. {
  11318. UpdateTabsSize();
  11319. }
  11320. //---------------------------------------------------------------------------
  11321. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11322. {
  11323. if (ASession == ManagedSession)
  11324. {
  11325. UpdateSession(ASession);
  11326. }
  11327. TSessionData * Data = ASession->StateData;
  11328. UnicodeString Result;
  11329. if (Side == osLocal)
  11330. {
  11331. Result = Data->LocalDirectory;
  11332. }
  11333. else if (DebugAlwaysTrue(Side == osOther))
  11334. {
  11335. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11336. }
  11337. return Result;
  11338. }
  11339. //---------------------------------------------------------------------------
  11340. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11341. {
  11342. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11343. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11344. if (Title == Result)
  11345. {
  11346. Result = EmptyStr;
  11347. }
  11348. else
  11349. {
  11350. Result += L"\n";
  11351. }
  11352. return Result;
  11353. }
  11354. //---------------------------------------------------------------------------
  11355. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11356. {
  11357. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11358. if (!ASession->Active)
  11359. {
  11360. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11361. }
  11362. else
  11363. {
  11364. Result += GetSessionPath(ASession, osRemote);
  11365. }
  11366. return Result;
  11367. }
  11368. //---------------------------------------------------------------------------
  11369. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11370. {
  11371. return LoadStr(NEW_REMOTE_TAB_HINT);
  11372. }
  11373. //---------------------------------------------------------------------------
  11374. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11375. {
  11376. if (Index >= 0)
  11377. {
  11378. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11379. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11380. if (TabSession == NULL)
  11381. {
  11382. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11383. if (NewTabTabCaption != TabSheet->Caption)
  11384. {
  11385. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11386. }
  11387. }
  11388. else
  11389. {
  11390. TTerminalManager * Manager = TTerminalManager::Instance();
  11391. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11392. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11393. }
  11394. }
  11395. }
  11396. //---------------------------------------------------------------------------
  11397. typedef std::vector<TListItem *> TListItemsVector;
  11398. struct TCalculateSizeOperation
  11399. {
  11400. TCalculateSizeStats Stats;
  11401. TListItemsVector ListItems;
  11402. size_t Index;
  11403. };
  11404. //---------------------------------------------------------------------------
  11405. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11406. {
  11407. TCalculateSizeOperation CalculateSizeOperation;
  11408. Side = GetSide(Side);
  11409. TCustomDirView * ADirView = DirView(Side);
  11410. bool LocalSide = IsSideLocalBrowser(Side);
  11411. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11412. std::unique_ptr<TStrings> FileList(new TStringList());
  11413. for (int Index = 0; Index < AllFileList->Count; Index++)
  11414. {
  11415. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11416. if (ADirView->ItemIsDirectory(Item))
  11417. {
  11418. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11419. CalculateSizeOperation.ListItems.push_back(Item);
  11420. }
  11421. }
  11422. CalculateSizeOperation.Index = 0;
  11423. __int64 Size = 0;
  11424. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation, &CalculateSizeOperation);
  11425. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11426. FOnFileOperationFinished = DirectorySizeCalculated;
  11427. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation, foCalculateSize);
  11428. TCalculatedSizes CalculatedSizes;
  11429. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11430. if (LocalSide)
  11431. {
  11432. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, Side);
  11433. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11434. }
  11435. else
  11436. {
  11437. TCalculateSizeParams Params;
  11438. Params.Stats = &CalculateSizeOperation.Stats;
  11439. Params.UseCache = true;
  11440. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11441. }
  11442. }
  11443. //---------------------------------------------------------------------------
  11444. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(
  11445. TOperationSide Side, const UnicodeString & FileName, bool Success, bool NotCancelled)
  11446. {
  11447. DebugAssert(FCalculateSizeOperation != NULL);
  11448. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11449. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11450. // optimization
  11451. bool GotExpectedItem =
  11452. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11453. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11454. int Index = -1;
  11455. if (DebugAlwaysTrue(GotExpectedItem))
  11456. {
  11457. Index = FCalculateSizeOperation->Index;
  11458. FCalculateSizeOperation->Index++;
  11459. }
  11460. else
  11461. {
  11462. TListItemsVector::iterator I =
  11463. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11464. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11465. {
  11466. Index = I - FCalculateSizeOperation->ListItems.begin();
  11467. }
  11468. }
  11469. if (DebugAlwaysTrue(Index >= 0) && Success && NotCancelled)
  11470. {
  11471. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11472. ADirView->SetItemCalculatedSize(Item, Size);
  11473. }
  11474. }
  11475. //---------------------------------------------------------------------------
  11476. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11477. {
  11478. Accept = false;
  11479. }
  11480. //---------------------------------------------------------------------------
  11481. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11482. {
  11483. // Send Ctrl+Gray+ to the list view
  11484. TKeyboardState KeyState;
  11485. GetKeyboardState(KeyState);
  11486. TKeyboardState NewKeyState;
  11487. memset(NewKeyState, 0, sizeof(NewKeyState));
  11488. NewKeyState[VK_CONTROL] = 0x81;
  11489. SetKeyboardState(NewKeyState);
  11490. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11491. SetKeyboardState(KeyState);
  11492. }
  11493. //---------------------------------------------------------------------------
  11494. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11495. {
  11496. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11497. }
  11498. //---------------------------------------------------------------------------
  11499. void * TCustomScpExplorerForm::SaveFocus()
  11500. {
  11501. return NULL;
  11502. }
  11503. //---------------------------------------------------------------------------
  11504. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11505. {
  11506. DebugUsedParam(Focus);
  11507. DebugAssert(Focus == NULL);
  11508. }
  11509. //---------------------------------------------------------------------------
  11510. void TCustomScpExplorerForm::IncrementalSearchStart()
  11511. {
  11512. TCustomDirView * ADirView = DirView(osCurrent);
  11513. ADirView->SetFocus();
  11514. if (!FIncrementalSearchState.Searching)
  11515. {
  11516. FIncrementalSearchState.Searching = true;
  11517. FIncrementalSearchState.HaveNext = false;
  11518. DebugAssert(FIncrementalSearchState.Text.IsEmpty());
  11519. ADirView->UpdateStatusBar();
  11520. }
  11521. }
  11522. //---------------------------------------------------------------------------
  11523. void __fastcall TCustomScpExplorerForm::RemoteDirViewThumbnailNeeded(
  11524. TUnixDirView *, TListItem * Item, TRemoteFile * File, const TSize & Size, TBitmap *& Bitmap)
  11525. {
  11526. // though when downloading to temporary folder, encryption should not be a problem
  11527. if (Terminal->IsCapable[fcBackgroundTransfers] &&
  11528. !File->IsDirectory)
  11529. {
  11530. UnicodeString FileName = File->FullFileName;
  11531. TFileMasks::TParams MaskParams;
  11532. MaskParams.Size = File->Size;
  11533. MaskParams.Modification = File->Modification;
  11534. if ((File->Size <= static_cast<__int64>(WinConfiguration->RemoteThumbnailSizeLimit) * 1024) &&
  11535. FRemoteThumbnailMask.Matches(FileName, false, File->IsDirectory, &MaskParams))
  11536. {
  11537. Bitmap = TTerminalManager::Instance()->ThumbnailNeeded(Terminal, Item->Index, File, Size);
  11538. }
  11539. }
  11540. }
  11541. //---------------------------------------------------------------------------
  11542. TThumbnailDownloadQueueItem * TCustomScpExplorerForm::AddThumbnailDownloadQueueItem(TManagedTerminal * ATerminal)
  11543. {
  11544. DebugAssert(ATerminal == Terminal);
  11545. TCopyParamType CopyParam = TemporaryFileCopyParam();
  11546. CopyParam.TransferMode = tmBinary;
  11547. UnicodeString SourceDir = ATerminal->CurrentDirectory;
  11548. UnicodeString TempDir, RootTempDir;
  11549. TemporaryDirectoryForRemoteFiles(SourceDir, CopyParam, true, TempDir, RootTempDir);
  11550. TTerminalQueue * AQueue = TTerminalManager::Instance()->FindQueueForTerminal(ATerminal);
  11551. DebugAssert((Queue == NULL) || (AQueue == Queue)); // we might get here before queue is set
  11552. TThumbnailDownloadQueueItem * QueueItem =
  11553. new TThumbnailDownloadQueueItem(this, Terminal, SourceDir, TempDir, &CopyParam);
  11554. AddQueueItem(AQueue, QueueItem, ATerminal);
  11555. return QueueItem;
  11556. }
  11557. //---------------------------------------------------------------------------
  11558. enum { qccRemoteItemVisible, qccRemoteItemRedraw };
  11559. typedef std::pair<int, UnicodeString> TRemoteItemVisibleData;
  11560. //---------------------------------------------------------------------------
  11561. void TCustomScpExplorerForm::PostThumbnailVisibleQueueQuery(int Index, const UnicodeString & FileName)
  11562. {
  11563. // The queue might be destroyed before the WM_QUEUE_CALLBACK is processed
  11564. TRemoteItemVisibleData * Data = new TRemoteItemVisibleData();
  11565. Data->first = Index;
  11566. Data->second = FileName;
  11567. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemVisible, reinterpret_cast<WPARAM>(Data));
  11568. }
  11569. //---------------------------------------------------------------------------
  11570. void TCustomScpExplorerForm::PostThumbnailDrawRequest(int Index)
  11571. {
  11572. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemRedraw, Index);
  11573. }
  11574. //---------------------------------------------------------------------------
  11575. void TCustomScpExplorerForm::WMQueueCallback(TMessage & Message)
  11576. {
  11577. int Command = Message.WParam;
  11578. if (Command == qccRemoteItemVisible)
  11579. {
  11580. TRemoteItemVisibleData * Data = reinterpret_cast<TRemoteItemVisibleData *>(Message.LParam);
  11581. int Index = Data->first;
  11582. UnicodeString FileName = Data->second;
  11583. delete Data;
  11584. TGuard Guard(Terminal->ThumbnailsSection.get());
  11585. bool Visible = False;
  11586. if (Terminal->ThumbnailsEnabled &&
  11587. // though we should better also disable thumbnails once we switch to different view style
  11588. (RemoteDirView->DirViewStyle == dvsThumbnail))
  11589. {
  11590. // The message might be processed, while we are already loading a different directory
  11591. if ((Index >= 0) &&
  11592. (Index < RemoteDirView->Items->Count))
  11593. {
  11594. TListItem * Item = RemoteDirView->Items->Item[Index];
  11595. Visible =
  11596. (RemoteDirView->ItemFullFileName(Item) == FileName) &&
  11597. ListView_IsItemVisible(RemoteDirView->Handle, Index);
  11598. }
  11599. }
  11600. Terminal->ThumbnailVisible(Index, FileName, Visible);
  11601. }
  11602. else if (Command == qccRemoteItemRedraw)
  11603. {
  11604. int Index = Message.LParam;
  11605. if ((Index >= 0) &&
  11606. (Index < RemoteDirView->Items->Count))
  11607. {
  11608. RemoteDirView->InvalidateItem(RemoteDirView->Items->Item[Index]);
  11609. }
  11610. }
  11611. }
  11612. //---------------------------------------------------------------------------
  11613. void TCustomScpExplorerForm::InitializeRemoteThumbnailMask()
  11614. {
  11615. UnicodeString DefaultRemoteThumbnailMask = L"*.jpg;*.jpeg;*.gif;*.png;*.svg;*.bmp;*.raw;*.ico;*.heic;*.webp";
  11616. UnicodeString RemoteThumbnailMask = WinConfiguration->RemoteThumbnailMask;
  11617. if (RemoteThumbnailMask.IsEmpty() ||
  11618. StartsStr(L"+", RemoteThumbnailMask) || StartsStr(L"-", RemoteThumbnailMask) || StartsStr(L"*", RemoteThumbnailMask))
  11619. {
  11620. std::unique_ptr<TStrings> RemoteThumbnailMasks(new TStringList());
  11621. while (!DefaultRemoteThumbnailMask.IsEmpty())
  11622. {
  11623. RemoteThumbnailMasks->Add(CutToChar(DefaultRemoteThumbnailMask, L';', true));
  11624. }
  11625. RemoteThumbnailMasks.reset(ProcessFeatures(RemoteThumbnailMasks.get(), RemoteThumbnailMask));
  11626. RemoteThumbnailMask = EmptyStr;
  11627. for (int Index = 0; Index < RemoteThumbnailMasks->Count; Index++)
  11628. {
  11629. AddToList(RemoteThumbnailMask, RemoteThumbnailMasks->Strings[Index], L";");
  11630. }
  11631. }
  11632. FRemoteThumbnailMask.Masks = RemoteThumbnailMask;
  11633. }
  11634. //---------------------------------------------------------------------------
  11635. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartLoading(TObject *)
  11636. {
  11637. Terminal->StartLoadingDirectory();
  11638. }
  11639. //---------------------------------------------------------------------------
  11640. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartReading(TObject *)
  11641. {
  11642. Terminal->DisableThumbnails();
  11643. }
  11644. //---------------------------------------------------------------------------
  11645. void TCustomScpExplorerForm::ChangeDirViewStyle(TOperationSide Side, TDirViewStyle DirViewStyle)
  11646. {
  11647. TCustomDirView * ADirView = DirView(Side);
  11648. if (ADirView->DirViewStyle != DirViewStyle)
  11649. {
  11650. if (DirViewStyle == dvsThumbnail)
  11651. {
  11652. if (dynamic_cast<TUnixDirView *>(ADirView) != NULL)
  11653. {
  11654. Configuration->Usage->Inc(L"ThumbnailsRemote");
  11655. }
  11656. else
  11657. {
  11658. Configuration->Usage->Inc(L"ThumbnailsLocal");
  11659. }
  11660. }
  11661. ADirView->DirViewStyle = DirViewStyle;
  11662. UpdateControls();
  11663. }
  11664. }