CustomScpExplorer.cpp 417 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <Common.h>
  6. #include "CustomScpExplorer.h"
  7. #include <algorithm>
  8. #include <Bookmarks.h>
  9. #include <Interface.h>
  10. #include <Exceptions.h>
  11. #include <CoreMain.h>
  12. #include <FileSystems.h>
  13. #include <TextsCore.h>
  14. #include <TextsWin.h>
  15. #include <HelpWin.h>
  16. #include <VCLCommon.h>
  17. #include <Progress.h>
  18. #include <SynchronizeProgress.h>
  19. #include <DragExt.h>
  20. #include <WinApi.h>
  21. #include "NonVisual.h"
  22. #include "Glyphs.h"
  23. #include "Tools.h"
  24. #include "WinConfiguration.h"
  25. #include "TerminalManager.h"
  26. #include "EditorManager.h"
  27. #include "ProgParams.h"
  28. #include "Setup.h"
  29. #include <Consts.hpp>
  30. #include <DateUtils.hpp>
  31. #include <TB2Common.hpp>
  32. #include <DirectoryMonitor.hpp>
  33. #include <System.IOUtils.hpp>
  34. #include <System.StrUtils.hpp>
  35. //---------------------------------------------------------------------------
  36. #pragma package(smart_init)
  37. #pragma link "CustomDirView"
  38. #pragma link "CustomUnixDirView"
  39. #pragma link "IEListView"
  40. #pragma link "NortonLikeListView"
  41. #pragma link "UnixDirView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "UnixDriveView"
  44. #pragma link "CustomDriveView"
  45. #pragma link "TB2Dock"
  46. #pragma link "TBXStatusBars"
  47. #pragma link "TB2Item"
  48. #pragma link "TB2Toolbar"
  49. #pragma link "ThemePageControl"
  50. #pragma link "PathLabel"
  51. #pragma resource "*.dfm"
  52. //---------------------------------------------------------------------------
  53. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  54. #define WM_PASTE_FILES (WM_WINSCP_USER + 14)
  55. static const int SessionPanelCount = 3;
  56. //---------------------------------------------------------------------------
  57. class TMutexGuard
  58. {
  59. public:
  60. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  61. int Timeout = 5000)
  62. {
  63. FMutex = NULL;
  64. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  65. if (WaitResult == WAIT_TIMEOUT)
  66. {
  67. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  68. }
  69. else
  70. {
  71. FMutex = AMutex;
  72. }
  73. }
  74. ~TMutexGuard()
  75. {
  76. if (FMutex != NULL)
  77. {
  78. ReleaseMutex(FMutex);
  79. }
  80. }
  81. private:
  82. HANDLE FMutex;
  83. };
  84. //---------------------------------------------------------------------------
  85. class TWindowLock
  86. {
  87. public:
  88. TWindowLock(TCustomScpExplorerForm * Form) :
  89. FForm(Form)
  90. {
  91. FForm->LockWindow();
  92. }
  93. ~TWindowLock()
  94. {
  95. FForm->UnlockWindow();
  96. }
  97. private:
  98. TCustomScpExplorerForm * FForm;
  99. };
  100. //---------------------------------------------------------------------------
  101. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  102. FForm(Form)
  103. {
  104. FForm->BatchStart(FBatchStorage);
  105. }
  106. //---------------------------------------------------------------------------
  107. TAutoBatch::~TAutoBatch()
  108. {
  109. FForm->BatchEnd(FBatchStorage);
  110. }
  111. //---------------------------------------------------------------------------
  112. struct TTransferOperationParam
  113. {
  114. TTransferOperationParam();
  115. UnicodeString TargetDirectory;
  116. bool Temp;
  117. bool DragDrop;
  118. int Options;
  119. TAutoSwitch Queue;
  120. };
  121. //---------------------------------------------------------------------------
  122. TTransferOperationParam::TTransferOperationParam()
  123. {
  124. Temp = false;
  125. DragDrop = false;
  126. Options = 0;
  127. Queue = asAuto;
  128. }
  129. //---------------------------------------------------------------------------
  130. class TTransferPresetNoteData : public TObject
  131. {
  132. public:
  133. UnicodeString Message;
  134. };
  135. //---------------------------------------------------------------------------
  136. class TTerminalNoteData : public TObject
  137. {
  138. public:
  139. TManagedTerminal * Terminal;
  140. };
  141. //---------------------------------------------------------------------------
  142. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  143. FFormRestored(false),
  144. TForm(Owner)
  145. {
  146. AddStartupSequence(L"F");
  147. FInvalid = false;
  148. FCurrentSide = osRemote;
  149. FEverShown = false;
  150. FDocks = new TList();
  151. InitControls();
  152. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  153. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  154. NonVisualDataModule->ScpExplorer = this;
  155. RestoreParams();
  156. ConfigurationChanged();
  157. RemoteDirView->Invalidate();
  158. FAutoOperation = false;
  159. FOnFileOperationFinished = NULL;
  160. FPrimaryOperation = foNone;
  161. FForceExecution = false;
  162. FIgnoreNextDialogChar = 0;
  163. FErrorList = NULL;
  164. FSynchronizeProgressForm = NULL;
  165. FProgressForm = NULL;
  166. FRefreshLocalDirectory = false;
  167. FRefreshRemoteDirectory = false;
  168. FDDExtMapFile = NULL;
  169. // CreateMutexW keeps failing with ERROR_NOACCESS
  170. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  171. DebugAssert(FDDExtMutex != NULL);
  172. FDDTargetControl = NULL;
  173. FDelayedDeletionTimer = NULL;
  174. FDelayedDeletionList = new TStringList();
  175. FDDFileList = NULL;
  176. FPendingTempSpaceWarn = false;
  177. FCapturedLog = NULL;
  178. FDragDropOperation = false;
  179. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  180. FAllowTransferPresetAutoSelect = true;
  181. FSessionChanging = false;
  182. FCopyParamDefault = L"";
  183. FSynchronizeController = NULL;
  184. FPendingQueueActionItem = NULL;
  185. FLockLevel = 0;
  186. FLockSuspendLevel = 0;
  187. FDisabledOnLockSuspend = false;
  188. FAlternativeDelete = false;
  189. FTrayIcon = new ::TTrayIcon(0);
  190. FTrayIcon->OnClick = TrayIconClick;
  191. FMaxQueueLength = 0;
  192. FLastContextPopupScreenPoint = TPoint(-1, -1);
  193. FTransferResumeList = NULL;
  194. FDeletedFiles = NULL;
  195. FMoveToQueue = false;
  196. StandaloneOperation = false;
  197. FOnFeedSynchronizeError = NULL;
  198. FOnSynchronizeAbort = NULL;
  199. FSynchronizeTerminal = NULL;
  200. FNeedSession = false;
  201. FDoNotIdleCurrentTerminal = 0;
  202. FIncrementalSearching = 0;
  203. FQueueFileList.reset(new TQueueFileList());
  204. FProgressSide = osCurrent;
  205. FCalculateSizeOperation = NULL;
  206. FDownloadingFromClipboard = false;
  207. FClipboardFakeMonitorsPendingReset = false;
  208. FHiContrastTheme = NULL;
  209. InitializeRemoteThumbnailMask();
  210. GlyphsModule->PixelsPerInch = CurrentPPI;
  211. FEditorManager = new TEditorManager();
  212. FEditorManager->OnFileChange = ExecutedFileChanged;
  213. FEditorManager->OnFileReload = ExecutedFileReload;
  214. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  215. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  216. FLocalEditors = new TList();
  217. FQueueStatus = NULL;
  218. FQueueStatusSection = new TCriticalSection();
  219. FQueueStatusInvalidated = false;
  220. FQueueItemInvalidated = false;
  221. FQueueStatusUpdating = false;
  222. FQueueActedItem = NULL;
  223. FQueueController = new TQueueController(QueueView3);
  224. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  225. FUserActionTimer = new TTimer(this);
  226. FUserActionTimer->Enabled = false;
  227. FUserActionTimer->Interval = 10;
  228. FUserActionTimer->OnTimer = UserActionTimer;
  229. FNotes = new TStringList();
  230. FNoteTimer = new TTimer(this);
  231. FNoteTimer->Enabled = false;
  232. FNoteTimer->OnTimer = NoteTimer;
  233. FOnNoteClick = NULL;
  234. FOle32Library = LoadLibrary(L"Ole32.dll");
  235. FDragMoveCursor = FOle32Library != NULL ?
  236. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  237. UseSystemSettings(this);
  238. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  239. static_cast<TObject*>(GetComponent(fcTransferList)));
  240. DebugAssert(TransferList != NULL);
  241. FTransferListHoverIndex = -1;
  242. TransferList->OnChange = TransferListChange;
  243. TransferList->OnDrawItem = TransferListDrawItem;
  244. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  245. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  246. UseDesktopFont(SessionsPageControl);
  247. UseDesktopFont(RemoteDirView);
  248. UseDesktopFont(RemoteDriveView);
  249. UseDesktopFont(QueueView3);
  250. UseDesktopFont(QueueFileList);
  251. UseDesktopFont(QueueLabel);
  252. UseDesktopFont(RemoteStatusBar);
  253. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  254. QueueSplitter->ShowHint = true;
  255. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  256. QueueFileListSplitter->ShowHint = true;
  257. RemotePanelSplitter->ShowHint = true;
  258. UpdateImages();
  259. FCustomCommandMenu = CreateTBXPopupMenu(this);
  260. FCustomCommandLocalFileList = NULL;
  261. FCustomCommandRemoteFileList = NULL;
  262. FSessionColors = new TPngImageList(this);
  263. FSessionColors->ColorDepth = cd32Bit;
  264. AddFixedSessionImages();
  265. SessionsPageControl->Images = FSessionColors;
  266. // Needed for Explorer (Commander calls it implicitly on its own)
  267. UpdateSessionsPageControlHeight();
  268. UpdateQueueLabel();
  269. CheckStoreTransition();
  270. CreateHiddenWindow();
  271. StartUpdates();
  272. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  273. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  274. DriveInfo->NeedData();
  275. }
  276. //---------------------------------------------------------------------------
  277. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  278. {
  279. AppLog(L"Destroying main window");
  280. FInvalid = true;
  281. ReleaseHiContrastTheme();
  282. if (FClipboardTerminal != NULL)
  283. {
  284. ClipboardClear(); // implies ClipboardStop
  285. }
  286. // this has to be one of the very first things to do
  287. StopUpdateThread();
  288. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  289. TTerminalManager::Instance()->ScpExplorer = NULL;
  290. delete FCustomCommandLocalFileList;
  291. delete FCustomCommandRemoteFileList;
  292. delete FCustomCommandMenu;
  293. delete FTrayIcon;
  294. FTrayIcon = NULL;
  295. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  296. delete FEditorManager;
  297. ForceCloseLocalEditors();
  298. delete FLocalEditors;
  299. HideFileFindDialog();
  300. if (FDelayedDeletionTimer)
  301. {
  302. DoDelayedDeletion(NULL);
  303. SAFE_DESTROY(FDelayedDeletionTimer);
  304. }
  305. SAFE_DESTROY(FDelayedDeletionList);
  306. // sometimes we do not get DDEnd so the list is not released
  307. SAFE_DESTROY(FDDFileList);
  308. DebugAssert(FSynchronizeController == NULL);
  309. CloseHandle(FDDExtMutex);
  310. FDDExtMutex = NULL;
  311. FreeLibrary(FOle32Library);
  312. FOle32Library = NULL;
  313. FDragMoveCursor = NULL;
  314. DebugAssert(!FErrorList);
  315. if (FEverShown)
  316. {
  317. // when window is never shown (like when running command-line operation),
  318. // particularly window site is not restored correctly (BoundsRect value set
  319. // in RestoreForm gets lost during handle allocation), so we do not want
  320. // it to be stored
  321. AppLog(L"Storing main window configuration");
  322. StoreParams();
  323. }
  324. ManagedSession = NULL;
  325. Queue = NULL;
  326. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  327. NonVisualDataModule->ScpExplorer = NULL;
  328. delete FQueueScrollOnDragOver;
  329. FQueueScrollOnDragOver = NULL;
  330. delete FQueueController;
  331. FQueueController = NULL;
  332. delete FQueueStatusSection;
  333. FQueueStatusSection = NULL;
  334. delete FQueueStatus;
  335. FQueueStatus = NULL;
  336. delete FUserActionTimer;
  337. FUserActionTimer = NULL;
  338. delete FNoteTimer;
  339. delete FNotes;
  340. delete FNoteData;
  341. SAFE_DESTROY(FDocks);
  342. SessionsPageControl->Images = NULL;
  343. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  344. SAFE_DESTROY(FSessionColors);
  345. SAFE_DESTROY(FSessionsDragDropFilesEx);
  346. SAFE_DESTROY(FHistoryMenu[0][0]);
  347. SAFE_DESTROY(FHistoryMenu[0][1]);
  348. SAFE_DESTROY(FHistoryMenu[1][0]);
  349. SAFE_DESTROY(FHistoryMenu[1][1]);
  350. if (FHiddenWindow != NULL)
  351. {
  352. DestroyWindow(FHiddenWindow);
  353. FHiddenWindow = NULL;
  354. }
  355. AppLog(L"Main window destroyed");
  356. }
  357. //---------------------------------------------------------------------------
  358. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  359. {
  360. if (FHiContrastTheme != NULL)
  361. {
  362. ReleaseTBXTheme(FHiContrastTheme);
  363. FHiContrastTheme = NULL;
  364. }
  365. }
  366. //---------------------------------------------------------------------------
  367. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  368. {
  369. std::unique_ptr<TSessionData> Data;
  370. if (!Session.IsEmpty())
  371. {
  372. bool DefaultsOnly;
  373. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  374. }
  375. TTerminalManager * Manager = TTerminalManager::Instance();
  376. for (int Index = 0; Index < Manager->Count; Index++)
  377. {
  378. TTerminal * Terminal = Manager->Sessions[Index];
  379. if (Session.IsEmpty() ||
  380. Manager->IsAvailableTerminalForSite(Terminal, Data.get()))
  381. {
  382. if (Path.IsEmpty())
  383. {
  384. Terminal->ClearCaches();
  385. }
  386. else
  387. {
  388. Terminal->DirectoryModified(Path, true);
  389. }
  390. }
  391. }
  392. // We should flag a pending refresh for the background terminals or busy foreground terminals
  393. if (HasAvailableTerminal() &&
  394. CanCommandLineFromAnotherInstance() &&
  395. (Session.IsEmpty() || Manager->IsAvailableTerminalForSite(Terminal, Data.get())) &&
  396. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  397. {
  398. Terminal->ReloadDirectory();
  399. }
  400. }
  401. //---------------------------------------------------------------------------
  402. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  403. {
  404. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  405. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  406. size_t MessageSize = sizeof(TCopyDataMessage);
  407. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  408. if (Result)
  409. {
  410. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  411. Result = (Message.Version == TCopyDataMessage::Version1);
  412. if (Result)
  413. {
  414. switch (Message.Command)
  415. {
  416. case TCopyDataMessage::CommandCanCommandLine:
  417. Result = CanCommandLineFromAnotherInstance();
  418. if (Result)
  419. {
  420. AppLog(L"Can process command-line from other instance");
  421. }
  422. else
  423. {
  424. AppLog(L"Cannot process command-line from other instance");
  425. }
  426. break;
  427. case TCopyDataMessage::CommandCommandLine:
  428. {
  429. UnicodeString CommandLine(Message.CommandLine);
  430. Result = CommandLineFromAnotherInstance(CommandLine);
  431. }
  432. break;
  433. case TCopyDataMessage::RefreshPanel:
  434. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  435. break;
  436. case TCopyDataMessage::MainWindowCheck:
  437. Result = true;
  438. break;
  439. default:
  440. Result = false;
  441. break;
  442. }
  443. }
  444. }
  445. Message.Result = Result ? 1 : 0;
  446. }
  447. //---------------------------------------------------------------------------
  448. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  449. {
  450. WNDCLASS WindowClass = {0};
  451. WindowClass.lpfnWndProc = DefWindowProc;
  452. WindowClass.hInstance = HInstance;
  453. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  454. FHiddenWindow = NULL;
  455. if (RegisterClass(&WindowClass))
  456. {
  457. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  458. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  459. }
  460. }
  461. //---------------------------------------------------------------------------
  462. bool __fastcall TCustomScpExplorerForm::CanConsole()
  463. {
  464. return
  465. HasAvailableTerminal() &&
  466. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  467. }
  468. //---------------------------------------------------------------------------
  469. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  470. {
  471. bool Result = Visible && !NonVisualDataModule->Busy;
  472. return Result;
  473. }
  474. //---------------------------------------------------------------------------
  475. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  476. const UnicodeString & CommandLine)
  477. {
  478. TProgramParams Params(CommandLine);
  479. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  480. if (Result)
  481. {
  482. NonVisualDataModule->StartBusy();
  483. try
  484. {
  485. // this action is initiated from another process,
  486. // so it's likely that our window is not visible,
  487. // and user won't see what is going on
  488. Application->BringToFront();
  489. // reload sessions as we may be asked to open a session
  490. // just stored by another instance
  491. StoredSessions->Reload();
  492. UnicodeString SessionName = Params.Param[1];
  493. std::unique_ptr<TObjectList> DataList(new TObjectList());
  494. try
  495. {
  496. UnicodeString DownloadFile; // unused
  497. int Flags = GetCommandLineParseUrlFlags(&Params);
  498. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  499. }
  500. catch (EAbort &)
  501. {
  502. // Happens when opening session in PuTTY and in other situations,
  503. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  504. // to process the command-line on its own (or to pass it to yet another instance)
  505. }
  506. if (DataList->Count > 0)
  507. {
  508. TTerminalManager * Manager = TTerminalManager::Instance();
  509. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  510. }
  511. }
  512. __finally
  513. {
  514. NonVisualDataModule->EndBusy();
  515. }
  516. }
  517. return Result;
  518. }
  519. //---------------------------------------------------------------------------
  520. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  521. {
  522. TManagedTerminal * Result;
  523. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  524. {
  525. Result = FManagedSession;
  526. }
  527. else
  528. {
  529. Result = NULL;
  530. }
  531. return Result;
  532. }
  533. //---------------------------------------------------------------------------
  534. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  535. {
  536. if (FManagedSession != value)
  537. {
  538. TWindowLock Lock(this);
  539. SessionChanging();
  540. DoSetManagedSession(value, false);
  541. }
  542. }
  543. //---------------------------------------------------------------------------
  544. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  545. {
  546. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  547. FManagedSession = value;
  548. {
  549. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect, false);
  550. TAutoFlag SessionChangingFlag(FSessionChanging);
  551. SessionChanged(Replace);
  552. }
  553. if (Terminal != NULL)
  554. {
  555. TransferPresetAutoSelect();
  556. }
  557. // Update app and tab titles, prevented above by FSessionChanging.
  558. UpdateControls();
  559. }
  560. //---------------------------------------------------------------------------
  561. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  562. {
  563. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  564. DoSetManagedSession(value, true);
  565. }
  566. //---------------------------------------------------------------------------
  567. void __fastcall TCustomScpExplorerForm::SessionChanging()
  568. {
  569. if (ManagedSession != NULL)
  570. {
  571. UpdateSession(ManagedSession);
  572. }
  573. }
  574. //---------------------------------------------------------------------------
  575. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  576. {
  577. if (ManagedSession != NULL)
  578. {
  579. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  580. }
  581. if (!TTerminalManager::Instance()->Updating)
  582. {
  583. SessionListChanged();
  584. }
  585. if (Terminal != NULL)
  586. {
  587. TObject * State = NULL;
  588. if (WinConfiguration->PreservePanelState)
  589. {
  590. State = Terminal->RemoteExplorerState;
  591. DirView(osRemote)->AnnounceState(State);
  592. }
  593. try
  594. {
  595. if (Replaced)
  596. {
  597. RemoteDirView->ReplaceTerminal(Terminal);
  598. }
  599. else
  600. {
  601. RemoteDirView->Terminal = Terminal;
  602. }
  603. if (Terminal->Active)
  604. {
  605. Terminal->RefreshDirectory();
  606. }
  607. if (State != NULL)
  608. {
  609. DirView(osRemote)->RestoreState(State);
  610. }
  611. }
  612. __finally
  613. {
  614. DirView(osRemote)->AnnounceState(NULL);
  615. }
  616. }
  617. else
  618. {
  619. RemoteDirView->Terminal = NULL;
  620. }
  621. InitStatusBar();
  622. UpdateTransferList();
  623. // Update panels Enable state before refreshing the labels
  624. UpdateControls();
  625. }
  626. //---------------------------------------------------------------------------
  627. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  628. {
  629. if (Queue != value)
  630. {
  631. if (FQueue != NULL)
  632. {
  633. FQueue->OnListUpdate = NULL;
  634. FQueue->OnQueueItemUpdate = NULL;
  635. }
  636. FQueue = value;
  637. if (FQueue != NULL)
  638. {
  639. DebugAssert(FQueue->OnListUpdate == NULL);
  640. FQueue->OnListUpdate = QueueListUpdate;
  641. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  642. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  643. }
  644. QueueChanged();
  645. }
  646. }
  647. //---------------------------------------------------------------------------
  648. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  649. TListItem * Item)
  650. {
  651. if (FQueueActedItem == Item)
  652. {
  653. FQueueActedItem = NULL;
  654. if ((QueueView3->PopupMenu != NULL) &&
  655. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  656. {
  657. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  658. ReleaseCapture();
  659. }
  660. }
  661. if (Item->Data == FPendingQueueActionItem)
  662. {
  663. FPendingQueueActionItem = NULL;
  664. }
  665. }
  666. //---------------------------------------------------------------------------
  667. bool TCustomScpExplorerForm::IsAnythingQueued()
  668. {
  669. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  670. }
  671. //---------------------------------------------------------------------------
  672. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  673. {
  674. {
  675. TGuard Guard(FQueueStatusSection);
  676. FQueueStatusInvalidated = false;
  677. if (FQueue != NULL)
  678. {
  679. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  680. }
  681. }
  682. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  683. {
  684. FMaxQueueLength = FQueueStatus->Count;
  685. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  686. }
  687. {
  688. TAutoFlag Flag(FQueueStatusUpdating);
  689. FQueueController->UpdateQueueStatus(FQueueStatus);
  690. }
  691. UpdateQueueFileList();
  692. SetQueueProgress();
  693. UpdateQueueView();
  694. bool IsEmpty = !IsAnythingQueued();
  695. if (IsEmpty && (Terminal != NULL))
  696. {
  697. TOnceDoneOperation OnceDoneOperation =
  698. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  699. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  700. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  701. {
  702. FQueue->Enabled = false;
  703. }
  704. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  705. {
  706. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  707. }
  708. }
  709. }
  710. //---------------------------------------------------------------------------
  711. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  712. {
  713. UnicodeString Result;
  714. if (FQueueStatus != NULL)
  715. {
  716. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  717. {
  718. TFileOperationProgressType * ProgressData =
  719. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  720. if ((ProgressData != NULL) && ProgressData->InProgress)
  721. {
  722. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  723. }
  724. }
  725. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  726. {
  727. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  728. }
  729. }
  730. return Result;
  731. }
  732. //---------------------------------------------------------------------------
  733. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  734. {
  735. ComponentVisible[fcQueueView] =
  736. !IsLocalBrowserMode() &&
  737. ((WinConfiguration->QueueView.Show == qvShow) ||
  738. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  739. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  740. }
  741. //---------------------------------------------------------------------------
  742. void __fastcall TCustomScpExplorerForm::QueueChanged()
  743. {
  744. if (FQueueStatus != NULL)
  745. {
  746. // UpdateFileList implementation relies on the status being recreated when session changes
  747. delete FQueueStatus;
  748. FQueueStatus = NULL;
  749. }
  750. UpdateQueueStatus(true);
  751. }
  752. //---------------------------------------------------------------------------
  753. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  754. {
  755. if (FQueue == Queue)
  756. {
  757. FQueueStatusInvalidated = true;
  758. }
  759. }
  760. //---------------------------------------------------------------------------
  761. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  762. TQueueItem * Item)
  763. {
  764. if (FQueue == Queue)
  765. {
  766. TGuard Guard(FQueueStatusSection);
  767. // this may be running in parallel with QueueChanged
  768. if (FQueueStatus != NULL)
  769. {
  770. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  771. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  772. {
  773. FRefreshLocalDirectory = (QueueItem == NULL) ||
  774. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  775. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  776. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  777. }
  778. if (QueueItem != NULL)
  779. {
  780. QueueItem->UserData = (void*)true;
  781. FQueueItemInvalidated = true;
  782. }
  783. }
  784. }
  785. }
  786. //---------------------------------------------------------------------------
  787. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  788. {
  789. // during standalone editing, we have no way to see/control queue,
  790. // so we have to always popup prompts automatically
  791. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  792. }
  793. //---------------------------------------------------------------------------
  794. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  795. {
  796. if (FQueueStatus != NULL)
  797. {
  798. bool QueueAutoPopup = IsQueueAutoPopup();
  799. bool NeedRefresh = FQueueController->NeedRefresh();
  800. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  801. FQueueItemInvalidated = false;
  802. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  803. bool Updated = false;
  804. TQueueItemProxy * QueueItem;
  805. bool WasUserAction;
  806. for (int Index = 0; Index < Limit; Index++)
  807. {
  808. bool Update = false;
  809. QueueItem = FQueueStatus->Items[Index];
  810. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  811. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  812. (FPendingQueueActionItem == NULL))
  813. {
  814. FPendingQueueActionItem = QueueItem;
  815. FUserActionTimer->Enabled = true;
  816. }
  817. if ((bool)QueueItem->UserData)
  818. {
  819. QueueItem->UserData = (void*)false;
  820. QueueItem->Update();
  821. Updated = true;
  822. Update = true;
  823. }
  824. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  825. {
  826. Update = true;
  827. }
  828. if (Update)
  829. {
  830. FQueueController->RefreshQueueItem(QueueItem);
  831. }
  832. }
  833. if (Updated)
  834. {
  835. NonVisualDataModule->UpdateNonVisibleActions();
  836. SetQueueProgress();
  837. UpdateQueueFileList();
  838. }
  839. }
  840. }
  841. //---------------------------------------------------------------------------
  842. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  843. {
  844. if (FTaskbarList != NULL)
  845. {
  846. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  847. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  848. }
  849. }
  850. //---------------------------------------------------------------------------
  851. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  852. {
  853. if (Progress >= 0)
  854. {
  855. if (FTaskbarList != NULL)
  856. {
  857. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  858. }
  859. }
  860. else
  861. {
  862. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  863. }
  864. }
  865. //---------------------------------------------------------------------------
  866. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  867. {
  868. int OverallProgress;
  869. // FProgressForm is null when this is called from SetQueueProgress
  870. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  871. {
  872. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  873. }
  874. else if (!ProgressData->IsIndeterminate())
  875. {
  876. OverallProgress = ProgressData->OverallProgress();
  877. }
  878. else
  879. {
  880. OverallProgress = -1;
  881. }
  882. SetTaskbarListProgressValue(OverallProgress);
  883. }
  884. //---------------------------------------------------------------------------
  885. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  886. {
  887. TTerminalManager::Instance()->QueueStatusUpdated();
  888. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  889. {
  890. // Do not animate task bar button, when items are queued, but processing is disabled
  891. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  892. {
  893. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  894. {
  895. TFileOperationProgressType * ProgressData = NULL;
  896. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  897. {
  898. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  899. }
  900. if ((ProgressData != NULL) &&
  901. ProgressData->InProgress)
  902. {
  903. SetTaskbarListProgressValue(ProgressData);
  904. }
  905. else
  906. {
  907. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  908. }
  909. }
  910. else
  911. {
  912. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  913. }
  914. }
  915. else
  916. {
  917. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  918. }
  919. }
  920. UpdateQueueLabel();
  921. }
  922. //---------------------------------------------------------------------------
  923. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  924. {
  925. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  926. if (FQueueStatus != NULL)
  927. {
  928. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  929. if (ActiveAndPendingPrimaryCount > 0)
  930. {
  931. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  932. }
  933. }
  934. QueueLabel->Caption = Caption;
  935. }
  936. //---------------------------------------------------------------------------
  937. void TCustomScpExplorerForm::CheckStoreTransition()
  938. {
  939. if (WinConfiguration->StoreTransition == stInit)
  940. {
  941. if (IsUWP())
  942. {
  943. WinConfiguration->StoreTransition = stStoreFresh;
  944. AppLog(L"Fresh UWP/store installation");
  945. }
  946. else
  947. {
  948. WinConfiguration->StoreTransition = stStandard;
  949. AppLog(L"Fresh standard installation");
  950. }
  951. }
  952. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  953. {
  954. WinConfiguration->StoreTransition = stStoreMigrated;
  955. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  956. AppLog(L"Standard installation migrated to store installation");
  957. }
  958. if (WinConfiguration->StoreTransition == stStoreMigrated)
  959. {
  960. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  961. Toolbar->Parent = MessageDock;
  962. Toolbar->FullSize = true;
  963. Toolbar->Color = Application->HintColor;
  964. TTBXLabelItem * LabelItem;
  965. LabelItem = new TTBXLabelItem(Toolbar);
  966. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  967. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  968. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  969. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  970. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  971. Toolbar->Items->Add(LabelItem);
  972. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  973. LinkItem->FontSettings->Color = GetLightLinkColor(); // the background is not themed yet
  974. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  975. LinkItem->OnClick = StoreTransitionLinkClick;
  976. Toolbar->Items->Add(LinkItem);
  977. AddMenuSeparator(Toolbar->Items);
  978. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  979. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  980. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  981. CloseItem->OnClick = StoreTransitionCloseClick;
  982. Toolbar->Items->Add(CloseItem);
  983. GiveTBItemPriority(CloseItem);
  984. }
  985. }
  986. //---------------------------------------------------------------------------
  987. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  988. {
  989. ShowHelp(HELP_STORE_TRANSITION);
  990. }
  991. //---------------------------------------------------------------------------
  992. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  993. {
  994. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  995. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  996. delete Toolbar;
  997. WinConfiguration->StoreTransition = stStoreAcknowledged;
  998. UpdateControls();
  999. }
  1000. //---------------------------------------------------------------------------
  1001. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  1002. {
  1003. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  1004. static_cast<TComponent*>(GetComponent(fcTransferList)));
  1005. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  1006. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  1007. TransferList->Strings->BeginUpdate();
  1008. try
  1009. {
  1010. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  1011. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  1012. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  1013. if (FTransferDropDownHint.IsEmpty())
  1014. {
  1015. FTransferDropDownHint = TransferDropDown->Hint;
  1016. }
  1017. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1018. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1019. TransferDropDown->Text = StripHotkey(Name);
  1020. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1021. (FTransferDropDownHint, StripHotkey(Name),
  1022. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1023. FLAGMASK(HasAvailableTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1024. // update the label, otherwise when it is updated only on the first draw
  1025. // of the list, it is drawn "bold" for some reason
  1026. FTransferListHoverIndex = TransferList->ItemIndex;
  1027. UpdateTransferLabel();
  1028. }
  1029. __finally
  1030. {
  1031. TransferList->Strings->EndUpdate();
  1032. }
  1033. }
  1034. //---------------------------------------------------------------------------
  1035. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1036. {
  1037. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1038. DebugAssert(Toolbar != NULL);
  1039. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1040. }
  1041. //---------------------------------------------------------------------------
  1042. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1043. {
  1044. TForm::UpdateActions();
  1045. if (ComponentVisible[fcCustomCommandsBand])
  1046. {
  1047. UpdateCustomCommandsToolbar();
  1048. }
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1052. {
  1053. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1057. {
  1058. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1059. {
  1060. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1061. // Without this, the panel turns gray and unused part of header turns black
  1062. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1063. }
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1067. {
  1068. Color = GetBtnFaceColor();
  1069. DebugAssert(Configuration && RemoteDirView);
  1070. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1071. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1072. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1073. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1074. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1075. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1076. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1077. UpdateRowSelect(RemoteDirView);
  1078. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1079. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1080. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1081. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1082. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1083. UpdateSessionsPageControlHeight();
  1084. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1085. UpdateToolbarDisplayMode();
  1086. UpdateTransferList();
  1087. if (Terminal != NULL)
  1088. {
  1089. TransferPresetAutoSelect();
  1090. }
  1091. UpdateQueueView();
  1092. UpdateControls();
  1093. // this can be called even before constuctor finishes.
  1094. if (FEditorManager != NULL)
  1095. {
  1096. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1097. }
  1098. // this can be called even before constuctor finishes.
  1099. if (FLocalEditors != NULL)
  1100. {
  1101. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1102. {
  1103. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1104. }
  1105. }
  1106. if (ComponentVisible[fcCustomCommandsBand])
  1107. {
  1108. UpdateCustomCommandsToolbar();
  1109. }
  1110. // show only when keeping queue items forever,
  1111. // otherwise, it's enough to have it in the context menu
  1112. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1113. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1114. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1115. {
  1116. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1117. FFileColorsCurrent = WinConfiguration->FileColors;
  1118. FileColorsChanged();
  1119. }
  1120. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1121. (FSessionColors != NULL))
  1122. {
  1123. SessionListChanged();
  1124. }
  1125. if (GlyphsModule->LargerToolbar != WinConfiguration->LargerToolbar)
  1126. {
  1127. GlyphsModule->LargerToolbar = WinConfiguration->LargerToolbar;
  1128. if (FSessionColors != NULL)
  1129. {
  1130. RegenerateSessionColorsImageList();
  1131. UpdateSessionsPageControlHeight();
  1132. }
  1133. }
  1134. }
  1135. //---------------------------------------------------------------------------
  1136. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1137. {
  1138. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1139. DirView->Invalidate();
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1143. {
  1144. DoFileColorsChanged(RemoteDirView);
  1145. }
  1146. //---------------------------------------------------------------------------
  1147. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1148. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1149. void * /*Arg*/)
  1150. {
  1151. if (Token != NULL)
  1152. {
  1153. TForm * Editor = dynamic_cast<TForm*>(Token);
  1154. DebugAssert(Editor != NULL);
  1155. ReconfigureEditorForm(Editor);
  1156. }
  1157. }
  1158. //---------------------------------------------------------------------------
  1159. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1160. {
  1161. WinConfiguration->DDTransferConfirmation = asOn;
  1162. }
  1163. //---------------------------------------------------------------------------
  1164. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1165. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1166. {
  1167. // noop
  1168. }
  1169. //---------------------------------------------------------------------------
  1170. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1171. {
  1172. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1176. {
  1177. if (DoNotShowAgain)
  1178. {
  1179. if (DragDrop)
  1180. {
  1181. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1182. {
  1183. PopupTrayBalloon(
  1184. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1185. }
  1186. WinConfiguration->DDTransferConfirmation = asOff;
  1187. }
  1188. else
  1189. {
  1190. WinConfiguration->ConfirmTransferring = false;
  1191. }
  1192. }
  1193. else
  1194. {
  1195. // User explicitly unchecked "do not show again",
  1196. // so show him the dialog the next time
  1197. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1198. {
  1199. WinConfiguration->DDTransferConfirmation = asOn;
  1200. }
  1201. }
  1202. }
  1203. //---------------------------------------------------------------------------
  1204. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1205. TTransferDirection Direction, TTransferType Type, bool Temp,
  1206. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1207. bool Confirm, bool DragDrop, int Options)
  1208. {
  1209. bool Result = true;
  1210. DebugAssert(HasAvailableTerminal());
  1211. // these parameters are known in advance
  1212. int Params =
  1213. FLAGMASK(Type == ttMove, cpDelete);
  1214. bool ToTemp = (Temp && (Direction == tdToLocal));
  1215. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1216. {
  1217. bool DisableNewerOnly =
  1218. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1219. ToTemp;
  1220. Options |=
  1221. FLAGMASK(ToTemp, coTemp) |
  1222. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1223. coDoNotShowAgain;
  1224. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1225. int CopyParamAttrs = (Direction == tdToRemote ?
  1226. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1227. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1228. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1229. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1230. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1231. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1232. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1233. if (Result)
  1234. {
  1235. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1236. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1237. }
  1238. }
  1239. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1240. {
  1241. Configuration->Usage->Inc(L"TransfersOnBackground");
  1242. // these parameter are known only after transfer dialog
  1243. Params |=
  1244. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1245. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1246. Result = false;
  1247. ClearTransferSourceSelection(Direction);
  1248. }
  1249. return Result;
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1253. {
  1254. if (FOnFileOperationFinished != NULL)
  1255. {
  1256. FOnFileOperationFinished(Side, UnicodeString(), true, true);
  1257. }
  1258. else
  1259. {
  1260. if (HasDirView[Side])
  1261. {
  1262. DirView(Side)->SelectAll(smNone);
  1263. }
  1264. }
  1265. }
  1266. //---------------------------------------------------------------------------
  1267. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1268. {
  1269. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1270. ClearOperationSelection(Side);
  1271. }
  1272. //---------------------------------------------------------------------------
  1273. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1274. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1275. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1276. int Params)
  1277. {
  1278. DebugAssert(Queue != NULL);
  1279. TQueueItem * QueueItem;
  1280. if (Direction == tdToRemote)
  1281. {
  1282. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1283. QueueItem =
  1284. new TUploadQueueItem(
  1285. Terminal, FileList, TargetDirectory, &CopyParam, Params, CopyParam.QueueParallel);
  1286. }
  1287. else
  1288. {
  1289. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1290. QueueItem =
  1291. new TDownloadQueueItem(
  1292. Terminal, FileList, TargetDirectory, &CopyParam, Params, CopyParam.QueueParallel);
  1293. }
  1294. AddQueueItem(Queue, QueueItem, Terminal);
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1298. {
  1299. if (Queue->IsEmpty)
  1300. {
  1301. Terminal->QueueOperationStart = Now();
  1302. }
  1303. Queue->AddItem(QueueItem);
  1304. }
  1305. //---------------------------------------------------------------------------
  1306. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1307. {
  1308. }
  1309. //---------------------------------------------------------------------------
  1310. void __fastcall TCustomScpExplorerForm::InitControls()
  1311. {
  1312. DebugAssert(FDocks != NULL);
  1313. for (int Index = 0; Index < ComponentCount; Index++)
  1314. {
  1315. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1316. if ((Dock != NULL) && (Dock->Tag == 0))
  1317. {
  1318. FDocks->Add(Dock);
  1319. }
  1320. }
  1321. CollectItemsWithTextDisplayMode(this);
  1322. }
  1323. //---------------------------------------------------------------------------
  1324. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1325. {
  1326. ConfigurationChanged();
  1327. QueuePanel->Height =
  1328. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1329. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1330. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1331. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1332. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1333. QueueFileList->Height =
  1334. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1335. if (QueueFileList->Visible)
  1336. {
  1337. AdjustQueueLayout();
  1338. }
  1339. UpdateCustomCommandsToolbar();
  1340. }
  1341. //---------------------------------------------------------------------------
  1342. void __fastcall TCustomScpExplorerForm::StoreParams()
  1343. {
  1344. int APixelsPerInch = GetControlPixelsPerInch(this);
  1345. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1346. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1347. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1348. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1349. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1350. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1351. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1352. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. void __fastcall TCustomScpExplorerForm::Loaded()
  1356. {
  1357. // Loaded is called in more deterministic moment than previously used CreateParams
  1358. if (!FFormRestored)
  1359. {
  1360. FFormRestored = true;
  1361. RestoreFormParams();
  1362. }
  1363. TForm::Loaded();
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1367. {
  1368. DebugAssert(FDocks != NULL);
  1369. for (int Index = 0; Index < FDocks->Count; Index++)
  1370. {
  1371. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1372. }
  1373. }
  1374. //---------------------------------------------------------------------------
  1375. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1376. {
  1377. SetDockAllowDrag(true);
  1378. while (!ButtonsStr.IsEmpty())
  1379. {
  1380. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1381. UnicodeString Name = CutToChar(S, L'=', true);
  1382. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1383. {
  1384. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1385. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1386. {
  1387. while (!S.IsEmpty())
  1388. {
  1389. UnicodeString S2 = CutToChar(S, L',', true);
  1390. UnicodeString Name = CutToChar(S2, L':', true);
  1391. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1392. {
  1393. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1394. if (SameText(GetToolbarItemName(Item), Name))
  1395. {
  1396. // forward compatibility
  1397. UnicodeString S3 = CutToChar(S2, L':', true);
  1398. bool Visible = StrToIntDef(S3, 0);
  1399. Item->Visible = Visible;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. }
  1405. }
  1406. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1407. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1411. {
  1412. UnicodeString Result;
  1413. SetDockAllowDrag(true);
  1414. Result = ::GetToolbarsLayoutStr(this);
  1415. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1416. return Result;
  1417. }
  1418. //---------------------------------------------------------------------------
  1419. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1420. {
  1421. UnicodeString Result;
  1422. if (Item->Action != NULL)
  1423. {
  1424. Result = Item->Action->Name;
  1425. Result = RemoveSuffix(Result, L"Action", true);
  1426. }
  1427. else
  1428. {
  1429. Result = Item->Name;
  1430. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1431. Result = RemoveSuffix(Result, L"Item", true);
  1432. }
  1433. return Result;
  1434. }
  1435. //---------------------------------------------------------------------------
  1436. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1437. {
  1438. UnicodeString Result;
  1439. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1440. {
  1441. UnicodeString ToolbarStr;
  1442. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1443. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1444. {
  1445. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1446. {
  1447. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1448. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1449. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1450. // and save the changes here only.
  1451. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1452. {
  1453. UnicodeString Name = GetToolbarItemName(Item);
  1454. DebugAssert(Name.Pos(L"TBX") == 0);
  1455. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1456. }
  1457. }
  1458. }
  1459. if (!ToolbarStr.IsEmpty())
  1460. {
  1461. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1462. }
  1463. }
  1464. return Result;
  1465. }
  1466. //---------------------------------------------------------------------------
  1467. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1468. {
  1469. DebugAssert(FProgressForm == NULL);
  1470. bool AllowSkip = HasAvailableTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1471. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1472. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1473. FProgressForm->DeleteLocalToRecycleBin =
  1474. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1475. FProgressForm->DeleteRemoteToRecycleBin =
  1476. HasAvailableTerminal() &&
  1477. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1478. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1479. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1480. LockWindow();
  1481. // Actually, do not know what hides the progress once the operation finishes
  1482. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1483. SetTaskbarListProgressState(TBPF_NORMAL);
  1484. }
  1485. //---------------------------------------------------------------------------
  1486. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1487. {
  1488. UnlockWindow();
  1489. SAFE_DESTROY(FProgressForm);
  1490. SetQueueProgress();
  1491. }
  1492. //---------------------------------------------------------------------------
  1493. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1494. TFileOperationProgressType & ProgressData)
  1495. {
  1496. // Download to temporary local directory
  1497. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1498. {
  1499. bool Continue = true;
  1500. FPendingTempSpaceWarn = false;
  1501. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1502. if (!Continue)
  1503. {
  1504. Abort();
  1505. }
  1506. }
  1507. // operation is being executed and we still didn't show up progress form
  1508. if (ProgressData.InProgress && !FProgressForm)
  1509. {
  1510. CreateProgressForm(NULL);
  1511. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1512. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1513. }
  1514. // operation is finished (or terminated), so we hide progress form
  1515. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1516. {
  1517. DestroyProgressForm();
  1518. if (ProgressData.Operation == foCalculateSize)
  1519. {
  1520. // When calculating size before transfer, the abort caused by
  1521. // cancel flag set due to "MoveToQueue" below,
  1522. // is not propagated back to us in ExecuteFileOperation,
  1523. // as it is silently swallowed.
  1524. // So we explicitly (re)throw it here.
  1525. if (FMoveToQueue)
  1526. {
  1527. Abort();
  1528. }
  1529. }
  1530. else
  1531. {
  1532. if ((ProgressData.Cancel == csContinue) &&
  1533. !FAutoOperation)
  1534. {
  1535. OperationComplete(ProgressData.StartTime);
  1536. }
  1537. }
  1538. }
  1539. if (FProgressForm &&
  1540. // Can happen only during synchronization, when ending one of the operations
  1541. ProgressData.InProgress)
  1542. {
  1543. FProgressForm->SetProgressData(ProgressData);
  1544. DebugAssert(ProgressData.InProgress);
  1545. SetTaskbarListProgressValue(&ProgressData);
  1546. if (FProgressForm->Cancel > csContinue)
  1547. {
  1548. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1549. if (FProgressForm->Cancel == csCancelFile)
  1550. {
  1551. FProgressForm->ClearCancel();
  1552. }
  1553. // cancel cancels even the move
  1554. FMoveToQueue = false;
  1555. }
  1556. else if (FProgressForm->MoveToQueue)
  1557. {
  1558. FMoveToQueue = true;
  1559. ProgressData.SetCancelAtLeast(csCancel);
  1560. }
  1561. if ((FTransferResumeList != NULL) &&
  1562. ProgressData.InProgress &&
  1563. ProgressData.IsTransfer() &&
  1564. !ProgressData.FullFileName.IsEmpty())
  1565. {
  1566. if ((FTransferResumeList->Count == 0) ||
  1567. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1568. {
  1569. // note that we do not recognize directories from files here
  1570. FTransferResumeList->Add(ProgressData.FullFileName);
  1571. }
  1572. }
  1573. }
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1577. const TDateTime & StartTime)
  1578. {
  1579. if (GUIConfiguration->BeepOnFinish &&
  1580. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1581. {
  1582. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1583. DWORD Sound;
  1584. if (!ExtractFileExt(BeepSound).IsEmpty())
  1585. {
  1586. Sound = SND_FILENAME;
  1587. }
  1588. else
  1589. {
  1590. Sound = SND_ALIAS;
  1591. }
  1592. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1593. }
  1594. }
  1595. //---------------------------------------------------------------------------
  1596. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1597. TFileOperationProgressType & ProgressData)
  1598. {
  1599. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1600. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1601. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1602. FileOperationProgress(ProgressData);
  1603. }
  1604. //---------------------------------------------------------------------------
  1605. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1606. {
  1607. UnicodeString Result;
  1608. if (FProgressForm != NULL)
  1609. {
  1610. Result = FProgressForm->ProgressStr();
  1611. }
  1612. return Result;
  1613. }
  1614. //---------------------------------------------------------------------------
  1615. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1616. bool DragDrop)
  1617. {
  1618. return (!DragDrop && (DropSourceControl == NULL)) ||
  1619. (DropSourceControl == DirView(osOther));
  1620. }
  1621. //---------------------------------------------------------------------------
  1622. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1623. {
  1624. TCustomDirView * ADirView = DirView(Side);
  1625. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1626. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1627. // this can happen when local drive is unplugged in the middle of the operation
  1628. if (Item != NULL)
  1629. {
  1630. if (Unselect)
  1631. {
  1632. Item->Selected = false;
  1633. }
  1634. ADirView->MakeProgressVisible(Item);
  1635. }
  1636. return Item;
  1637. }
  1638. //---------------------------------------------------------------------------
  1639. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1640. TFileOperation Operation, TOperationSide Side,
  1641. bool /*Temp*/, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1642. TOnceDoneOperation & OnceDoneOperation)
  1643. {
  1644. if (!FAutoOperation)
  1645. {
  1646. // no selection on "/upload", form serves only as event handler
  1647. // (it is not displayed)
  1648. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1649. ((Operation == FPrimaryOperation) ||
  1650. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1651. {
  1652. TOperationSide DViewSide;
  1653. if ((FProgressSide != osCurrent) &&
  1654. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1655. {
  1656. // assume the operation is over the focused panel
  1657. DViewSide = FProgressSide;
  1658. }
  1659. else
  1660. {
  1661. DViewSide = Side;
  1662. }
  1663. if (FOnFileOperationFinished != NULL)
  1664. {
  1665. FOnFileOperationFinished(DViewSide, FileName, Success, NotCancelled);
  1666. }
  1667. else
  1668. {
  1669. VisualiseOperationFinished(DViewSide, FileName, Success && NotCancelled);
  1670. }
  1671. }
  1672. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1673. {
  1674. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1675. {
  1676. if (Side == osLocal)
  1677. {
  1678. Configuration->Usage->Inc(L"UploadedFiles");
  1679. }
  1680. else
  1681. {
  1682. Configuration->Usage->Inc(L"DownloadedFiles");
  1683. }
  1684. }
  1685. }
  1686. }
  1687. if (Success && (FSynchronizeController != NULL))
  1688. {
  1689. DebugAssert(!IsSideLocalBrowser(osRemote));
  1690. if (Operation == foCopy)
  1691. {
  1692. DebugAssert(Side == osLocal);
  1693. FSynchronizeController->LogOperation(soUpload, FileName);
  1694. }
  1695. else if (Operation == foDelete)
  1696. {
  1697. DebugAssert(Side == osRemote);
  1698. FSynchronizeController->LogOperation(soDelete, FileName);
  1699. }
  1700. }
  1701. if (FProgressForm)
  1702. {
  1703. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1704. }
  1705. }
  1706. //---------------------------------------------------------------------------
  1707. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1708. TFileOperation Operation, TOperationSide Side,
  1709. bool Temp, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1710. TOnceDoneOperation & OnceDoneOperation)
  1711. {
  1712. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1713. DoOperationFinished(Operation, Side, Temp, FileName, Success, NotCancelled, OnceDoneOperation);
  1714. }
  1715. //---------------------------------------------------------------------------
  1716. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1717. {
  1718. return false;
  1719. }
  1720. //---------------------------------------------------------------------------
  1721. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1722. {
  1723. return false;
  1724. }
  1725. //---------------------------------------------------------------------------
  1726. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1727. {
  1728. return false;
  1729. }
  1730. //---------------------------------------------------------------------------
  1731. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1732. {
  1733. return NULL;
  1734. }
  1735. //---------------------------------------------------------------------------
  1736. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1737. {
  1738. DebugAssert(GetSide(Side) == osRemote);
  1739. DebugUsedParam(Side);
  1740. return RemoteDirView;
  1741. }
  1742. //---------------------------------------------------------------------------
  1743. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1744. {
  1745. DebugAssert(GetSide(Side) == osRemote);
  1746. DebugUsedParam(Side);
  1747. return RemoteDriveView;
  1748. }
  1749. //---------------------------------------------------------------------------
  1750. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1751. {
  1752. DebugAssert(GetSide(Side) == osRemote);
  1753. DebugUsedParam(Side);
  1754. return HasAvailableTerminal();
  1755. }
  1756. //---------------------------------------------------------------------------
  1757. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1758. TOperationSide Side, int FilesOnly)
  1759. {
  1760. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1761. }
  1762. //---------------------------------------------------------------------------
  1763. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1764. TOperationSide Side, int FilesOnly)
  1765. {
  1766. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1767. }
  1768. //---------------------------------------------------------------------------
  1769. struct THistoryItemData
  1770. {
  1771. short int Side;
  1772. short int Index;
  1773. };
  1774. //---------------------------------------------------------------------------
  1775. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1776. {
  1777. DirView(Side)->HistoryGo(Index);
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1781. {
  1782. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1783. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1784. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1785. }
  1786. //---------------------------------------------------------------------------
  1787. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1788. bool Back)
  1789. {
  1790. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1791. {
  1792. TCustomDirView * DView = DirView(Side);
  1793. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1794. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1795. if (ICount > 10)
  1796. {
  1797. ICount = 10;
  1798. }
  1799. Menu->Items->Clear();
  1800. THistoryItemData Data;
  1801. Data.Side = Side;
  1802. for (short int i = 1; i <= ICount; i++)
  1803. {
  1804. TTBCustomItem * Item = new TTBXItem(Menu);
  1805. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1806. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1807. Item->Hint = DView->HistoryPath[Data.Index];
  1808. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1809. Item->Tag = *reinterpret_cast<int*>(&Data);
  1810. Item->OnClick = HistoryItemClick;
  1811. Menu->Items->Add(Item);
  1812. }
  1813. }
  1814. }
  1815. //---------------------------------------------------------------------------
  1816. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1817. TOperationSide Side, bool Back)
  1818. {
  1819. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1820. {
  1821. // workaround
  1822. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1823. // operator new allocates memory in Pascal code, but calls inline
  1824. // constructor in C++, leading in problems, the function does
  1825. // both in Pascal code
  1826. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1827. UpdateHistoryMenu(Side, Back);
  1828. }
  1829. return FHistoryMenu[Side == osLocal][Back];
  1830. }
  1831. //---------------------------------------------------------------------------
  1832. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1833. TCustomDirView *Sender)
  1834. {
  1835. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1836. UpdateHistoryMenu(Side, true);
  1837. UpdateHistoryMenu(Side, false);
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1841. {
  1842. // remote custom commands can be executed only if the server supports shell commands
  1843. // or have secondary shell
  1844. return HasAvailableTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1845. }
  1846. //---------------------------------------------------------------------------
  1847. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1848. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1849. {
  1850. // -1 = hidden, 0 = disabled, 1 = enabled
  1851. int Result;
  1852. TFileCustomCommand RemoteCustomCommand;
  1853. TLocalCustomCommand LocalCustomCommand;
  1854. TFileCustomCommand * NonInteractiveCustomCommand =
  1855. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1856. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1857. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1858. if (FLAGCLEAR(Command.Params, ccLocal))
  1859. {
  1860. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1861. // custom command that does not operate with files can be executed anytime ...
  1862. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1863. {
  1864. // ... but do not show such command in remote file menu
  1865. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1866. {
  1867. Result = AllowedState;
  1868. }
  1869. else
  1870. {
  1871. Result = -1;
  1872. }
  1873. }
  1874. else
  1875. {
  1876. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1877. {
  1878. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1879. }
  1880. else
  1881. {
  1882. Result = -1;
  1883. }
  1884. }
  1885. }
  1886. else
  1887. {
  1888. // custom command that does not operate with files can be executed anytime
  1889. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1890. {
  1891. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1892. }
  1893. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1894. {
  1895. if ((ListType == ccltAll) || (ListType == ccltFile))
  1896. {
  1897. // special case is "diff"-style command that can be executed over any side,
  1898. // if we have both sides
  1899. Result =
  1900. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1901. // directly (instead of EnableSelectedOperation) to pass
  1902. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1903. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1904. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1905. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1906. }
  1907. else if (ListType == ccltBoth)
  1908. {
  1909. DebugAssert(!IsLocalBrowserMode());
  1910. Result = 1;
  1911. }
  1912. else
  1913. {
  1914. Result = -1;
  1915. }
  1916. }
  1917. else
  1918. {
  1919. if ((ListType == ccltAll) ||
  1920. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1921. {
  1922. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1923. }
  1924. else
  1925. {
  1926. Result = -1;
  1927. }
  1928. }
  1929. if ((Result > 0) &&
  1930. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1931. !HasAvailableTerminal())
  1932. {
  1933. Result = 0;
  1934. }
  1935. }
  1936. return Result;
  1937. }
  1938. //---------------------------------------------------------------------------
  1939. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1940. TStrings * FileList, const TCustomCommandType & ACommand,
  1941. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1942. {
  1943. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1944. {
  1945. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1946. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1947. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1948. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1949. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1950. bool Capture =
  1951. FLAGSET(ACommand.Params, ccShowResults) ||
  1952. FLAGSET(ACommand.Params, ccCopyResults) ||
  1953. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1954. TCaptureOutputEvent OutputEvent = NULL;
  1955. DebugAssert(FCapturedLog == NULL);
  1956. if (Capture)
  1957. {
  1958. FCapturedLog = new TStringList();
  1959. OutputEvent = TerminalCaptureLog;
  1960. }
  1961. try
  1962. {
  1963. if (!RemoteCustomCommand.IsFileCommand(Command))
  1964. {
  1965. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1966. OutputEvent);
  1967. }
  1968. else
  1969. {
  1970. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1971. }
  1972. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1973. {
  1974. if (FLAGSET(ACommand.Params, ccCopyResults))
  1975. {
  1976. CopyToClipboard(FCapturedLog);
  1977. }
  1978. if (FLAGSET(ACommand.Params, ccShowResults))
  1979. {
  1980. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1981. }
  1982. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1983. {
  1984. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1985. }
  1986. }
  1987. }
  1988. __finally
  1989. {
  1990. SAFE_DESTROY(FCapturedLog);
  1991. }
  1992. }
  1993. }
  1994. //---------------------------------------------------------------------------
  1995. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1996. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1997. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1998. {
  1999. DebugAssert(!IsLocalBrowserMode());
  2000. TStrings * LocalFileList = NULL;
  2001. TStrings * RemoteFileList = NULL;
  2002. TStrings * RemoteFileListFull = NULL;
  2003. try
  2004. {
  2005. if (LocalFileCommand)
  2006. {
  2007. if (ALocalFileList == NULL)
  2008. {
  2009. DebugAssert(HasDirView[osLocal]);
  2010. // Cannot have focus on both panels, so we have to call AnyFileSelected
  2011. // directly (instead of EnableSelectedOperation) to pass
  2012. // false to FocusedFileOnlyWhenFocused
  2013. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  2014. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  2015. }
  2016. else
  2017. {
  2018. LocalFileList = ALocalFileList;
  2019. }
  2020. if (FileListCommand)
  2021. {
  2022. if (LocalFileList->Count != 1)
  2023. {
  2024. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2025. }
  2026. }
  2027. else
  2028. {
  2029. if ((LocalFileList->Count != 1) &&
  2030. (FileList->Count != 1) &&
  2031. (LocalFileList->Count != FileList->Count))
  2032. {
  2033. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2034. }
  2035. }
  2036. }
  2037. UnicodeString RootTempDir;
  2038. UnicodeString TempDir;
  2039. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2040. if (!RemoteFiles)
  2041. {
  2042. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, true, true);
  2043. DebugAssert(RootTempDir == TempDir);
  2044. }
  2045. try
  2046. {
  2047. TDateTimes RemoteFileTimes;
  2048. if (RemoteFiles)
  2049. {
  2050. RemoteFileList = FileList;
  2051. }
  2052. else
  2053. {
  2054. RemoteFileList = new TStringList();
  2055. TMakeLocalFileListParams MakeFileListParam;
  2056. MakeFileListParam.FileList = RemoteFileList;
  2057. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2058. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2059. MakeFileListParam.Recursive =
  2060. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2061. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2062. if (!MakeFileListParam.Recursive)
  2063. {
  2064. RemoteFileTimes.clear();
  2065. RemoteFileListFull = new TStringList();
  2066. MakeFileListParam.FileList = RemoteFileListFull;
  2067. MakeFileListParam.Recursive = true;
  2068. MakeFileListParam.IncludeDirs = false;
  2069. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2070. }
  2071. else
  2072. {
  2073. RemoteFileListFull = RemoteFileList;
  2074. }
  2075. }
  2076. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2077. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2078. if (!NonBlocking)
  2079. {
  2080. int Count;
  2081. if (FileListCommand)
  2082. {
  2083. Count = 1;
  2084. }
  2085. else if (LocalFileCommand)
  2086. {
  2087. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2088. }
  2089. else
  2090. {
  2091. Count = RemoteFileList->Count;
  2092. }
  2093. Progress.Start(foCustomCommand, osRemote, Count);
  2094. DebugAssert(FProgressForm != NULL);
  2095. FProgressForm->ReadOnly = true;
  2096. }
  2097. try
  2098. {
  2099. if (FileListCommand)
  2100. {
  2101. UnicodeString LocalFile;
  2102. // MakeFileList does not delimit filenames
  2103. UnicodeString FileList = MakeFileList(RemoteFileList);
  2104. if (LocalFileCommand)
  2105. {
  2106. DebugAssert(LocalFileList->Count == 1);
  2107. LocalFile = LocalFileList->Strings[0];
  2108. }
  2109. TLocalCustomCommand CustomCommand(Data,
  2110. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2111. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2112. if (NonBlocking)
  2113. {
  2114. DebugAssert(!POutput);
  2115. ExecuteShellChecked(ShellCommand);
  2116. }
  2117. else
  2118. {
  2119. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2120. }
  2121. }
  2122. else if (LocalFileCommand)
  2123. {
  2124. if (LocalFileList->Count == 1)
  2125. {
  2126. UnicodeString LocalFile = LocalFileList->Strings[0];
  2127. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2128. {
  2129. UnicodeString FileName = RemoteFileList->Strings[Index];
  2130. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2131. Progress.SetFile(FileNameForProgress);
  2132. TLocalCustomCommand CustomCommand(Data,
  2133. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2134. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2135. TOnceDoneOperation OnceDoneOperation;
  2136. // Do not unselect anything, as it won't work with two panels anyway
  2137. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2138. }
  2139. }
  2140. else if (RemoteFileList->Count == 1)
  2141. {
  2142. UnicodeString FileName = RemoteFileList->Strings[0];
  2143. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2144. {
  2145. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2146. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2147. Progress.SetFile(LocalFileNameOnly);
  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. else
  2158. {
  2159. if (LocalFileList->Count != RemoteFileList->Count)
  2160. {
  2161. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2162. }
  2163. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2164. {
  2165. UnicodeString FileName = RemoteFileList->Strings[Index];
  2166. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2167. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2168. Progress.SetFile(LocalFileNameOnly); // sic
  2169. TLocalCustomCommand CustomCommand(
  2170. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2171. FileName, LocalFileName, L"");
  2172. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2173. TOnceDoneOperation OnceDoneOperation;
  2174. // Do not unselect anything, as it won't work with two panels anyway
  2175. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2176. }
  2177. }
  2178. }
  2179. else
  2180. {
  2181. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2182. {
  2183. UnicodeString FileName = RemoteFileList->Strings[Index];
  2184. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2185. Progress.SetFile(FileNameForProgress);
  2186. TLocalCustomCommand CustomCommand(Data,
  2187. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2188. FileName, L"", L"");
  2189. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2190. TOnceDoneOperation OnceDoneOperation;
  2191. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2192. }
  2193. }
  2194. }
  2195. __finally
  2196. {
  2197. if (!NonBlocking)
  2198. {
  2199. Progress.Stop();
  2200. }
  2201. }
  2202. DebugAssert(!FAutoOperation);
  2203. if (!RemoteFiles)
  2204. {
  2205. TempDir = IncludeTrailingBackslash(TempDir);
  2206. typedef std::map<UnicodeString, UnicodeString> TTempNameMap;
  2207. TTempNameMap TempNameMap;
  2208. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2209. {
  2210. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2211. TSearchRecSmart SearchRec;
  2212. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2213. FileSearchRec(FileName, SearchRec) &&
  2214. // Skip directories, process only nested files.
  2215. !SearchRec.IsDirectory() &&
  2216. (SearchRec.GetLastWriteTime() != RemoteFileTimes[Index]))
  2217. {
  2218. if (TempNameMap.empty()) // optimization (create map only once it is really needed)
  2219. {
  2220. TCopyParamType CopyParam = TemporaryFileCopyParam();
  2221. for (int Index2 = 0; Index2 < FileList->Count; Index2++)
  2222. {
  2223. UnicodeString RemotePath = FileList->Strings[Index2];
  2224. UnicodeString TempName = GetTempLocalName(RemotePath, CopyParam);
  2225. TempNameMap.insert(std::make_pair(TempName.UpperCase(), RemotePath));
  2226. }
  2227. }
  2228. UnicodeString RelPath = MidStr(FileName, TempDir.Length() + 1);
  2229. UnicodeString TempName = CutToChar(RelPath, L'\\', false).UpperCase();
  2230. TTempNameMap::const_iterator TempNameI = TempNameMap.find(TempName);
  2231. if (DebugAlwaysTrue(TempNameI != TempNameMap.end()))
  2232. {
  2233. TCopyParamType CopyParam = TemporaryFileCopyParam();
  2234. CopyParam.FileMask = L"";
  2235. FAutoOperation = true;
  2236. FMoveToQueue = false;
  2237. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2238. TemporaryFilesList->Add(FileName);
  2239. UnicodeString RemoteDir = UnixExtractFileDir(UnixCombinePathsSmart(TempNameI->second, ToUnixPath(RelPath)));
  2240. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2241. }
  2242. }
  2243. }
  2244. }
  2245. }
  2246. __finally
  2247. {
  2248. FAutoOperation = false;
  2249. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2250. {
  2251. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2252. }
  2253. }
  2254. }
  2255. __finally
  2256. {
  2257. if (RemoteFileList != FileList)
  2258. {
  2259. delete RemoteFileList;
  2260. }
  2261. if (LocalFileList != ALocalFileList)
  2262. {
  2263. delete LocalFileList;
  2264. }
  2265. if (RemoteFileListFull != RemoteFileList)
  2266. {
  2267. delete RemoteFileListFull;
  2268. }
  2269. }
  2270. }
  2271. //---------------------------------------------------------------------------
  2272. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2273. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2274. bool FileListCommand, UnicodeString * POutput)
  2275. {
  2276. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2277. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2278. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2279. {
  2280. UnicodeString FileName = SelectedFileList->Strings[Index];
  2281. if (DirectoryExists(FileName))
  2282. {
  2283. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2284. {
  2285. LocalFileList->Add(FileName);
  2286. }
  2287. if (FLAGSET(ACommand.Params, ccRecursive))
  2288. {
  2289. TMakeLocalFileListParams MakeFileListParam;
  2290. MakeFileListParam.FileList = LocalFileList.get();
  2291. MakeFileListParam.FileTimes = NULL;
  2292. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2293. MakeFileListParam.Recursive = true;
  2294. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2295. }
  2296. }
  2297. else
  2298. {
  2299. LocalFileList->Add(FileName);
  2300. }
  2301. }
  2302. UnicodeString RemotePath;
  2303. if (Terminal != NULL)
  2304. {
  2305. RemotePath = Terminal->CurrentDirectory;
  2306. }
  2307. if (FileListCommand)
  2308. {
  2309. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2310. TLocalCustomCommand CustomCommand(
  2311. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2312. L"", L"", FileList);
  2313. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2314. }
  2315. else
  2316. {
  2317. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2318. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2319. DebugAssert(FProgressForm != NULL);
  2320. FProgressForm->ReadOnly = true;
  2321. try
  2322. {
  2323. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2324. {
  2325. UnicodeString FileName = LocalFileList->Strings[Index];
  2326. Progress.SetFile(FileName);
  2327. TLocalCustomCommand CustomCommand(
  2328. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2329. FileName, L"", L"");
  2330. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2331. TOnceDoneOperation OnceDoneOperation;
  2332. Progress.Finish(FileName, true, OnceDoneOperation);
  2333. }
  2334. }
  2335. __finally
  2336. {
  2337. Progress.Stop();
  2338. }
  2339. }
  2340. }
  2341. //---------------------------------------------------------------------------
  2342. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2343. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2344. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2345. {
  2346. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2347. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2348. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2349. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2350. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2351. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2352. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2353. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2354. std::unique_ptr<UnicodeString> POutput;
  2355. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2356. FLAGSET(ACommand.Params, ccCopyResults))
  2357. {
  2358. POutput.reset(new UnicodeString());
  2359. }
  2360. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  2361. if (!LocalCustomCommand.IsFileCommand(Command))
  2362. {
  2363. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2364. }
  2365. // remote files?
  2366. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2367. {
  2368. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2369. }
  2370. // local files
  2371. else
  2372. {
  2373. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2374. }
  2375. if (POutput.get() != NULL)
  2376. {
  2377. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2378. int P = POutput->Pos(sLineBreak);
  2379. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2380. {
  2381. POutput->SetLength(P - 1);
  2382. }
  2383. // Copy even empty output to clipboard
  2384. if (FLAGSET(ACommand.Params, ccCopyResults))
  2385. {
  2386. CopyToClipboard(*POutput);
  2387. }
  2388. // But do not show an empty message box.
  2389. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2390. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2391. !POutput->IsEmpty())
  2392. {
  2393. TClipboardHandler ClipboardHandler;
  2394. ClipboardHandler.Text = *POutput;
  2395. TMessageParams Params;
  2396. TQueryButtonAlias Aliases[1];
  2397. Aliases[0].Button = qaRetry;
  2398. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2399. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2400. Params.Aliases = Aliases;
  2401. Params.AliasesCount = LENOF(Aliases);
  2402. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2403. }
  2404. }
  2405. }
  2406. //---------------------------------------------------------------------------
  2407. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2408. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2409. {
  2410. TCustomCommandData Data;
  2411. UnicodeString Site;
  2412. UnicodeString RemotePath;
  2413. if (HasAvailableTerminal())
  2414. {
  2415. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2416. Data = TCustomCommandData(SessionData.get());
  2417. Site = Terminal->SessionData->SessionKey;
  2418. RemotePath = Terminal->CurrentDirectory;
  2419. }
  2420. UnicodeString HelpKeyword = ACommand.HomePage;
  2421. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2422. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2423. {
  2424. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2425. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2426. {
  2427. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2428. }
  2429. else
  2430. {
  2431. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2432. }
  2433. if (!DoCustomCommandOptionsDialog(
  2434. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2435. {
  2436. Abort();
  2437. }
  2438. }
  2439. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2440. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2441. {
  2442. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2443. }
  2444. else
  2445. {
  2446. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2447. }
  2448. }
  2449. //---------------------------------------------------------------------------
  2450. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2451. const TCustomCommandType & Command)
  2452. {
  2453. DebugAssert(FCustomCommandLocalFileList != NULL);
  2454. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2455. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2456. TStrings * LocalFileList = new TStringList();
  2457. TStrings * RemoteFileList = new TStringList();
  2458. try
  2459. {
  2460. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2461. {
  2462. LocalFileList->Clear();
  2463. LocalFileList->AddObject(
  2464. FCustomCommandLocalFileList->Strings[Index],
  2465. FCustomCommandLocalFileList->Objects[Index]);
  2466. RemoteFileList->Clear();
  2467. RemoteFileList->AddObject(
  2468. FCustomCommandRemoteFileList->Strings[Index],
  2469. FCustomCommandRemoteFileList->Objects[Index]);
  2470. CustomCommand(RemoteFileList, Command, LocalFileList);
  2471. }
  2472. }
  2473. __finally
  2474. {
  2475. delete LocalFileList;
  2476. delete RemoteFileList;
  2477. }
  2478. }
  2479. //---------------------------------------------------------------------------
  2480. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2481. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2482. {
  2483. delete FCustomCommandLocalFileList;
  2484. delete FCustomCommandRemoteFileList;
  2485. // takeover ownership,
  2486. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2487. FCustomCommandLocalFileList = LocalFileList;
  2488. FCustomCommandRemoteFileList = RemoteFileList;
  2489. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2490. if (Button != NULL)
  2491. {
  2492. FCustomCommandMenu->Items->Clear();
  2493. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2494. MenuPopup(FCustomCommandMenu, Button);
  2495. }
  2496. else
  2497. {
  2498. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2499. }
  2500. }
  2501. //---------------------------------------------------------------------------
  2502. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2503. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2504. {
  2505. DebugAssert(FCapturedLog != NULL);
  2506. if ((OutputType == cotOutput) || (OutputType == cotError))
  2507. {
  2508. FCapturedLog->Add(AddedLine);
  2509. }
  2510. }
  2511. //---------------------------------------------------------------------------
  2512. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2513. TOperationSide Side)
  2514. {
  2515. return
  2516. (Side == osOther) &&
  2517. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2518. }
  2519. //---------------------------------------------------------------------------
  2520. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2521. TOperationSide Side, TTBXCustomItem * Item,
  2522. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2523. {
  2524. TCustomDirView * DView = DirView(Side);
  2525. bool IsDefault = false;
  2526. if (DView->ItemFocused != NULL)
  2527. {
  2528. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2529. TResolvedDoubleClickAction DefaultAction =
  2530. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2531. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2532. }
  2533. TTBItemOptions O = Item->Options;
  2534. if (IsDefault)
  2535. {
  2536. Item->Options = O << tboDefault;
  2537. }
  2538. else
  2539. {
  2540. Item->Options = O >> tboDefault;
  2541. }
  2542. }
  2543. //---------------------------------------------------------------------------
  2544. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2545. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2546. {
  2547. TCustomDirView * DView = DirView(Side);
  2548. TListItem * Item = DView->ItemFocused;
  2549. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2550. EnableFocusedOperation[Side])
  2551. {
  2552. TPoint ClientPoint;
  2553. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2554. TPoint(0, 0) : MousePos;
  2555. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2556. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2557. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2558. }
  2559. }
  2560. //---------------------------------------------------------------------------
  2561. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2562. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2563. {
  2564. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2565. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2566. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2567. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2568. Handled = true;
  2569. }
  2570. //---------------------------------------------------------------------------
  2571. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2572. {
  2573. }
  2574. //---------------------------------------------------------------------------
  2575. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2576. {
  2577. DebugAssert(FErrorList == NULL);
  2578. if (WinConfiguration->ContinueOnError)
  2579. {
  2580. FErrorList = new TStringList();
  2581. Configuration->Usage->Inc(L"ContinuationsOnError");
  2582. }
  2583. NonVisualDataModule->StartBusy();
  2584. }
  2585. //---------------------------------------------------------------------------
  2586. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2587. {
  2588. NonVisualDataModule->EndBusy();
  2589. if (FErrorList)
  2590. {
  2591. HandleErrorList(FErrorList);
  2592. }
  2593. }
  2594. //---------------------------------------------------------------------------
  2595. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2596. const TCopyParamType & CopyParam)
  2597. {
  2598. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2599. {
  2600. Configuration->Usage->Inc(L"FileMaskUses");
  2601. }
  2602. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2603. {
  2604. Configuration->Usage->Inc(L"OperationMaskUses");
  2605. }
  2606. }
  2607. //---------------------------------------------------------------------------
  2608. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2609. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2610. {
  2611. DebugAssert(!IsLocalBrowserMode());
  2612. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2613. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2614. TTransferOperationParam DefaultParam;
  2615. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2616. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2617. switch (Param.Queue)
  2618. {
  2619. case asOn:
  2620. CopyParam.Queue = true;
  2621. break;
  2622. case asOff:
  2623. CopyParam.Queue = false;
  2624. break;
  2625. case asAuto:
  2626. default:
  2627. // keep default
  2628. break;
  2629. }
  2630. bool Result =
  2631. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2632. if (Result)
  2633. {
  2634. DebugAssert(Terminal);
  2635. bool SelectionRestored = false;
  2636. TCustomDirView * DView = NULL;
  2637. if (HasDirView[Side])
  2638. {
  2639. DView = DirView(Side);
  2640. DView->SaveSelection();
  2641. DView->SaveSelectedNames();
  2642. }
  2643. UpdateCopyParamCounters(CopyParam);
  2644. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2645. DebugAssert(FTransferResumeList == NULL);
  2646. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2647. FMoveToQueue = false;
  2648. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2649. try
  2650. {
  2651. TStrings * PermanentFileList;
  2652. std::unique_ptr<TStrings> PermanentFileListOwner;
  2653. try
  2654. {
  2655. if (Side == osLocal)
  2656. {
  2657. PermanentFileList = FileList;
  2658. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2659. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2660. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2661. if (Operation == foMove)
  2662. {
  2663. ReloadLocalDirectory();
  2664. if (DView != NULL)
  2665. {
  2666. DView->RestoreSelection();
  2667. }
  2668. SelectionRestored = true;
  2669. }
  2670. }
  2671. else
  2672. {
  2673. // Clone the file list as it may refer to current directory files,
  2674. // which get destroyed, when the source directory is reloaded after foMove operation.
  2675. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2676. // But for a hotfix, we are not going to do such a big change.
  2677. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2678. PermanentFileList = PermanentFileListOwner.get();
  2679. try
  2680. {
  2681. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2682. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2683. }
  2684. __finally
  2685. {
  2686. if (Operation == foMove)
  2687. {
  2688. if (DView != NULL)
  2689. {
  2690. DView->RestoreSelection();
  2691. }
  2692. SelectionRestored = true;
  2693. }
  2694. ReloadLocalDirectory(Param.TargetDirectory);
  2695. }
  2696. }
  2697. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2698. if (FMoveToQueue)
  2699. {
  2700. Abort();
  2701. }
  2702. }
  2703. catch (EAbort &)
  2704. {
  2705. if (FMoveToQueue)
  2706. {
  2707. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2708. DebugAssert(CopyParam.TransferSkipList == NULL);
  2709. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2710. if (TransferResumeList->Count > 0)
  2711. {
  2712. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2713. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2714. }
  2715. CopyParam.TransferSkipList = TransferResumeList.release();
  2716. // not really needed, just to keep it consistent with TransferResumeList
  2717. FTransferResumeList = NULL;
  2718. FMoveToQueue = false;
  2719. Configuration->Usage->Inc("MovesToBackground");
  2720. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2721. ClearTransferSourceSelection(Direction);
  2722. }
  2723. throw;
  2724. }
  2725. }
  2726. __finally
  2727. {
  2728. if (!SelectionRestored && (DView != NULL))
  2729. {
  2730. DView->DiscardSavedSelection();
  2731. }
  2732. FTransferResumeList = NULL;
  2733. }
  2734. }
  2735. return Result;
  2736. }
  2737. //---------------------------------------------------------------------------
  2738. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2739. TOperationSide Side, TStrings * FileList, void * Param)
  2740. {
  2741. DebugAssert(FileList->Count);
  2742. // We deliberately do not toggle alternative flag (Param), but use OR,
  2743. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2744. // shortcut of CurrentDeleteAlternativeAction
  2745. bool Alternative =
  2746. bool(Param) || UseAlternativeFunction();
  2747. bool Recycle;
  2748. if (IsSideLocalBrowser(Side))
  2749. {
  2750. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2751. }
  2752. else
  2753. {
  2754. Recycle =
  2755. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2756. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2757. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2758. }
  2759. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2760. if (!Result)
  2761. {
  2762. UnicodeString Query;
  2763. if (FileList->Count == 1)
  2764. {
  2765. if (IsSideLocalBrowser(Side))
  2766. {
  2767. Query = ExtractFileName(FileList->Strings[0]);
  2768. }
  2769. else
  2770. {
  2771. Query = UnixExtractFileName(FileList->Strings[0]);
  2772. }
  2773. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2774. }
  2775. else
  2776. {
  2777. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2778. }
  2779. TMessageParams Params(mpNeverAskAgainCheck);
  2780. Params.ImageName = L"Delete file";
  2781. unsigned int Answer =
  2782. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2783. if (Answer == qaNeverAskAgain)
  2784. {
  2785. Result = true;
  2786. if (Recycle)
  2787. {
  2788. WinConfiguration->ConfirmRecycling = false;
  2789. }
  2790. else
  2791. {
  2792. WinConfiguration->ConfirmDeleting = false;
  2793. }
  2794. }
  2795. else
  2796. {
  2797. Result = (Answer == qaOK);
  2798. }
  2799. }
  2800. if (Result)
  2801. {
  2802. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2803. }
  2804. return Result;
  2805. }
  2806. //---------------------------------------------------------------------------
  2807. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2808. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2809. {
  2810. TAutoBatch AutoBatch(this);
  2811. bool Result;
  2812. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2813. {
  2814. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2815. }
  2816. else if (Operation == foRename)
  2817. {
  2818. DebugAssert(DirView(Side)->ItemFocused);
  2819. DirView(Side)->ItemFocused->EditCaption();
  2820. Result = true;
  2821. }
  2822. else if (Operation == foDelete)
  2823. {
  2824. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2825. }
  2826. else if (Operation == foSetProperties)
  2827. {
  2828. DirView(osRemote)->SaveSelectedNames();
  2829. Result = SetProperties(Side, FileList);
  2830. }
  2831. else if (Operation == foCustomCommand)
  2832. {
  2833. DebugAssert(Param);
  2834. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2835. DirView(osRemote)->SaveSelectedNames();
  2836. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2837. CustomCommand(FileList, *Command, NULL);
  2838. Result = true;
  2839. }
  2840. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2841. {
  2842. DebugAssert(!IsSideLocalBrowser(Side));
  2843. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2844. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2845. }
  2846. else if (Operation == foLock)
  2847. {
  2848. DebugAssert(!IsSideLocalBrowser(Side));
  2849. LockFiles(FileList, true);
  2850. Result = true;
  2851. }
  2852. else if (Operation == foUnlock)
  2853. {
  2854. DebugAssert(!IsSideLocalBrowser(Side));
  2855. LockFiles(FileList, false);
  2856. Result = true;
  2857. }
  2858. else
  2859. {
  2860. DebugFail();
  2861. }
  2862. return Result;
  2863. }
  2864. //---------------------------------------------------------------------------
  2865. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2866. {
  2867. if (Side == osCurrent)
  2868. {
  2869. Side = FCurrentSide;
  2870. }
  2871. return Side;
  2872. }
  2873. //---------------------------------------------------------------------------
  2874. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2875. {
  2876. TOperationSide Result;
  2877. switch (GetSide(Side))
  2878. {
  2879. case osLocal:
  2880. Result = osOther;
  2881. break;
  2882. case osOther:
  2883. Result = osLocal;
  2884. break;
  2885. default:
  2886. DebugFail();
  2887. Abort();
  2888. }
  2889. return Result;
  2890. }
  2891. //---------------------------------------------------------------------------
  2892. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2893. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2894. {
  2895. Side = GetSide(Side);
  2896. bool FullPath = IsSideLocalBrowser(Side);
  2897. TCustomDirView * ADirView = DirView(Side);
  2898. std::unique_ptr<TStringList> FileList(new TStringList());
  2899. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2900. bool ReloadProperties =
  2901. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2902. DebugAlwaysTrue(HasAvailableTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2903. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2904. if (Result && ReloadProperties)
  2905. {
  2906. std::unique_ptr<TStringList> FileList2(new TStringList());
  2907. FileList->CaseSensitive = true;
  2908. FileList->Sort();
  2909. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2910. {
  2911. TListItem * Item = ADirView->Items->Item[Index];
  2912. UnicodeString FileName = ADirView->ItemFileName(Item);
  2913. int Index2;
  2914. if (FileList->Find(FileName, Index2))
  2915. {
  2916. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2917. }
  2918. }
  2919. LoadFilesProperties(FileList2.get());
  2920. }
  2921. return Result;
  2922. }
  2923. //---------------------------------------------------------------------------
  2924. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2925. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2926. bool NoConfirmation, void * Param)
  2927. {
  2928. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2929. {
  2930. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2931. {
  2932. DebugAssert(!IsLocalBrowserMode());
  2933. if (GetSide(Side) == osLocal)
  2934. {
  2935. Configuration->Usage->Inc(L"UploadsCommand");
  2936. }
  2937. else
  2938. {
  2939. Configuration->Usage->Inc(L"DownloadsCommand");
  2940. }
  2941. }
  2942. }
  2943. }
  2944. //---------------------------------------------------------------------------
  2945. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2946. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2947. {
  2948. TTransferOperationParam Param;
  2949. if ((WinConfiguration->Interface != ifCommander) ||
  2950. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2951. {
  2952. Flags &= ~cocShortCutHint;
  2953. }
  2954. TCustomDirView * DView = DirView(Side);
  2955. Param.Options =
  2956. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2957. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2958. if (FLAGSET(Flags, cocQueue))
  2959. {
  2960. Param.Queue = asOn;
  2961. }
  2962. else if (FLAGSET(Flags, cocNonQueue))
  2963. {
  2964. Param.Queue = asOff;
  2965. }
  2966. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2967. }
  2968. //---------------------------------------------------------------------------
  2969. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2970. {
  2971. int Count = ErrorList->Count;
  2972. try
  2973. {
  2974. if (ErrorList->Count)
  2975. {
  2976. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2977. if (MessageDialog(Message, qtError,
  2978. qaOK | qaCancel, HELP_NONE) == qaOK)
  2979. {
  2980. unsigned int Answer;
  2981. int Index = 0;
  2982. do
  2983. {
  2984. DebugAssert(Index >= 0 && Index < Count);
  2985. TQueryButtonAlias Aliases[2];
  2986. Aliases[0].Button = qaYes;
  2987. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2988. Aliases[1].Button = qaNo;
  2989. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2990. TMessageParams Params;
  2991. Params.Aliases = Aliases;
  2992. Params.AliasesCount = LENOF(Aliases);
  2993. int No = Index + 1;
  2994. UnicodeString Message = ErrorList->Strings[Index];
  2995. UnicodeString AMainInstructions;
  2996. UnicodeString Details;
  2997. if (ExtractMainInstructions(Message, AMainInstructions))
  2998. {
  2999. Details = Message;
  3000. Message = AMainInstructions;
  3001. }
  3002. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  3003. Answer = MoreMessageDialog(
  3004. Message,
  3005. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  3006. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  3007. qaOK, HELP_NONE, &Params);
  3008. if (Answer == qaNo)
  3009. {
  3010. Index++;
  3011. }
  3012. if (Answer == qaYes)
  3013. {
  3014. Index--;
  3015. }
  3016. }
  3017. while (Answer != qaOK);
  3018. }
  3019. }
  3020. }
  3021. __finally
  3022. {
  3023. TStrings * List = ErrorList;
  3024. ErrorList = NULL;
  3025. for (int i = 0; i < Count; i++)
  3026. {
  3027. delete List->Objects[i];
  3028. }
  3029. delete List;
  3030. }
  3031. }
  3032. //---------------------------------------------------------------------------
  3033. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3034. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3035. {
  3036. // needed for checking filemasks, as there's no directory object
  3037. // associated with the file object
  3038. File->FullFileName = FullFileName;
  3039. TFileMasks::TParams MaskParams;
  3040. MaskParams.Size = File->Size;
  3041. MaskParams.Modification = File->Modification;
  3042. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3043. }
  3044. //---------------------------------------------------------------------------
  3045. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3046. {
  3047. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3048. Side = GetSide(Side);
  3049. TCustomDirView * DView = DirView(Side);
  3050. TListItem * FocusedItem = DView->ItemFocused;
  3051. UnicodeString Name;
  3052. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3053. {
  3054. Name = DView->ItemFileName(FocusedItem);
  3055. }
  3056. else
  3057. {
  3058. Name = LoadStr(NEW_FILE);
  3059. }
  3060. UnicodeString Names = Name;
  3061. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3062. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3063. HELP_EDIT_NEW, History.get(), true, NULL, true, 444))
  3064. {
  3065. while (!Names.IsEmpty())
  3066. {
  3067. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3068. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3069. UnicodeString TargetFileName;
  3070. UnicodeString LocalFileName;
  3071. UnicodeString RootTempDir;
  3072. UnicodeString TempDir;
  3073. UnicodeString RemoteDirectory;
  3074. bool ExistingFile = false;
  3075. if (!IsSideLocalBrowser(Side))
  3076. {
  3077. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3078. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3079. if ((File.get() != NULL) &&
  3080. !File->IsDirectory)
  3081. {
  3082. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3083. ExistingFile = true;
  3084. }
  3085. File.reset(NULL);
  3086. if (!ExistingFile)
  3087. {
  3088. RemoteDirectory = UnixExtractFilePath(Name);
  3089. TemporaryDirectoryForRemoteFiles(
  3090. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3091. TargetFileName = UnixExtractFileName(Name);
  3092. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3093. LocalFileName = TempDir +
  3094. // We probably do not want to trim the VMS version here
  3095. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3096. }
  3097. }
  3098. else
  3099. {
  3100. if (ExtractFilePath(Name).IsEmpty())
  3101. {
  3102. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3103. }
  3104. else
  3105. {
  3106. LocalFileName = ExpandFileName(Name);
  3107. }
  3108. TargetFileName = ExtractFileName(Name);
  3109. }
  3110. if (!ExistingFile)
  3111. {
  3112. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3113. if (NewFile)
  3114. {
  3115. int File = FileCreate(ApiPath(LocalFileName));
  3116. if (File < 0)
  3117. {
  3118. if (!RootTempDir.IsEmpty())
  3119. {
  3120. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3121. }
  3122. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3123. }
  3124. else
  3125. {
  3126. FileClose(File);
  3127. }
  3128. }
  3129. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3130. const TEditorData * ExternalEditor = NULL;
  3131. TFileMasks::TParams MaskParams; // size not known
  3132. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3133. false, MaskParams);
  3134. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3135. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3136. }
  3137. }
  3138. }
  3139. }
  3140. //---------------------------------------------------------------------------
  3141. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3142. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3143. {
  3144. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3145. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3146. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3147. return
  3148. ((ExecuteFileBy == efInternalEditor)) ||
  3149. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3150. }
  3151. //---------------------------------------------------------------------------
  3152. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3153. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3154. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3155. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3156. {
  3157. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3158. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3159. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3160. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3161. Side = GetSide(Side);
  3162. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3163. if (!IsSideLocalBrowser(Side))
  3164. {
  3165. Data->Terminal = Terminal;
  3166. Data->SessionData = CloneCurrentSessionData();
  3167. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3168. Data->RemoteDirectory = RemoteDirectory;
  3169. Data->SessionName = Terminal->SessionData->SessionName;
  3170. Data->LocalRootDirectory = LocalRootDirectory;
  3171. Data->OriginalFileName = OriginalFileName;
  3172. Data->Command = L""; // will be changed later for external editor
  3173. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3174. if (WinConfiguration->EditorCheckNotModified)
  3175. {
  3176. Data->SourceTimestamp = SourceTimestamp;
  3177. }
  3178. }
  3179. if (ExecuteFileBy == efInternalEditor)
  3180. {
  3181. if (!IsSideLocalBrowser(Side))
  3182. {
  3183. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3184. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3185. TForm * Editor;
  3186. try
  3187. {
  3188. Editor =
  3189. ShowEditorForm(
  3190. FileName, this,
  3191. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3192. SaveAllInternalEditors, AnyInternalEditorModified,
  3193. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3194. }
  3195. catch(...)
  3196. {
  3197. if (!LocalRootDirectory.IsEmpty())
  3198. {
  3199. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3200. }
  3201. throw;
  3202. }
  3203. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3204. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3205. }
  3206. else
  3207. {
  3208. DebugAssert(!StandaloneOperation);
  3209. TForm * Editor =
  3210. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3211. SaveAllInternalEditors, AnyInternalEditorModified,
  3212. L"", false, SessionColor, -1, NewFile);
  3213. FLocalEditors->Add(Editor);
  3214. }
  3215. }
  3216. else
  3217. {
  3218. HANDLE Process;
  3219. if (ExecuteFileBy == efExternalEditor)
  3220. {
  3221. UnicodeString Program, Params, Dir;
  3222. Data->Command = ExternalEditor->ExternalEditor;
  3223. ReformatFileNameCommand(Data->Command);
  3224. SplitCommand(Data->Command, Program, Params, Dir);
  3225. Params = ExpandFileNameCommand(Params, FileName);
  3226. Program = ExpandEnvironmentVariables(Program);
  3227. if (!ExecuteShell(Program, Params, Process))
  3228. {
  3229. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3230. }
  3231. }
  3232. else
  3233. {
  3234. DebugAssert(!IsSideLocalBrowser(Side));
  3235. if (!ExecuteShell(FileName, L"", Process))
  3236. {
  3237. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3238. }
  3239. }
  3240. if (IsSideLocalBrowser(Side) ||
  3241. ((ExecuteFileBy == efShell) &&
  3242. !WinConfiguration->Editor.SDIShellEditor) ||
  3243. ((ExecuteFileBy == efExternalEditor) &&
  3244. !ExternalEditor->SDIExternalEditor))
  3245. {
  3246. // no need for handle
  3247. if (Process != NULL)
  3248. {
  3249. DebugCheck(CloseHandle(Process));
  3250. }
  3251. Process = INVALID_HANDLE_VALUE;
  3252. }
  3253. else
  3254. {
  3255. if (Process == NULL)
  3256. {
  3257. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3258. }
  3259. }
  3260. if (!IsSideLocalBrowser(Side))
  3261. {
  3262. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3263. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3264. }
  3265. }
  3266. }
  3267. //---------------------------------------------------------------------------
  3268. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3269. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3270. void * /*Arg*/)
  3271. {
  3272. if (Token != NULL)
  3273. {
  3274. EditorFormFileSave(static_cast<TForm *>(Token));
  3275. }
  3276. }
  3277. //---------------------------------------------------------------------------
  3278. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3279. {
  3280. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3281. {
  3282. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3283. }
  3284. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3285. }
  3286. //---------------------------------------------------------------------------
  3287. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3288. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3289. void * Arg)
  3290. {
  3291. if ((Token != NULL) &&
  3292. IsEditorFormModified(static_cast<TForm *>(Token)))
  3293. {
  3294. *static_cast<bool *>(Arg) = true;
  3295. }
  3296. }
  3297. //---------------------------------------------------------------------------
  3298. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3299. TObject * /*Sender*/, bool & Modified)
  3300. {
  3301. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3302. {
  3303. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3304. {
  3305. Modified = true;
  3306. }
  3307. }
  3308. if (!Modified)
  3309. {
  3310. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3311. }
  3312. }
  3313. //---------------------------------------------------------------------------
  3314. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3315. {
  3316. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3317. }
  3318. //---------------------------------------------------------------------------
  3319. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3320. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3321. UnicodeString & Result, UnicodeString & RootDirectory)
  3322. {
  3323. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3324. {
  3325. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3326. Result = RootDirectory;
  3327. }
  3328. else
  3329. {
  3330. RootDirectory = L"";
  3331. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3332. Result = IncludeTrailingBackslash(Result);
  3333. }
  3334. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3335. {
  3336. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3337. }
  3338. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3339. {
  3340. UnicodeString ARemoteDirectory = RemoteDirectory;
  3341. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3342. {
  3343. ARemoteDirectory.Delete(1, 1);
  3344. }
  3345. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3346. }
  3347. if (!ForceDirectories(ApiPath(Result)))
  3348. {
  3349. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3350. }
  3351. }
  3352. //---------------------------------------------------------------------------
  3353. UnicodeString TCustomScpExplorerForm::GetTempLocalName(const UnicodeString & Path, const TCopyParamType & CopyParam)
  3354. {
  3355. return Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(Path), osRemote, false);
  3356. }
  3357. //---------------------------------------------------------------------------
  3358. void TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3359. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3360. bool AutoOperation, bool SimpleTempDir)
  3361. {
  3362. DebugAssert(!IsLocalBrowserMode());
  3363. TCopyParamType CopyParam = TemporaryFileCopyParam(ForceText);
  3364. if (TempDir.IsEmpty())
  3365. {
  3366. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3367. }
  3368. DebugAssert(!FAutoOperation);
  3369. FAutoOperation = AutoOperation;
  3370. FMoveToQueue = false;
  3371. Terminal->ExceptionOnFail = true;
  3372. try
  3373. {
  3374. try
  3375. {
  3376. // turn off confirmations, as for MDI editors we may possibly download
  3377. // the same file over
  3378. Terminal->CopyToLocal(
  3379. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3380. }
  3381. catch(...)
  3382. {
  3383. if (!RootTempDir.IsEmpty())
  3384. {
  3385. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3386. }
  3387. throw;
  3388. }
  3389. }
  3390. __finally
  3391. {
  3392. FAutoOperation = false;
  3393. Terminal->ExceptionOnFail = false;
  3394. }
  3395. }
  3396. //---------------------------------------------------------------------------
  3397. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3398. {
  3399. // Do not waste time checking for default editor list the next time,
  3400. // or testing if default editor is not notepad.
  3401. bool TryNextTime = false;
  3402. UnicodeString UsageState;
  3403. if (!WinConfiguration->EditorList->IsDefaultList())
  3404. {
  3405. UsageState = "H";
  3406. }
  3407. else
  3408. {
  3409. UnicodeString Executable;
  3410. UnicodeString ExecutableDescription;
  3411. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3412. {
  3413. UnicodeString Message =
  3414. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3415. unsigned int Answer =
  3416. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3417. if (Answer != qaOK)
  3418. {
  3419. UsageState = "R";
  3420. }
  3421. else
  3422. {
  3423. UsageState = "A";
  3424. TEditorData EditorData;
  3425. EditorData.Editor = edExternal;
  3426. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3427. EditorData.ExternalEditorOptionsAutodetect();
  3428. TEditorList EditorList;
  3429. EditorList = *WinConfiguration->EditorList;
  3430. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3431. WinConfiguration->EditorList = &EditorList;
  3432. }
  3433. }
  3434. }
  3435. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3436. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3437. }
  3438. //---------------------------------------------------------------------------
  3439. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3440. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3441. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3442. {
  3443. if (ExecuteFileBy == efDefaultEditor)
  3444. {
  3445. if (!WinConfiguration->OfferedEditorAutoConfig)
  3446. {
  3447. EditorAutoConfig();
  3448. }
  3449. const TEditorPreferences * Editor =
  3450. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3451. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3452. {
  3453. ExecuteFileBy = efInternalEditor;
  3454. ExternalEditor = NULL;
  3455. }
  3456. else if (Editor->Data->Editor == edOpen)
  3457. {
  3458. ExecuteFileBy = efShell;
  3459. ExternalEditor = NULL;
  3460. }
  3461. else
  3462. {
  3463. ExecuteFileBy = efExternalEditor;
  3464. ExternalEditor = Editor->Data;
  3465. }
  3466. }
  3467. }
  3468. //---------------------------------------------------------------------------
  3469. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3470. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3471. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3472. {
  3473. UnicodeString OriginalFileName;
  3474. UnicodeString LocalRootDirectory;
  3475. UnicodeString RemoteDirectory;
  3476. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3477. IsSideLocalBrowser(Side), MaskParams);
  3478. UnicodeString Counter;
  3479. UnicodeString LocalFileName;
  3480. bool Handled = false;
  3481. if (!IsSideLocalBrowser(Side))
  3482. {
  3483. // We need to trim VMS version here, so that we use name without version
  3484. // when uploading back to create a new version of the file
  3485. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3486. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3487. TObject * Token = NULL;
  3488. UnicodeString LocalDirectory;
  3489. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3490. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3491. LocalDirectory))
  3492. {
  3493. if (Token != NULL)
  3494. {
  3495. TForm * Form = dynamic_cast<TForm *>(Token);
  3496. if (Form->WindowState == wsMinimized)
  3497. {
  3498. ShowWindow(Form->Handle, SW_RESTORE);
  3499. }
  3500. else
  3501. {
  3502. Form->SetFocus();
  3503. }
  3504. Handled = true;
  3505. }
  3506. else
  3507. {
  3508. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3509. }
  3510. }
  3511. if (!Handled)
  3512. {
  3513. std::unique_ptr<TStrings> FileList1(new TStringList());
  3514. FileList1->AddObject(FullFileName, Object);
  3515. bool ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3516. TemporarilyDownloadFiles(FileList1.get(), ForceText, LocalRootDirectory, LocalDirectory, true, false);
  3517. LocalFileName = LocalDirectory + GetTempLocalName(FullFileName, TemporaryFileCopyParam(ForceText));
  3518. switch (ExecuteFileBy)
  3519. {
  3520. case efShell:
  3521. Counter = "RemoteFilesExecuted";
  3522. break;
  3523. case efInternalEditor:
  3524. Counter = "RemoteFilesOpenedInInternalEditor";
  3525. break;
  3526. case efExternalEditor:
  3527. Counter = "RemoteFilesOpenedInExternalEditor";
  3528. break;
  3529. default:
  3530. DebugFail();
  3531. }
  3532. }
  3533. }
  3534. else
  3535. {
  3536. LocalFileName = FullFileName;
  3537. OriginalFileName = ExtractFileName(FullFileName);
  3538. switch (ExecuteFileBy)
  3539. {
  3540. case efShell:
  3541. Counter = "LocalFilesExecuted";
  3542. break;
  3543. case efInternalEditor:
  3544. Counter = "LocalFilesOpenedInInternalEditor";
  3545. break;
  3546. case efExternalEditor:
  3547. Counter = "LocalFilesOpenedInExternalEditor";
  3548. break;
  3549. default:
  3550. DebugFail();
  3551. }
  3552. }
  3553. if (!Handled)
  3554. {
  3555. Configuration->Usage->Inc(Counter);
  3556. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3557. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3558. }
  3559. }
  3560. //---------------------------------------------------------------------------
  3561. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3562. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3563. bool AllSelected, bool OnFocused)
  3564. {
  3565. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3566. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3567. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3568. Side = GetSide(Side);
  3569. TCustomDirView * DView = DirView(Side);
  3570. TStrings * FileList =
  3571. AllSelected ?
  3572. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3573. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3574. try
  3575. {
  3576. DebugAssert(AllSelected || (FileList->Count == 1));
  3577. for (int i = 0; i < FileList->Count; i++)
  3578. {
  3579. UnicodeString ListFileName = FileList->Strings[i];
  3580. UnicodeString FileNameOnly =
  3581. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3582. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3583. if (!DView->ItemIsDirectory(Item))
  3584. {
  3585. UnicodeString FullFileName;
  3586. if (!IsSideLocalBrowser(Side))
  3587. {
  3588. FullFileName = DirView(Side)->Path + ListFileName;
  3589. }
  3590. else
  3591. {
  3592. FullFileName = ListFileName;
  3593. }
  3594. TObject * Object = FileList->Objects[i];
  3595. TFileMasks::TParams MaskParams;
  3596. MaskParams.Size = DView->ItemFileSize(Item);
  3597. TDateTimePrecision Precision;
  3598. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3599. std::unique_ptr<TRemoteFile> File;
  3600. if (!IsSideLocalBrowser(Side))
  3601. {
  3602. File.reset(Terminal->TryReadFile(FullFileName));
  3603. if (File.get() != NULL)
  3604. {
  3605. File->FullFileName = FullFileName;
  3606. Object = File.get();
  3607. MaskParams.Size = File->Size;
  3608. MaskParams.Modification = File->Modification;
  3609. }
  3610. }
  3611. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3612. }
  3613. }
  3614. }
  3615. __finally
  3616. {
  3617. delete FileList;
  3618. }
  3619. }
  3620. //---------------------------------------------------------------------------
  3621. TCopyParamType TCustomScpExplorerForm::TemporaryFileCopyParam(bool ForceText)
  3622. {
  3623. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3624. CopyParam.FileNameCase = ncNoChange;
  3625. CopyParam.PreserveRights = false;
  3626. CopyParam.PreserveReadOnly = false;
  3627. CopyParam.ReplaceInvalidChars = true;
  3628. CopyParam.IncludeFileMask = TFileMasks();
  3629. CopyParam.NewerOnly = false;
  3630. CopyParam.FileMask = L"";
  3631. if (ForceText)
  3632. {
  3633. CopyParam.TransferMode = tmAscii;
  3634. }
  3635. return CopyParam;
  3636. }
  3637. //---------------------------------------------------------------------------
  3638. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3639. {
  3640. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3641. }
  3642. //---------------------------------------------------------------------------
  3643. class TEditorUploadQueueItem : public TUploadQueueItem
  3644. {
  3645. public:
  3646. __fastcall TEditorUploadQueueItem(
  3647. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3648. const TCopyParamType * CopyParam, int Params) :
  3649. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, false)
  3650. {
  3651. }
  3652. protected:
  3653. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3654. {
  3655. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3656. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3657. }
  3658. };
  3659. //---------------------------------------------------------------------------
  3660. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3661. {
  3662. if (WinConfiguration->EditorCheckNotModified) // optimization
  3663. {
  3664. UnicodeString RemoteFilePath;
  3665. {
  3666. TGuard Guard(FEditorManager->Section);
  3667. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3668. if (DebugAlwaysTrue(Data != NULL) &&
  3669. EditorCheckNotModified(Data))
  3670. {
  3671. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3672. }
  3673. }
  3674. if (!RemoteFilePath.IsEmpty())
  3675. {
  3676. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3677. if (File.get() != NULL)
  3678. {
  3679. TGuard Guard(FEditorManager->Section);
  3680. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3681. if (DebugAlwaysTrue(Data != NULL))
  3682. {
  3683. Data->SourceTimestamp = File->Modification;
  3684. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3685. }
  3686. }
  3687. }
  3688. }
  3689. }
  3690. //---------------------------------------------------------------------------
  3691. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3692. const UnicodeString & FileName, const TDateTime & Timestamp, TEditedFileData * Data,
  3693. HANDLE UploadCompleteEvent, bool & Retry)
  3694. {
  3695. TTerminalManager * Manager = TTerminalManager::Instance();
  3696. bool IsInavailable = !IsAvailableTerminal(Data->Terminal);
  3697. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3698. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3699. {
  3700. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3701. Retry = true;
  3702. }
  3703. else if (Manager->IsReconnectingTerminal(Data->Terminal))
  3704. {
  3705. AppLog(L"Session is being reconnected, will retry the upload later");
  3706. Retry = true;
  3707. }
  3708. else if (IsInavailable &&
  3709. GUIConfiguration->SessionReopenAutoInactive &&
  3710. (Data->Terminal->NextInactiveReconnect != TDateTime()))
  3711. {
  3712. if (Data->Terminal->LastInactiveSave != Timestamp)
  3713. {
  3714. AppLog(L"Inactive session reconnect is pending, rescheduling it for as soon as possible to retry the upload");
  3715. Data->Terminal->NextInactiveReconnect = Now();
  3716. Data->Terminal->LastInactiveSave = Timestamp;
  3717. }
  3718. else
  3719. {
  3720. AppLog(L"Inactive session reconnect is pending, will retry the upload later");
  3721. }
  3722. Retry = true;
  3723. }
  3724. else if (IsInavailable)
  3725. {
  3726. if (!NonVisualDataModule->Busy)
  3727. {
  3728. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3729. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3730. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3731. if (Data->Terminal == NULL)
  3732. {
  3733. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3734. if (SameSiteTerminal != NULL)
  3735. {
  3736. UnicodeString Message =
  3737. FMTLOAD(EDIT_SESSION_REATTACH,
  3738. (FileNameOnly, Data->SessionName, FileNameOnly));
  3739. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3740. {
  3741. Data->Terminal = SameSiteTerminal;
  3742. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3743. // We might also overwrite session data
  3744. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3745. }
  3746. else
  3747. {
  3748. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3749. Abort();
  3750. }
  3751. }
  3752. }
  3753. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3754. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3755. {
  3756. UnicodeString Message =
  3757. MainInstructions(
  3758. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3759. TMessageParams Params(FLAGMASK(!GUIConfiguration->SessionReopenAutoInactive, mpNeverAskAgainCheck));
  3760. Params.NeverAskAgainTitle = LoadStr(ALWAYS_RECONNECT);
  3761. unsigned int Answer = MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_NONE, &Params);
  3762. if (Answer == qaNeverAskAgain)
  3763. {
  3764. GUIConfiguration->SessionReopenAutoInactive = true;
  3765. Answer = qaOK;
  3766. }
  3767. if (Answer == qaOK)
  3768. {
  3769. if (Terminal->Disconnected)
  3770. {
  3771. Manager->ActiveSession = Terminal;
  3772. ReconnectSession();
  3773. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3774. if (!IsAvailableTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3775. {
  3776. Abort();
  3777. }
  3778. }
  3779. else
  3780. {
  3781. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3782. }
  3783. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3784. }
  3785. else
  3786. {
  3787. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3788. Abort();
  3789. }
  3790. }
  3791. }
  3792. if (!IsAvailableTerminal(Data->Terminal))
  3793. {
  3794. Configuration->Usage->Inc(L"EditInactiveSession");
  3795. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3796. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3797. (ExtractFileName(FileName), Data->SessionName)));
  3798. }
  3799. }
  3800. if (!Retry && EditorCheckNotModified(Data))
  3801. {
  3802. if (NonVisualDataModule->Busy)
  3803. {
  3804. Retry = true;
  3805. }
  3806. else
  3807. {
  3808. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3809. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3810. if (File.get() != NULL)
  3811. {
  3812. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3813. if (File->Modification != Data->SourceTimestamp)
  3814. {
  3815. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3816. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3817. {
  3818. Abort();
  3819. }
  3820. }
  3821. }
  3822. }
  3823. }
  3824. if (!Retry)
  3825. {
  3826. TStrings * FileList = new TStringList();
  3827. try
  3828. {
  3829. FileList->Add(FileName);
  3830. // Consider using the same settings (preset) as when the file was downloaded.
  3831. // More over this does not reflect the actual session that will do the upload.
  3832. TCopyParamType CopyParam = TemporaryFileCopyParam(Data->ForceText);
  3833. // so i do not need to worry if masking algorithm works in all cases
  3834. // ("" means "copy file name", no masking is actually done)
  3835. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3836. {
  3837. CopyParam.FileMask = L"";
  3838. }
  3839. else
  3840. {
  3841. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3842. }
  3843. int Params = cpNoConfirmation | cpTemporary;
  3844. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3845. {
  3846. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3847. TQueueItem * QueueItem =
  3848. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3849. QueueItem->CompleteEvent = UploadCompleteEvent;
  3850. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3851. }
  3852. else
  3853. {
  3854. if (NonVisualDataModule->Busy)
  3855. {
  3856. Retry = true;
  3857. }
  3858. else
  3859. {
  3860. FMoveToQueue = false;
  3861. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3862. SetEvent(UploadCompleteEvent);
  3863. }
  3864. }
  3865. }
  3866. __finally
  3867. {
  3868. delete FileList;
  3869. }
  3870. }
  3871. }
  3872. //---------------------------------------------------------------------------
  3873. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3874. const UnicodeString & FileName, TEditedFileData * Data)
  3875. {
  3876. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3877. DebugAssert(!NonVisualDataModule->Busy);
  3878. if (!IsAvailableTerminal(Data->Terminal))
  3879. {
  3880. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3881. (ExtractFileName(FileName), Data->SessionName)));
  3882. }
  3883. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3884. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3885. NonVisualDataModule->StartBusy();
  3886. try
  3887. {
  3888. std::unique_ptr<TRemoteFile> File;
  3889. UnicodeString RemoteFileName =
  3890. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3891. Terminal->ExceptionOnFail = true;
  3892. try
  3893. {
  3894. File.reset(Terminal->ReadFile(RemoteFileName));
  3895. if (!File->HaveFullFileName)
  3896. {
  3897. File->FullFileName = RemoteFileName;
  3898. }
  3899. }
  3900. __finally
  3901. {
  3902. Terminal->ExceptionOnFail = false;
  3903. }
  3904. std::unique_ptr<TStrings> FileList(new TStringList());
  3905. FileList->AddObject(RemoteFileName, File.get());
  3906. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3907. UnicodeString TempDir = ExtractFilePath(FileName);
  3908. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, false);
  3909. if (EditorCheckNotModified(Data))
  3910. {
  3911. Data->SourceTimestamp = File->Modification;
  3912. }
  3913. }
  3914. __finally
  3915. {
  3916. NonVisualDataModule->EndBusy();
  3917. // it actually may not exist anymore...
  3918. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3919. }
  3920. }
  3921. //---------------------------------------------------------------------------
  3922. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3923. const TEditedFileData * Data, bool & KeepOpen)
  3924. {
  3925. // Command is set for external editors only (not for "shell" open).
  3926. if (!Data->Command.IsEmpty())
  3927. {
  3928. bool AnyFound = false;
  3929. bool AnyMDI = false;
  3930. bool AnyNonMDI = false;
  3931. bool AnyDetect = false;
  3932. TEditorList * EditorList = new TEditorList();
  3933. try
  3934. {
  3935. *EditorList = *WinConfiguration->EditorList;
  3936. for (int i = 0; i < EditorList->Count; i++)
  3937. {
  3938. const TEditorPreferences * Editor = EditorList->Editors[i];
  3939. if ((Editor->Data->Editor == edExternal) &&
  3940. (Editor->Data->ExternalEditor == Data->Command))
  3941. {
  3942. AnyFound = true;
  3943. if (Editor->Data->SDIExternalEditor)
  3944. {
  3945. AnyNonMDI = true;
  3946. if (Editor->Data->DetectMDIExternalEditor)
  3947. {
  3948. AnyDetect = true;
  3949. }
  3950. }
  3951. else
  3952. {
  3953. AnyMDI = true;
  3954. }
  3955. }
  3956. }
  3957. bool EnableMDI = false;
  3958. bool DisableDetect = false;
  3959. if (AnyMDI)
  3960. {
  3961. KeepOpen = true;
  3962. if (AnyNonMDI)
  3963. {
  3964. // there is at least one instance of the editor with MDI support enabled,
  3965. // and one with disabled, enable it for all instances
  3966. EnableMDI = true;
  3967. }
  3968. }
  3969. else if (AnyFound && !AnyDetect)
  3970. {
  3971. // at least once instance found but all have MDI autodetection disabled
  3972. // => close the file (default action)
  3973. }
  3974. else
  3975. {
  3976. // no instance of the editor has MDI support enabled
  3977. TMessageParams Params;
  3978. if (AnyFound)
  3979. {
  3980. // there is at least one instance of the editor
  3981. Params.Params |= mpNeverAskAgainCheck;
  3982. }
  3983. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3984. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3985. switch (Answer)
  3986. {
  3987. case qaNeverAskAgain:
  3988. DisableDetect = true;
  3989. break;
  3990. case qaNo:
  3991. EnableMDI = true;
  3992. KeepOpen = true;
  3993. break;
  3994. }
  3995. }
  3996. if (AnyFound && (EnableMDI || DisableDetect))
  3997. {
  3998. bool Changed = false;
  3999. for (int i = 0; i < EditorList->Count; i++)
  4000. {
  4001. const TEditorPreferences * Editor = EditorList->Editors[i];
  4002. if ((Editor->Data->Editor == edExternal) &&
  4003. (Editor->Data->ExternalEditor == Data->Command) &&
  4004. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  4005. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  4006. {
  4007. Changed = true;
  4008. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  4009. if (EnableMDI)
  4010. {
  4011. UpdatedEditor->GetData()->SDIExternalEditor = false;
  4012. }
  4013. if (DisableDetect)
  4014. {
  4015. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  4016. }
  4017. EditorList->Change(i, UpdatedEditor);
  4018. }
  4019. }
  4020. if (Changed)
  4021. {
  4022. WinConfiguration->EditorList = EditorList;
  4023. }
  4024. }
  4025. }
  4026. __finally
  4027. {
  4028. delete EditorList;
  4029. }
  4030. }
  4031. else
  4032. {
  4033. // "open" case
  4034. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4035. qaOK, HELP_APP_EARLY_CLOSED);
  4036. }
  4037. }
  4038. //---------------------------------------------------------------------------
  4039. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4040. {
  4041. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4042. }
  4043. //---------------------------------------------------------------------------
  4044. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4045. {
  4046. SideEnter(osRemote);
  4047. }
  4048. //---------------------------------------------------------------------------
  4049. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4050. {
  4051. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4052. SideEnter(osRemote);
  4053. }
  4054. //---------------------------------------------------------------------------
  4055. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4056. {
  4057. FCurrentSide = Side;
  4058. if (Visible)
  4059. {
  4060. UpdateControls();
  4061. }
  4062. }
  4063. //---------------------------------------------------------------------------
  4064. void __fastcall TCustomScpExplorerForm::FileDeleted(
  4065. TOperationSide Side, const UnicodeString & FileName, bool Success, bool NotCancelled)
  4066. {
  4067. VisualiseOperationFinished(Side, FileName, Success && NotCancelled);
  4068. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4069. {
  4070. FDeletedFiles->Add(FileName);
  4071. }
  4072. }
  4073. //---------------------------------------------------------------------------
  4074. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4075. TStrings * FileList, bool Alternative)
  4076. {
  4077. TCustomDirView * DView = DirView(Side);
  4078. DView->SaveSelection();
  4079. DView->SaveSelectedNames();
  4080. DebugAssert(!FAlternativeDelete);
  4081. FAlternativeDelete = Alternative;
  4082. try
  4083. {
  4084. int Params = FLAGMASK(Alternative, dfAlternative);
  4085. bool Remote = !IsSideLocalBrowser(Side);
  4086. std::unique_ptr<TStringList> DeletedFiles;
  4087. std::unique_ptr<TStrings> PermanentFileList;
  4088. bool AllowMoveToQueue = (Terminal != NULL);
  4089. if (AllowMoveToQueue)
  4090. {
  4091. DeletedFiles.reset(new TStringList());
  4092. DeletedFiles->CaseSensitive = Remote;
  4093. }
  4094. try
  4095. {
  4096. DebugAssert(FDeletedFiles == NULL);
  4097. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles, DeletedFiles.get());
  4098. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4099. if (AllowMoveToQueue)
  4100. {
  4101. FOnFileOperationFinished = FileDeleted;
  4102. }
  4103. FMoveToQueue = false;
  4104. if (Remote)
  4105. {
  4106. DebugAssert(AllowMoveToQueue);
  4107. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4108. PermanentFileList.reset(TRemoteFileList::CloneStrings(FileList));
  4109. DebugAssert(Terminal != NULL);
  4110. Terminal->DeleteFiles(FileList, Params);
  4111. }
  4112. else
  4113. {
  4114. if (AllowMoveToQueue) // optimization)
  4115. {
  4116. PermanentFileList.reset(CloneStrings(FileList));
  4117. }
  4118. if (IsLocalBrowserMode())
  4119. {
  4120. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4121. }
  4122. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  4123. try
  4124. {
  4125. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, Params);
  4126. }
  4127. __finally
  4128. {
  4129. ReloadLocalDirectory();
  4130. }
  4131. }
  4132. // Probably not needed for deleting, just for consistency with transfer code
  4133. if (FMoveToQueue)
  4134. {
  4135. Abort();
  4136. }
  4137. }
  4138. catch (EAbort &)
  4139. {
  4140. if (FMoveToQueue && DebugAlwaysTrue(AllowMoveToQueue) && DebugAlwaysTrue(Terminal != NULL))
  4141. {
  4142. FMoveToQueue = false;
  4143. DeletedFiles->Sorted = true;
  4144. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4145. {
  4146. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4147. {
  4148. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4149. DebugAssert(Index == 0);
  4150. PermanentFileList->Delete(Index);
  4151. Index--;
  4152. }
  4153. }
  4154. if (Remote)
  4155. {
  4156. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4157. TQueueItem * QueueItem = new TRemoteDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4158. AddQueueItem(Queue, QueueItem, Terminal);
  4159. }
  4160. else
  4161. {
  4162. Configuration->Usage->Inc("MovesToBackgroundDeleteLocal");
  4163. TQueueItem * QueueItem = new TLocalDeleteQueueItem(PermanentFileList.get(), Params);
  4164. AddQueueItem(Queue, QueueItem, Terminal);
  4165. }
  4166. ClearOperationSelection(Side);
  4167. }
  4168. }
  4169. FAlternativeDelete = false;
  4170. }
  4171. catch(...)
  4172. {
  4173. FAlternativeDelete = false;
  4174. DView->DiscardSavedSelection();
  4175. throw;
  4176. }
  4177. DView->RestoreSelection();
  4178. }
  4179. //---------------------------------------------------------------------------
  4180. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4181. {
  4182. DebugAssert(Terminal);
  4183. DebugAssert(!IsLocalBrowserMode());
  4184. RemoteDirView->SaveSelection();
  4185. RemoteDirView->SaveSelectedNames();
  4186. try
  4187. {
  4188. if (Lock)
  4189. {
  4190. Terminal->LockFiles(FileList);
  4191. }
  4192. else
  4193. {
  4194. Terminal->UnlockFiles(FileList);
  4195. }
  4196. }
  4197. catch(...)
  4198. {
  4199. RemoteDirView->DiscardSavedSelection();
  4200. throw;
  4201. }
  4202. RemoteDirView->RestoreSelection();
  4203. }
  4204. //---------------------------------------------------------------------------
  4205. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4206. {
  4207. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4208. bool Result =
  4209. IsAvailableTerminal(ATerminal) &&
  4210. ATerminal->DirectoryExists(Directory);
  4211. return Result;
  4212. }
  4213. //---------------------------------------------------------------------------
  4214. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4215. {
  4216. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4217. return
  4218. !Terminal->IsCapable[fcRemoteCopy] ||
  4219. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4220. }
  4221. //---------------------------------------------------------------------------
  4222. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4223. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4224. bool NoConfirmation, bool Move)
  4225. {
  4226. DebugAssert(Terminal != NULL);
  4227. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4228. DebugAssert(!IsLocalBrowserMode());
  4229. if (Session == NULL)
  4230. {
  4231. Session = Terminal;
  4232. }
  4233. bool TargetConfirmed = false;
  4234. if (Session == Terminal)
  4235. {
  4236. if (RemoteDriveView->DropTarget != NULL)
  4237. {
  4238. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4239. TargetConfirmed = true;
  4240. }
  4241. else if (RemoteDirView->DropTarget != NULL)
  4242. {
  4243. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4244. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4245. TargetConfirmed = true;
  4246. }
  4247. else
  4248. {
  4249. Target = RemoteDirView->Path;
  4250. }
  4251. }
  4252. else
  4253. {
  4254. Target = GetSessionPath(Session, osRemote);
  4255. }
  4256. Target = UnixIncludeTrailingBackslash(Target);
  4257. if (FileList->Count == 1)
  4258. {
  4259. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4260. }
  4261. else
  4262. {
  4263. FileMask = AnyMask;
  4264. }
  4265. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4266. bool Result = true;
  4267. if (!NoConfirmation)
  4268. {
  4269. bool Multi = (FileList->Count > 1);
  4270. if (Move)
  4271. {
  4272. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4273. }
  4274. else
  4275. {
  4276. std::unique_ptr<TStrings> Sessions(new TStringList);
  4277. std::unique_ptr<TStrings> Directories(new TStringList);
  4278. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4279. for (int Index = 0; Index < SessionList->Count; Index++)
  4280. {
  4281. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4282. if (IsAvailableTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4283. {
  4284. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4285. Directories->Add(GetSessionPath(ASession, osRemote));
  4286. }
  4287. }
  4288. bool AnyDirectory = false;
  4289. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4290. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4291. {
  4292. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4293. {
  4294. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4295. }
  4296. }
  4297. TDirectRemoteCopy AllowDirectCopy;
  4298. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4299. {
  4300. DebugAssert(DirectCopy);
  4301. AllowDirectCopy = drcAllow;
  4302. }
  4303. else if (Terminal->IsCapable[fcSecondaryShell])
  4304. {
  4305. DebugAssert(DirectCopy);
  4306. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4307. }
  4308. else
  4309. {
  4310. DebugAssert(!DirectCopy);
  4311. AllowDirectCopy = drcDisallow;
  4312. }
  4313. void * ASession = Session;
  4314. Result = DoRemoteCopyDialog(
  4315. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4316. DoDirectoryExists, TargetConfirmed);
  4317. Session = static_cast<TManagedTerminal *>(ASession);
  4318. }
  4319. }
  4320. return Result;
  4321. }
  4322. //---------------------------------------------------------------------------
  4323. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4324. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4325. {
  4326. DebugAssert(!IsLocalBrowserMode());
  4327. bool DirectCopy;
  4328. UnicodeString Target, FileMask;
  4329. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4330. if (Result)
  4331. {
  4332. if (!Move && !DirectCopy)
  4333. {
  4334. Configuration->Usage->Inc("RemoteCopyTemp");
  4335. UnicodeString RootTempDir;
  4336. UnicodeString TempDir;
  4337. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true);
  4338. TStrings * TemporaryFilesList = new TStringList();
  4339. try
  4340. {
  4341. TMakeLocalFileListParams MakeFileListParam;
  4342. MakeFileListParam.FileList = TemporaryFilesList;
  4343. MakeFileListParam.FileTimes = NULL;
  4344. MakeFileListParam.IncludeDirs = true;
  4345. MakeFileListParam.Recursive = false;
  4346. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4347. TTerminalManager::Instance()->ActiveSession = Session;
  4348. if (TemporaryFilesList->Count > 0)
  4349. {
  4350. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4351. CopyParam.FileMask = FileMask;
  4352. DebugAssert(!FAutoOperation);
  4353. FAutoOperation = true;
  4354. FMoveToQueue = false;
  4355. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4356. }
  4357. }
  4358. __finally
  4359. {
  4360. delete TemporaryFilesList;
  4361. FAutoOperation = false;
  4362. if (!RootTempDir.IsEmpty())
  4363. {
  4364. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4365. }
  4366. }
  4367. }
  4368. else
  4369. {
  4370. RemoteDirView->SaveSelection();
  4371. RemoteDirView->SaveSelectedNames();
  4372. try
  4373. {
  4374. if (Move)
  4375. {
  4376. Configuration->Usage->Inc("RemoteMove");
  4377. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4378. }
  4379. else
  4380. {
  4381. Configuration->Usage->Inc("RemoteCopyDirect");
  4382. DebugAssert(DirectCopy);
  4383. DebugAssert(Session == Terminal);
  4384. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4385. Terminal->CommandSessionOpened ||
  4386. CommandSessionFallback())
  4387. {
  4388. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4389. }
  4390. }
  4391. }
  4392. catch(...)
  4393. {
  4394. RemoteDirView->DiscardSavedSelection();
  4395. throw;
  4396. }
  4397. RemoteDirView->RestoreSelection();
  4398. }
  4399. }
  4400. return Result;
  4401. }
  4402. //---------------------------------------------------------------------------
  4403. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4404. const UnicodeString & Path, TRemoteProperties & Properties)
  4405. {
  4406. DebugAssert(!IsLocalBrowserMode());
  4407. Properties.Valid = Properties.Valid << vpEncrypt;
  4408. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4409. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4410. }
  4411. //---------------------------------------------------------------------------
  4412. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4413. {
  4414. Side = GetSide(Side);
  4415. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4416. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4417. UnicodeString Name = LoadStr(NEW_FOLDER);
  4418. int AllowedChanges =
  4419. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4420. bool SaveSettings = false;
  4421. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4422. {
  4423. TWindowLock Lock(this);
  4424. if (!IsSideLocalBrowser(Side))
  4425. {
  4426. if (SaveSettings)
  4427. {
  4428. GUIConfiguration->NewDirectoryProperties = Properties;
  4429. }
  4430. CreateRemoteDirectory(Name, Properties);
  4431. }
  4432. else
  4433. {
  4434. DirView(Side)->CreateDirectory(Name);
  4435. }
  4436. }
  4437. }
  4438. //---------------------------------------------------------------------------
  4439. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4440. {
  4441. TWindowLock Lock(this);
  4442. DirView(Side)->ExecuteHomeDirectory();
  4443. }
  4444. //---------------------------------------------------------------------------
  4445. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4446. {
  4447. DoOpenDirectoryDialog(odBrowse, Side);
  4448. }
  4449. //---------------------------------------------------------------------------
  4450. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4451. {
  4452. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4453. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4454. bool Result = !Path.IsEmpty();
  4455. if (Result)
  4456. {
  4457. TryOpenDirectory(Side, Path);
  4458. }
  4459. return Result;
  4460. }
  4461. //---------------------------------------------------------------------------
  4462. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4463. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4464. bool & Close)
  4465. {
  4466. // terminal can be already closed (e.g. dropped connection)
  4467. if (Terminal != NULL)
  4468. {
  4469. try
  4470. {
  4471. TCalculateSizeParams Params;
  4472. Params.Stats = &Stats;
  4473. Terminal->CalculateFilesSize(FileList, Size, Params);
  4474. }
  4475. catch(...)
  4476. {
  4477. if (!Terminal->Active)
  4478. {
  4479. Close = true;
  4480. }
  4481. throw;
  4482. }
  4483. }
  4484. }
  4485. //---------------------------------------------------------------------------
  4486. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4487. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4488. bool & Close)
  4489. {
  4490. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4491. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4492. {
  4493. Configuration->Usage->Inc(L"ChecksumCalculated");
  4494. try
  4495. {
  4496. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4497. }
  4498. catch(...)
  4499. {
  4500. if (!Terminal->Active)
  4501. {
  4502. Close = true;
  4503. }
  4504. throw;
  4505. }
  4506. }
  4507. }
  4508. //---------------------------------------------------------------------------
  4509. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4510. {
  4511. if (Terminal->LoadFilesProperties(FileList))
  4512. {
  4513. RemoteDirView->Invalidate();
  4514. }
  4515. }
  4516. //---------------------------------------------------------------------------
  4517. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4518. {
  4519. return
  4520. Terminal->IsCapable[fcCalculatingChecksum] ||
  4521. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4522. }
  4523. //---------------------------------------------------------------------------
  4524. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4525. {
  4526. bool Result;
  4527. if (!IsSideLocalBrowser(Side))
  4528. {
  4529. TRemoteTokenList * GroupList = NULL;
  4530. TRemoteTokenList * UserList = NULL;
  4531. try
  4532. {
  4533. TRemoteProperties CurrentProperties;
  4534. LoadFilesProperties(FileList);
  4535. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4536. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4537. if (CapableGroupChanging || CapableOwnerChanging)
  4538. {
  4539. if (CapableGroupChanging)
  4540. {
  4541. GroupList = Terminal->Groups->Duplicate();
  4542. }
  4543. if (CapableOwnerChanging)
  4544. {
  4545. UserList = Terminal->Users->Duplicate();
  4546. }
  4547. TRemoteDirectory * Files = Terminal->Files;
  4548. int Count = Files->Count;
  4549. if (Count > 100)
  4550. {
  4551. Count = 100;
  4552. }
  4553. for (int Index = 0; Index < Count; Index++)
  4554. {
  4555. TRemoteFile * File = Files->Files[Index];
  4556. if (CapableGroupChanging)
  4557. {
  4558. GroupList->AddUnique(File->Group);
  4559. }
  4560. if (CapableOwnerChanging)
  4561. {
  4562. UserList->AddUnique(File->Owner);
  4563. }
  4564. }
  4565. // if we haven't collected tokens for all files in current directory,
  4566. // make sure we collect them at least for all selected files.
  4567. // (note that so far the files in FileList has to be from current direcotry)
  4568. if (Count < Files->Count)
  4569. {
  4570. for (int Index = 0; Index < FileList->Count; Index++)
  4571. {
  4572. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4573. if (CapableGroupChanging)
  4574. {
  4575. GroupList->AddUnique(File->Group);
  4576. }
  4577. if (CapableOwnerChanging)
  4578. {
  4579. UserList->AddUnique(File->Owner);
  4580. }
  4581. }
  4582. }
  4583. }
  4584. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4585. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4586. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4587. {
  4588. CapableAclChanging = false;
  4589. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4590. }
  4591. int Flags = 0;
  4592. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4593. if (CapableAclChanging) Flags |= cpAcl;
  4594. if (CapableOwnerChanging) Flags |= cpOwner;
  4595. if (CapableGroupChanging) Flags |= cpGroup;
  4596. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4597. if (CanCalculateChecksum())
  4598. {
  4599. CalculateChecksumEvent = CalculateChecksum;
  4600. }
  4601. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4602. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4603. int Options =
  4604. FLAGMASK(Terminal->IsCapable[fcGroupOwnerChangingByID], poUserGroupByID) |
  4605. FLAGMASK(Terminal->IsCapable[fcTags], poTags);
  4606. TRemoteProperties NewProperties = CurrentProperties;
  4607. Result =
  4608. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4609. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags, Options,
  4610. CalculateSize, CalculateChecksumEvent);
  4611. if (Result)
  4612. {
  4613. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4614. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4615. }
  4616. }
  4617. __finally
  4618. {
  4619. delete GroupList;
  4620. delete UserList;
  4621. }
  4622. }
  4623. else
  4624. {
  4625. DirView(Side)->DisplayPropertiesMenu();
  4626. Result = true;
  4627. }
  4628. return Result;
  4629. }
  4630. //---------------------------------------------------------------------------
  4631. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4632. {
  4633. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4634. {
  4635. FIgnoreNextDialogChar = Key;
  4636. }
  4637. Key = 0;
  4638. }
  4639. //---------------------------------------------------------------------------
  4640. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4641. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4642. {
  4643. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4644. if (Command != NULL)
  4645. {
  4646. KeyProcessed(Key, Shift);
  4647. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4648. {
  4649. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4650. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4651. false, false, const_cast<TCustomCommandType *>(Command));
  4652. }
  4653. }
  4654. }
  4655. //---------------------------------------------------------------------------
  4656. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4657. {
  4658. if (!NonVisualDataModule->Busy)
  4659. {
  4660. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4661. {
  4662. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4663. }
  4664. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4665. {
  4666. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4667. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4668. {
  4669. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4670. // But so far it's not a problem, as it does what we want.
  4671. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4672. if (((Action->ShortCut == KeyShortCut) ||
  4673. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4674. AllowedAction(Action, aaShortCut))
  4675. {
  4676. // Has to be called before the action as the dialog char is already in queue.
  4677. // So when the action consumes message queue, we already need to have the
  4678. // FIgnoreNextDialogChar set
  4679. KeyProcessed(Key, Shift);
  4680. // Reset reference to previous component (when menu/toolbar was clicked).
  4681. // Needed to detect that action was invoked by keyboard shortcut
  4682. // in TNonVisualDataModule::ExplorerActionsExecute
  4683. Action->ActionComponent = NULL;
  4684. Action->Execute();
  4685. return;
  4686. }
  4687. }
  4688. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4689. {
  4690. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4691. {
  4692. KeyProcessed(Key, Shift);
  4693. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4694. return;
  4695. }
  4696. }
  4697. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4698. {
  4699. KeyProcessed(Key, Shift);
  4700. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4701. }
  4702. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4703. if (IsCustomShortCut(CustomShortCut))
  4704. {
  4705. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4706. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4707. if (WinConfiguration->SharedBookmarks != NULL)
  4708. {
  4709. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4710. if ((Bookmark != NULL) &&
  4711. OpenBookmark(FCurrentSide, Bookmark))
  4712. {
  4713. KeyProcessed(Key, Shift);
  4714. }
  4715. }
  4716. }
  4717. }
  4718. }
  4719. TForm::KeyDown(Key, Shift);
  4720. }
  4721. //---------------------------------------------------------------------------
  4722. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4723. {
  4724. bool OpenedTerminal = false;
  4725. UnicodeString ProtocolName;
  4726. UnicodeString ProtocolNameHint;
  4727. UnicodeString SecurityProtocolName;
  4728. UnicodeString DurationHint;
  4729. // See the comment in TScpCommanderForm::UpdateControls()
  4730. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4731. if (ActiveTerminal != NULL)
  4732. {
  4733. // Active is not enough here
  4734. if (ActiveTerminal->Status == ssOpened)
  4735. {
  4736. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4737. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4738. if (FileSystemInfo.ProtocolName.IsEmpty())
  4739. {
  4740. ProtocolName = SessionInfo.ProtocolName;
  4741. }
  4742. else
  4743. {
  4744. ProtocolName = FileSystemInfo.ProtocolName;
  4745. }
  4746. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4747. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4748. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4749. OpenedTerminal = true;
  4750. }
  4751. else if (ActiveTerminal->Status > ssClosed)
  4752. {
  4753. ProtocolName = LoadStr(STATUS_CONNECTING);
  4754. }
  4755. else
  4756. {
  4757. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4758. }
  4759. }
  4760. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4761. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4762. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4763. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4764. if (ProtocolStatusPanel->Caption != ProtocolName)
  4765. {
  4766. ProtocolStatusPanel->Caption = ProtocolName;
  4767. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4768. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4769. }
  4770. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4771. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4772. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4773. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4774. SecurityStatusPanel->Enabled = SecurityEnabled;
  4775. UnicodeString SecurityProtocolHint;
  4776. if (SecurityEnabled)
  4777. {
  4778. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4779. }
  4780. else
  4781. {
  4782. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4783. }
  4784. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4785. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4786. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4787. DurationStatusPanel->Hint = DurationHint;
  4788. UpdateStatusBar();
  4789. }
  4790. //---------------------------------------------------------------------------
  4791. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4792. {
  4793. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4794. DebugAssert(SessionStatusBar != NULL);
  4795. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4796. if (!FNote.IsEmpty())
  4797. {
  4798. NoteStatusPanel->Caption = FNote;
  4799. }
  4800. else
  4801. {
  4802. UpdateStatusPanelText(NoteStatusPanel);
  4803. }
  4804. NoteStatusPanel->Hint = FNoteHints;
  4805. UnicodeString LoginTime;
  4806. // See the comment in TScpCommanderForm::UpdateControls()
  4807. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4808. // Active is not enough here
  4809. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4810. {
  4811. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4812. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4813. }
  4814. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4815. DurationStatusPanel->Caption = LoginTime;
  4816. }
  4817. //---------------------------------------------------------------------------
  4818. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4819. {
  4820. Panel->Caption = L"";
  4821. }
  4822. //---------------------------------------------------------------------------
  4823. void __fastcall TCustomScpExplorerForm::Idle()
  4824. {
  4825. if (FShowing ||
  4826. // Particularly for
  4827. // - Standalone editing
  4828. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4829. // while "keeping remote directory up to date".
  4830. StandaloneOperation)
  4831. {
  4832. FEditorManager->Check();
  4833. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4834. // that needs to know if queue view is visible (and it may be closed after queue update)
  4835. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4836. }
  4837. if (FShowing)
  4838. {
  4839. if (!NonVisualDataModule->Busy &&
  4840. // Menu is opened or drag&drop is going on
  4841. (Mouse->Capture == NULL))
  4842. {
  4843. if (FRefreshRemoteDirectory)
  4844. {
  4845. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4846. {
  4847. Terminal->RefreshDirectory();
  4848. }
  4849. FRefreshRemoteDirectory = false;
  4850. }
  4851. if (FRefreshLocalDirectory)
  4852. {
  4853. ReloadLocalDirectory();
  4854. FRefreshLocalDirectory = false;
  4855. }
  4856. if (WinConfiguration->RefreshRemotePanel)
  4857. {
  4858. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4859. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4860. {
  4861. RemoteDirView->ReloadDirectory();
  4862. }
  4863. }
  4864. }
  4865. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4866. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4867. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4868. // 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.
  4869. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4870. MenuToolbar->Idle();
  4871. }
  4872. if (FShowing || StandaloneOperation)
  4873. {
  4874. if (FQueueStatusInvalidated)
  4875. {
  4876. UpdateQueueStatus(false);
  4877. }
  4878. RefreshQueueItems();
  4879. }
  4880. if (FShowing)
  4881. {
  4882. UpdateStatusBar();
  4883. }
  4884. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4885. {
  4886. FClipboardFakeMonitorsPendingReset = false;
  4887. FClipboardFakeMonitors.reset(NULL);
  4888. }
  4889. FIgnoreNextDialogChar = 0;
  4890. }
  4891. //---------------------------------------------------------------------------
  4892. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4893. {
  4894. try
  4895. {
  4896. FUserActionTimer->Enabled = false;
  4897. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4898. {
  4899. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4900. {
  4901. FPendingQueueActionItem->ProcessUserAction();
  4902. }
  4903. }
  4904. }
  4905. __finally
  4906. {
  4907. FPendingQueueActionItem = NULL;
  4908. }
  4909. }
  4910. //---------------------------------------------------------------------------
  4911. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4912. {
  4913. if (WinConfiguration->MinimizeToTray)
  4914. {
  4915. UpdateTrayIcon();
  4916. FTrayIcon->Visible = true;
  4917. if (Visible)
  4918. {
  4919. ShowWindow(Handle, SW_HIDE);
  4920. }
  4921. }
  4922. }
  4923. //---------------------------------------------------------------------------
  4924. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4925. {
  4926. // WORKAROUND
  4927. // When restoring maximized window from minimization,
  4928. // rarely some controls do not align properly.
  4929. // Two instances seen (both for Commander):
  4930. // - When restoring, window is temporarily narrower (not maximized),
  4931. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4932. // Once maximized already, top dock shinks back, but the session PageControl,
  4933. // do not align up, leaving space between TopDock and PageControl.
  4934. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4935. for (int Index = 0; Index < ControlCount; Index++)
  4936. {
  4937. RealignControl(Controls[Index]);
  4938. }
  4939. if (FTrayIcon->Visible)
  4940. {
  4941. FTrayIcon->Visible = false;
  4942. if (Visible)
  4943. {
  4944. ShowWindow(Handle, SW_SHOW);
  4945. }
  4946. }
  4947. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4948. {
  4949. FNeedSession = false;
  4950. NonVisualDataModule->StartBusy();
  4951. try
  4952. {
  4953. NeedSession(true);
  4954. }
  4955. __finally
  4956. {
  4957. NonVisualDataModule->EndBusy();
  4958. }
  4959. }
  4960. }
  4961. //---------------------------------------------------------------------------
  4962. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4963. {
  4964. FTrayIcon->Hint = GetMainForm()->Caption;
  4965. }
  4966. //---------------------------------------------------------------------------
  4967. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4968. {
  4969. UpdateTrayIcon();
  4970. }
  4971. //---------------------------------------------------------------------------
  4972. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4973. {
  4974. // workaround
  4975. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4976. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4977. // But WM_ACTIVATEAPP message can be received even when
  4978. // the main window is minimized to the tray and internal editor window is focused
  4979. // (after another application was previously active)
  4980. if (::IsIconic(Handle))
  4981. {
  4982. if (!IsAppIconic())
  4983. {
  4984. SetAppIconic(true);
  4985. }
  4986. }
  4987. ::ApplicationRestore();
  4988. Application->BringToFront();
  4989. }
  4990. //---------------------------------------------------------------------------
  4991. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4992. {
  4993. RestoreApp();
  4994. }
  4995. //---------------------------------------------------------------------------
  4996. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4997. {
  4998. if (OpenInNewWindow())
  4999. {
  5000. ExecuteNewInstance(SessionUrl);
  5001. }
  5002. else
  5003. {
  5004. TTerminalManager::Instance()->NewSession(SessionUrl);
  5005. }
  5006. }
  5007. //---------------------------------------------------------------------------
  5008. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  5009. {
  5010. NewSession();
  5011. }
  5012. //---------------------------------------------------------------------------
  5013. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  5014. {
  5015. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  5016. StoredSessions->NewSession(SessionName, SessionData);
  5017. // modified only, explicit
  5018. StoredSessions->Save(false, true);
  5019. // encode session name because of slashes in hierarchical sessions
  5020. return EncodeUrlString(SessionName);
  5021. }
  5022. //---------------------------------------------------------------------------
  5023. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  5024. {
  5025. // current working directories become defaults here, what is not right
  5026. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5027. return SaveHiddenDuplicateSession(SessionData.get());
  5028. }
  5029. //---------------------------------------------------------------------------
  5030. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  5031. {
  5032. if (OpenInNewWindow())
  5033. {
  5034. ExecuteNewInstance(CreateHiddenDuplicateSession());
  5035. }
  5036. else
  5037. {
  5038. // current working directories become defaults here, what is not right
  5039. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5040. TTerminalManager * Manager = TTerminalManager::Instance();
  5041. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  5042. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  5043. // We definitely want these
  5044. ASession->Disconnected = ManagedSession->Disconnected;
  5045. // Not sure about these two
  5046. ASession->Permanent = ManagedSession->Permanent;
  5047. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  5048. Manager->ActiveSession = ASession;
  5049. }
  5050. }
  5051. //---------------------------------------------------------------------------
  5052. void __fastcall TCustomScpExplorerForm::RenameTab()
  5053. {
  5054. UnicodeString Name = ManagedSession->SessionData->SessionName;
  5055. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  5056. // When submitting the default name, do not fix it
  5057. (Name != ManagedSession->SessionData->SessionName))
  5058. {
  5059. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5060. TSessionData::ValidateName(Name);
  5061. // This is inconsistent with how color (for example) is handled.
  5062. ManagedSession->SessionData->Name = Name;
  5063. UpdateControls();
  5064. // Add/Remove distinguishing paths from sessions of the same name.
  5065. SessionListChanged();
  5066. }
  5067. }
  5068. //---------------------------------------------------------------------------
  5069. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5070. {
  5071. DebugAssert(Queue != NULL);
  5072. bool Result = Queue->IsEmpty;
  5073. if (!Result)
  5074. {
  5075. SetFocus();
  5076. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5077. }
  5078. return Result;
  5079. }
  5080. //---------------------------------------------------------------------------
  5081. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5082. {
  5083. return CanCloseQueue(FQueue);
  5084. }
  5085. //---------------------------------------------------------------------------
  5086. void __fastcall TCustomScpExplorerForm::CloseTab()
  5087. {
  5088. if (CanCloseQueue())
  5089. {
  5090. TTerminalManager::Instance()->FreeActiveTerminal();
  5091. }
  5092. }
  5093. //---------------------------------------------------------------------------
  5094. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5095. {
  5096. if (CanCloseQueue())
  5097. {
  5098. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5099. }
  5100. }
  5101. //---------------------------------------------------------------------------
  5102. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5103. {
  5104. DetachTerminal(Terminal);
  5105. RemoteDirView->Terminal = Terminal;
  5106. UpdateRemotePathComboBox(false);
  5107. InitStatusBar();
  5108. UpdateControls();
  5109. }
  5110. //---------------------------------------------------------------------------
  5111. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5112. {
  5113. InitStatusBar();
  5114. }
  5115. //---------------------------------------------------------------------------
  5116. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5117. {
  5118. if (DebugAlwaysTrue(!Terminal->Active))
  5119. {
  5120. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5121. }
  5122. }
  5123. //---------------------------------------------------------------------------
  5124. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5125. {
  5126. if (OpenInNewWindow())
  5127. {
  5128. // encode session name because of slashes in hierarchical sessions
  5129. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5130. }
  5131. else
  5132. {
  5133. TTerminalManager * Manager = TTerminalManager::Instance();
  5134. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5135. Manager->ActiveSession = Terminal;
  5136. }
  5137. }
  5138. //---------------------------------------------------------------------------
  5139. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5140. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5141. {
  5142. TTerminalManager * Manager = TTerminalManager::Instance();
  5143. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5144. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5145. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5146. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5147. {
  5148. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5149. // FirstSession can be null, if none of the workspace sites exist anymore
  5150. // or if all workspace sessions are not suported by the interface
  5151. // (when trying to open all local-local workspace in "explorer" interface)
  5152. if (FirstSession != NULL)
  5153. {
  5154. if (!ConnectFirstTerminal)
  5155. {
  5156. FirstSession->Disconnected = true;
  5157. FirstSession->DisconnectedTemporarily = true;
  5158. }
  5159. Manager->ActiveSession = FirstSession;
  5160. }
  5161. }
  5162. }
  5163. //---------------------------------------------------------------------------
  5164. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5165. {
  5166. if (OpenInNewWindow())
  5167. {
  5168. ExecuteNewInstance(Name);
  5169. }
  5170. else
  5171. {
  5172. DoOpenFolderOrWorkspace(Name, true, false);
  5173. }
  5174. }
  5175. //---------------------------------------------------------------------------
  5176. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5177. bool &CanClose)
  5178. {
  5179. AppLog(L"Windows close query");
  5180. // See the comment in CloseApp()
  5181. if (NonVisualDataModule->Busy)
  5182. {
  5183. CanClose = false;
  5184. }
  5185. else
  5186. {
  5187. TTerminalManager * Manager = TTerminalManager::Instance();
  5188. int ActiveSessions = 0;
  5189. for (int Index = 0; Index < Manager->Count; Index++)
  5190. {
  5191. if (Manager->Sessions[Index]->Active)
  5192. {
  5193. ActiveSessions++;
  5194. }
  5195. }
  5196. // Confirm, when there's at least one active remote session or
  5197. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5198. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5199. WinConfiguration->ConfirmClosingSession)
  5200. {
  5201. unsigned int Result;
  5202. TMessageParams Params(mpNeverAskAgainCheck);
  5203. UnicodeString Message;
  5204. int Answers = qaOK | qaCancel;
  5205. // The current session is the only active session
  5206. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5207. {
  5208. if (!WinConfiguration->AutoSaveWorkspace)
  5209. {
  5210. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5211. }
  5212. else
  5213. {
  5214. Message = LoadStr(CLOSE_SESSION);
  5215. }
  5216. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5217. }
  5218. // Multiple active sessions or one active session, but it's not the current one
  5219. else if (ActiveSessions > 0)
  5220. {
  5221. if (!WinConfiguration->AutoSaveWorkspace)
  5222. {
  5223. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5224. }
  5225. else
  5226. {
  5227. Message = LoadStr(CLOSE_SESSIONS);
  5228. }
  5229. }
  5230. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5231. else
  5232. {
  5233. DebugAlwaysTrue(Manager->Count > 1);
  5234. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5235. Message = LoadStr(CLOSE_WORKSPACE);
  5236. }
  5237. UnicodeString Note;
  5238. if (WinConfiguration->AutoSaveWorkspace)
  5239. {
  5240. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5241. }
  5242. else
  5243. {
  5244. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5245. Answers = qaYes | qaNo | qaCancel;
  5246. }
  5247. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5248. SetFocus();
  5249. Result = MessageDialog(Message, qtConfirmation,
  5250. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5251. if (Result == qaNeverAskAgain)
  5252. {
  5253. WinConfiguration->ConfirmClosingSession = false;
  5254. }
  5255. if (Result == qaNo)
  5256. {
  5257. CanClose = SaveWorkspace(true);
  5258. // note that the workspace will be saved redundatly again from FormClose
  5259. }
  5260. else
  5261. {
  5262. CanClose =
  5263. (Result == qaOK) ||
  5264. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5265. (Result == qaNeverAskAgain);
  5266. }
  5267. }
  5268. if (CanClose && HasAvailableTerminal())
  5269. {
  5270. CanClose = CanCloseQueue();
  5271. }
  5272. }
  5273. if (CanClose)
  5274. {
  5275. CanClose =
  5276. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5277. FEditorManager->CloseExternalFilesWithoutProcess();
  5278. if (CanClose)
  5279. {
  5280. while (CanClose && (FLocalEditors->Count > 0))
  5281. {
  5282. int PrevCount = FLocalEditors->Count;
  5283. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5284. CanClose = (FLocalEditors->Count < PrevCount);
  5285. }
  5286. if (CanClose)
  5287. {
  5288. CanClose = FEditorManager->Empty(true);
  5289. if (!CanClose)
  5290. {
  5291. SetFocus();
  5292. CanClose =
  5293. (MessageDialog(
  5294. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5295. }
  5296. }
  5297. }
  5298. }
  5299. }
  5300. //---------------------------------------------------------------------------
  5301. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5302. {
  5303. TForm * Form = dynamic_cast<TForm *>(Sender);
  5304. DebugAssert(Form != NULL);
  5305. Form->Close();
  5306. }
  5307. //---------------------------------------------------------------------------
  5308. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5309. {
  5310. TForm * Form = dynamic_cast<TForm *>(Sender);
  5311. delete Form;
  5312. }
  5313. //---------------------------------------------------------------------------
  5314. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5315. {
  5316. while (FLocalEditors->Count > 0)
  5317. {
  5318. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5319. }
  5320. }
  5321. //---------------------------------------------------------------------------
  5322. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5323. TObject *Sender)
  5324. {
  5325. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5326. try
  5327. {
  5328. SetProperties(osRemote, FileList);
  5329. }
  5330. __finally
  5331. {
  5332. delete FileList;
  5333. }
  5334. }
  5335. //---------------------------------------------------------------------------
  5336. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5337. {
  5338. if (value)
  5339. {
  5340. if (Component == fcCustomCommandsBand)
  5341. {
  5342. UpdateCustomCommandsToolbar();
  5343. }
  5344. if (Component == fcQueueFileList)
  5345. {
  5346. DebugAssert(!QueueFileListSplitter->Visible);
  5347. AdjustQueueLayout();
  5348. UpdateQueueFileList();
  5349. }
  5350. }
  5351. }
  5352. //---------------------------------------------------------------------------
  5353. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5354. {
  5355. int MinHeightLimit =
  5356. GetStaticQueuePanelComponentsHeight() +
  5357. QueueFileListSplitter->Height +
  5358. QueueFileList->Height +
  5359. GetMinQueueViewHeight();
  5360. if (QueuePanel->ClientHeight < MinHeightLimit)
  5361. {
  5362. QueuePanel->ClientHeight = MinHeightLimit;
  5363. }
  5364. }
  5365. //---------------------------------------------------------------------------
  5366. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5367. {
  5368. TControl * Control = GetComponent(Component);
  5369. DebugAssert(Control);
  5370. bool Changed = (Control->Visible != value);
  5371. if (Changed)
  5372. {
  5373. ComponentShowing(Component, value);
  5374. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5375. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5376. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5377. if (value)
  5378. {
  5379. int RemainingHeight = Control->Parent->ClientHeight;
  5380. int RemainingWidth = Control->Parent->ClientWidth;
  5381. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5382. {
  5383. TControl * ChildControl = Control->Parent->Controls[i];
  5384. if (ChildControl->Visible)
  5385. {
  5386. switch (ChildControl->Align)
  5387. {
  5388. case alTop:
  5389. case alBottom:
  5390. RemainingHeight -= ChildControl->Height;
  5391. break;
  5392. case alLeft:
  5393. case alRight:
  5394. RemainingWidth -= ChildControl->Width;
  5395. break;
  5396. }
  5397. }
  5398. }
  5399. int Reserve = ScaleByTextHeight(this, 32);
  5400. // queue in explorer, trees in commander
  5401. if (Control->Height > RemainingHeight - Reserve)
  5402. {
  5403. Control->Height = RemainingHeight / 2;
  5404. }
  5405. if (Control->Width > RemainingWidth - Reserve)
  5406. {
  5407. Control->Width = RemainingWidth / 2;
  5408. }
  5409. }
  5410. Control->Visible = value;
  5411. if (WasFocused && Visible)
  5412. {
  5413. DirView(osCurrent)->SetFocus();
  5414. }
  5415. FixControlsPlacement();
  5416. }
  5417. }
  5418. //---------------------------------------------------------------------------
  5419. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5420. {
  5421. TControl * Control = GetComponent(Component);
  5422. if (Control == NULL)
  5423. {
  5424. return false;
  5425. }
  5426. else
  5427. {
  5428. return Control->Visible;
  5429. }
  5430. }
  5431. //---------------------------------------------------------------------------
  5432. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5433. {
  5434. bool Result;
  5435. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5436. {
  5437. Result = !IsUWP();
  5438. }
  5439. else
  5440. {
  5441. Result = true;
  5442. }
  5443. return Result;
  5444. }
  5445. //---------------------------------------------------------------------------
  5446. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5447. {
  5448. if (DirView->ItemFocused != NULL)
  5449. {
  5450. DirView->ItemFocused->MakeVisible(false);
  5451. }
  5452. }
  5453. //---------------------------------------------------------------------------
  5454. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5455. {
  5456. MakeFocusedItemVisible(RemoteDirView);
  5457. QueueSplitter->Visible = QueuePanel->Visible;
  5458. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5459. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5460. TControl * TopControlsOrder[] =
  5461. { TopDock, MessageDock, SessionsPageControl };
  5462. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5463. TControl * QueueControlsOrder[] =
  5464. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5465. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5466. }
  5467. //---------------------------------------------------------------------------
  5468. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5469. {
  5470. switch (Component) {
  5471. case fcStatusBar: return RemoteStatusBar;
  5472. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5473. case fcQueueView: return QueuePanel;
  5474. case fcQueueToolbar: return QueueDock;
  5475. case fcRemoteTree: return RemoteDrivePanel;
  5476. case fcSessionsTabs: return SessionsPageControl;
  5477. case fcQueueFileList: return QueueFileList;
  5478. default: return NULL;
  5479. }
  5480. }
  5481. //---------------------------------------------------------------------------
  5482. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5483. TObject *Sender, TListColumn *Column, TPoint &Point)
  5484. {
  5485. DebugAssert(NonVisualDataModule && Column && Sender);
  5486. NonVisualDataModule->ListColumn = Column;
  5487. TPopupMenu * DirViewColumnMenu;
  5488. if (Sender == DirView(osOther))
  5489. {
  5490. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5491. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5492. bool SizeColumn = (Column->Index == uvSize);
  5493. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5494. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5495. }
  5496. else
  5497. {
  5498. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5499. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5500. bool SizeColumn = (Column->Index == dvSize);
  5501. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5502. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5503. }
  5504. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5505. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5506. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5507. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5508. }
  5509. //---------------------------------------------------------------------------
  5510. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5511. TObject *Sender, TListItem *Item, bool &AllowExec)
  5512. {
  5513. DoDirViewExecFile(Sender, Item, AllowExec);
  5514. }
  5515. //---------------------------------------------------------------------------
  5516. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5517. TListItem * Item, bool & AllowExec)
  5518. {
  5519. DebugAssert(Sender && Item && Configuration);
  5520. DebugAssert(AllowExec);
  5521. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5522. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5523. bool Remote = !IsSideLocalBrowser(Side);
  5524. DebugAssert(Item == ADirView->ItemFocused);
  5525. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5526. TResolvedDoubleClickAction Action;
  5527. if (FForceExecution)
  5528. {
  5529. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5530. }
  5531. else
  5532. {
  5533. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5534. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5535. }
  5536. if (Action == rdcaCopy)
  5537. {
  5538. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5539. UnlockWindow();
  5540. try
  5541. {
  5542. if (IsLocalBrowserMode())
  5543. {
  5544. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5545. }
  5546. else
  5547. {
  5548. if (HasAvailableTerminal())
  5549. {
  5550. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5551. }
  5552. }
  5553. }
  5554. __finally
  5555. {
  5556. LockWindow();
  5557. }
  5558. AllowExec = false;
  5559. }
  5560. else if (Action == rdcaEdit)
  5561. {
  5562. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5563. {
  5564. ExecuteFile(Side, efDefaultEditor);
  5565. AllowExec = false;
  5566. }
  5567. }
  5568. else if (Action == rdcaOpen)
  5569. {
  5570. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5571. {
  5572. ExecuteFile(osRemote, efShell);
  5573. AllowExec = false;
  5574. }
  5575. }
  5576. }
  5577. //---------------------------------------------------------------------------
  5578. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5579. {
  5580. return ((Side == osRemote) || (Side == osCurrent));
  5581. }
  5582. //---------------------------------------------------------------------------
  5583. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5584. {
  5585. DebugFail();
  5586. }
  5587. //---------------------------------------------------------------------------
  5588. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5589. {
  5590. DebugFail();
  5591. }
  5592. //---------------------------------------------------------------------------
  5593. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5594. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5595. {
  5596. TSynchronizeParamType Params;
  5597. Params.LocalDirectory = LocalDirectory;
  5598. Params.RemoteDirectory = RemoteDirectory;
  5599. int UnusedParams =
  5600. (GUIConfiguration->SynchronizeParams &
  5601. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5602. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5603. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5604. Params.Options = GUIConfiguration->SynchronizeOptions;
  5605. bool SaveSettings = false;
  5606. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5607. &DoSynchronizeTooManyDirectories);
  5608. DebugAssert(FSynchronizeController == NULL);
  5609. FSynchronizeController = &Controller;
  5610. bool Result;
  5611. try
  5612. {
  5613. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5614. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5615. int Options =
  5616. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5617. DebugAssert(FOnFeedSynchronizeError == NULL);
  5618. DebugAssert(FOnSynchronizeAbort == NULL);
  5619. DebugAssert(FSynchronizeTerminal == NULL);
  5620. FSynchronizeTerminal = Terminal;
  5621. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5622. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5623. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5624. if (Result)
  5625. {
  5626. if (SaveSettings)
  5627. {
  5628. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5629. GUIConfiguration->SynchronizeOptions = Params.Options;
  5630. }
  5631. else
  5632. {
  5633. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5634. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5635. FLAGSET(Params.Options, soSynchronize))
  5636. {
  5637. GUIConfiguration->SynchronizeOptions =
  5638. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5639. soSynchronize;
  5640. }
  5641. }
  5642. LocalDirectory = Params.LocalDirectory;
  5643. RemoteDirectory = Params.RemoteDirectory;
  5644. }
  5645. }
  5646. __finally
  5647. {
  5648. FSynchronizeController = NULL;
  5649. DebugAssert(FOnFeedSynchronizeError == NULL);
  5650. FOnFeedSynchronizeError = NULL;
  5651. DebugAssert(FOnSynchronizeAbort == NULL);
  5652. FOnSynchronizeAbort = NULL;
  5653. FSynchronizeTerminal = NULL;
  5654. }
  5655. return Result;
  5656. }
  5657. //---------------------------------------------------------------------------
  5658. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5659. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5660. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5661. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5662. TSynchronizeOptions * Options, bool Full)
  5663. {
  5664. // Keep-up-to-date mode
  5665. if (Terminal->Status == ssOpened)
  5666. {
  5667. try
  5668. {
  5669. int PParams = Params.Params;
  5670. if (!Full)
  5671. {
  5672. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5673. if (FLAGSET(Params.Options, soRecurse))
  5674. {
  5675. PParams |= TTerminal::spSubDirs;
  5676. }
  5677. }
  5678. else
  5679. {
  5680. // if keepuptodate is non-recursive,
  5681. // full sync before has to be non-recursive as well
  5682. if (FLAGCLEAR(Params.Options, soRecurse))
  5683. {
  5684. PParams |= TTerminal::spNoRecurse;
  5685. }
  5686. }
  5687. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5688. PParams, Checklist, Options);
  5689. }
  5690. catch (Exception & E)
  5691. {
  5692. if (!Terminal->Active)
  5693. {
  5694. ShowExtendedExceptionEx(Terminal, &E);
  5695. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5696. if (!Terminal->Active)
  5697. {
  5698. throw;
  5699. }
  5700. }
  5701. else
  5702. {
  5703. if (FLAGSET(Params.Options, soContinueOnError) &&
  5704. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5705. {
  5706. // noop, already logged in MoreMessageDialog
  5707. }
  5708. else
  5709. {
  5710. // We get mostly EAbort here, so this is noop.
  5711. // Exception is an error when listing directories while looking for differences.
  5712. ShowExtendedExceptionEx(Terminal, &E);
  5713. throw;
  5714. }
  5715. }
  5716. }
  5717. }
  5718. }
  5719. //---------------------------------------------------------------------------
  5720. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5721. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5722. const UnicodeString ErrorStr)
  5723. {
  5724. if (!Directory.IsEmpty())
  5725. {
  5726. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5727. }
  5728. else
  5729. {
  5730. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5731. }
  5732. }
  5733. //---------------------------------------------------------------------------
  5734. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5735. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5736. {
  5737. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5738. {
  5739. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5740. }
  5741. else
  5742. {
  5743. TMessageParams Params(mpNeverAskAgainCheck);
  5744. unsigned int Result = MessageDialog(
  5745. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5746. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5747. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5748. {
  5749. MaxDirectories *= 2;
  5750. if (Result == qaNeverAskAgain)
  5751. {
  5752. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5753. }
  5754. }
  5755. else
  5756. {
  5757. Abort();
  5758. }
  5759. }
  5760. }
  5761. //---------------------------------------------------------------------------
  5762. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5763. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5764. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5765. TSynchronizeOptions * Options)
  5766. {
  5767. // Keep-up-to-date mode
  5768. DebugAssert(!FAutoOperation);
  5769. void * BatchStorage;
  5770. BatchStart(BatchStorage);
  5771. FAutoOperation = true;
  5772. bool AnyOperation = false;
  5773. TDateTime StartTime = Now();
  5774. TSynchronizeChecklist * AChecklist = NULL;
  5775. try
  5776. {
  5777. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5778. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5779. {
  5780. FSynchronizeProgressForm->Start();
  5781. }
  5782. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5783. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5784. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5785. Options);
  5786. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5787. SAFE_DESTROY(FSynchronizeProgressForm);
  5788. AnyOperation = (AChecklist->CheckedCount > 0);
  5789. if (AnyOperation)
  5790. {
  5791. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5792. CreateProgressForm(&SynchronizeProgress);
  5793. try
  5794. {
  5795. Terminal->SynchronizeApply(
  5796. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5797. SynchronizeProcessedItem, NULL, NULL, NULL);
  5798. }
  5799. __finally
  5800. {
  5801. DestroyProgressForm();
  5802. }
  5803. }
  5804. }
  5805. __finally
  5806. {
  5807. if (Checklist == NULL)
  5808. {
  5809. delete AChecklist;
  5810. }
  5811. else
  5812. {
  5813. *Checklist = AChecklist;
  5814. }
  5815. FAutoOperation = false;
  5816. SAFE_DESTROY(FSynchronizeProgressForm);
  5817. BatchEnd(BatchStorage);
  5818. ReloadLocalDirectory();
  5819. if (AnyOperation)
  5820. {
  5821. OperationComplete(StartTime);
  5822. }
  5823. }
  5824. }
  5825. //---------------------------------------------------------------------------
  5826. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5827. {
  5828. // can be called from command line
  5829. return Visible &&
  5830. ((DirView(osRemote)->SelCount > 0) ||
  5831. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5832. }
  5833. //---------------------------------------------------------------------------
  5834. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5835. {
  5836. LogSynchronizeEvent(Terminal, Message);
  5837. }
  5838. //---------------------------------------------------------------------------
  5839. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5840. int Params, TSynchronizeOptions & Options)
  5841. {
  5842. DebugAssert(!IsLocalBrowserMode());
  5843. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5844. {
  5845. Options.Filter = new TStringList();
  5846. Options.Filter->CaseSensitive = false;
  5847. Options.Filter->Duplicates = Types::dupAccept;
  5848. if (DirView(osRemote)->SelCount > 0)
  5849. {
  5850. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5851. }
  5852. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5853. {
  5854. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5855. }
  5856. Options.Filter->Sort();
  5857. }
  5858. }
  5859. //---------------------------------------------------------------------------
  5860. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5861. {
  5862. TCopyParamType Defaults;
  5863. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5864. ConfigStorage->AccessMode = smRead;
  5865. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5866. {
  5867. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5868. }
  5869. ConfigStorage.reset(NULL);
  5870. std::unique_ptr<TStringList> Options(new TStringList());
  5871. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5872. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5873. UnicodeString Result;
  5874. if (Options->Count > 0)
  5875. {
  5876. Result =
  5877. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5878. }
  5879. return Result;
  5880. }
  5881. //---------------------------------------------------------------------------
  5882. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5883. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5884. {
  5885. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5886. UnicodeString AdditionalParams =
  5887. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5888. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5889. SerializeCopyParamForCommandLine(CopyParams),
  5890. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5891. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5892. ExecuteNewInstance(SessionName, AdditionalParams);
  5893. }
  5894. //---------------------------------------------------------------------------
  5895. struct TSynchronizeParams
  5896. {
  5897. UnicodeString LocalDirectory;
  5898. UnicodeString RemoteDirectory;
  5899. TSynchronizeMode Mode;
  5900. TSynchronizeChecklist * Checklist;
  5901. int Params;
  5902. TCopyParamType * CopyParam;
  5903. TDateTime CollectElapsed;
  5904. TDateTime * StartTime;
  5905. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5906. };
  5907. //---------------------------------------------------------------------------
  5908. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5909. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5910. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5911. {
  5912. DebugAssert(!FAutoOperation);
  5913. void * BatchStorage;
  5914. BatchStart(BatchStorage);
  5915. FAutoOperation = true;
  5916. TFileOperationStatistics Statistics;
  5917. TDateTime Start = Now();
  5918. try
  5919. {
  5920. Params.OnProcessedItem = OnProcessedItem;
  5921. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5922. CreateProgressForm(&SynchronizeProgress);
  5923. Terminal->SynchronizeApply(
  5924. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5925. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5926. &Statistics);
  5927. }
  5928. __finally
  5929. {
  5930. Params.OnProcessedItem = NULL;
  5931. FAutoOperation = false;
  5932. DestroyProgressForm();
  5933. BatchEnd(BatchStorage);
  5934. ReloadLocalDirectory();
  5935. }
  5936. if (WinConfiguration->SynchronizeSummary)
  5937. {
  5938. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5939. // The statistics should be 0 anyway in this case
  5940. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5941. {
  5942. Message += L"\n";
  5943. if (Statistics.FilesUploaded > 0)
  5944. {
  5945. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5946. }
  5947. if (Statistics.FilesDownloaded > 0)
  5948. {
  5949. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5950. }
  5951. if (Statistics.FilesDeletedLocal > 0)
  5952. {
  5953. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5954. }
  5955. if (Statistics.FilesDeletedRemote > 0)
  5956. {
  5957. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5958. }
  5959. }
  5960. TDateTime Elapsed = (Now() - Start);
  5961. Message +=
  5962. L"\n" +
  5963. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5964. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5965. TMessageParams Params(mpNeverAskAgainCheck);
  5966. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5967. if (Result == qaNeverAskAgain)
  5968. {
  5969. WinConfiguration->SynchronizeSummary = false;
  5970. }
  5971. }
  5972. }
  5973. //---------------------------------------------------------------------------
  5974. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5975. {
  5976. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5977. {
  5978. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5979. }
  5980. // Not set in keep-up-to-date mode - Synchronize() method
  5981. if (Token != NULL)
  5982. {
  5983. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5984. if (Params.OnProcessedItem != NULL)
  5985. {
  5986. Params.OnProcessedItem(NULL, ChecklistItem);
  5987. }
  5988. }
  5989. }
  5990. //---------------------------------------------------------------------------
  5991. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5992. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5993. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5994. {
  5995. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5996. *Params.StartTime = Now();
  5997. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5998. }
  5999. //---------------------------------------------------------------------------
  6000. void TCustomScpExplorerForm::DoQueueSynchronize(void * Token)
  6001. {
  6002. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6003. int CopyParams = TTerminal::GetSynchronizeCopyParams(Params.Params);
  6004. TCopyParamType SyncCopyParam = TTerminal::GetSynchronizeCopyParam(Params.CopyParam, Params.Params);
  6005. bool Parallel = GUIConfiguration->CurrentCopyParam.QueueParallel;
  6006. int Index = 0;
  6007. const TSynchronizeChecklist::TItem * ChecklistItem;
  6008. while (Params.Checklist->GetNextChecked(Index, ChecklistItem))
  6009. {
  6010. TQueueItem * QueueItem = Terminal->SynchronizeToQueue(ChecklistItem, &SyncCopyParam, CopyParams, Parallel);
  6011. AddQueueItem(Queue, QueueItem, Terminal);
  6012. }
  6013. }
  6014. //---------------------------------------------------------------------------
  6015. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  6016. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  6017. {
  6018. // terminal can be already closed (e.g. dropped connection)
  6019. if (Terminal != NULL)
  6020. {
  6021. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6022. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  6023. }
  6024. }
  6025. //---------------------------------------------------------------------------
  6026. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  6027. TOperationSide Side, TStrings * FileList, const UnicodeString & NewFileName, bool TargetIsDirectory, void * Token)
  6028. {
  6029. DebugAssert(!IsLocalBrowserMode());
  6030. TAutoBatch AutoBatch(this);
  6031. TAutoFlag AutoOperationFlag(FAutoOperation);
  6032. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6033. if (Side == osRemote)
  6034. {
  6035. UnicodeString Target;
  6036. UnicodeString FileMask;
  6037. if (TargetIsDirectory)
  6038. {
  6039. Target = NewFileName;
  6040. Terminal->CreateTargetDirectory(Target, faDirectory, Params.CopyParam);
  6041. }
  6042. else
  6043. {
  6044. Target = UnixExtractFileDir(NewFileName);
  6045. FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  6046. }
  6047. RemoteDirView->SaveSelection();
  6048. RemoteDirView->SaveSelectedNames();
  6049. try
  6050. {
  6051. Terminal->MoveFiles(FileList, Target, FileMask, false);
  6052. }
  6053. catch(...)
  6054. {
  6055. RemoteDirView->DiscardSavedSelection();
  6056. throw;
  6057. }
  6058. RemoteDirView->RestoreSelection();
  6059. }
  6060. else if (DebugAlwaysTrue(Side == osLocal))
  6061. {
  6062. std::unique_ptr<TStrings> Directories(CreateSortedStringList());
  6063. if (TargetIsDirectory)
  6064. {
  6065. if (!ForceDirectories(ApiPath(NewFileName)))
  6066. {
  6067. throw EOSExtException(FMTLOAD(CREATE_DIR_ERROR, (NewFileName)));
  6068. }
  6069. Directories->Add(NewFileName);
  6070. }
  6071. else
  6072. {
  6073. Directories->Add(ExtractFileDir(NewFileName));
  6074. }
  6075. for (int Index = 0; Index < FileList->Count; Index++)
  6076. {
  6077. UnicodeString FileName = FileList->Strings[Index];
  6078. UnicodeString Directory = ExtractFileDir(FileName);
  6079. Directories->Add(Directory);
  6080. UnicodeString NewFilePath = NewFileName;
  6081. if (TargetIsDirectory)
  6082. {
  6083. NewFilePath = TPath::Combine(NewFilePath, ExtractFileName(FileName));
  6084. }
  6085. if (!MoveFile(ApiPath(FileName).c_str(), ApiPath(NewFilePath).c_str()))
  6086. {
  6087. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFilePath)));
  6088. }
  6089. }
  6090. for (int Index = 0; Index < Directories->Count; Index++)
  6091. {
  6092. ReloadLocalDirectory(Directories->Strings[Index]);
  6093. }
  6094. }
  6095. }
  6096. //---------------------------------------------------------------------------
  6097. void __fastcall TCustomScpExplorerForm::DoSynchronizeExplore(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  6098. {
  6099. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  6100. if (Side == osLocal)
  6101. {
  6102. if (Action == TSynchronizeChecklist::saDownloadNew)
  6103. {
  6104. OpenFolderInExplorer(LocalPath);
  6105. }
  6106. else
  6107. {
  6108. OpenFileInExplorer(Item->ForceGetLocalPath());
  6109. }
  6110. }
  6111. else if (DebugAlwaysTrue(Side == osRemote))
  6112. {
  6113. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6114. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6115. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6116. if (!LocalPath.IsEmpty())
  6117. {
  6118. SessionData->LocalDirectory = LocalPath;
  6119. }
  6120. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6121. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(EXPLORE_SWITCH), Item->GetFileName())));
  6122. }
  6123. }
  6124. //---------------------------------------------------------------------------
  6125. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6126. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6127. const TCopyParamType * CopyParams)
  6128. {
  6129. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6130. UnicodeString AdditionalParams =
  6131. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6132. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6133. SerializeCopyParamForCommandLine(CopyParams),
  6134. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6135. LocalDirectory, RemoteDirectory, Mode, Params));
  6136. ExecuteNewInstance(SessionName, AdditionalParams);
  6137. }
  6138. //---------------------------------------------------------------------------
  6139. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6140. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6141. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6142. {
  6143. int Result;
  6144. bool SaveSettings = false;
  6145. int Options =
  6146. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6147. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6148. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6149. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6150. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6151. bool Continue =
  6152. ((UseDefaults == 0) ||
  6153. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6154. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6155. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6156. if (Continue)
  6157. {
  6158. Configuration->Usage->Inc(L"Synchronizations");
  6159. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6160. UpdateCopyParamCounters(CopyParam);
  6161. TSynchronizeOptions SynchronizeOptions;
  6162. GetSynchronizeOptions(Params, SynchronizeOptions);
  6163. if (SaveSettings)
  6164. {
  6165. GUIConfiguration->SynchronizeParams = Params;
  6166. }
  6167. else
  6168. {
  6169. SaveMode = false;
  6170. }
  6171. TDateTime StartTime = Now();
  6172. TSynchronizeChecklist * Checklist = NULL;
  6173. try
  6174. {
  6175. DebugAssert(!FAutoOperation);
  6176. FAutoOperation = true;
  6177. try
  6178. {
  6179. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6180. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6181. int Files = -1;
  6182. if (DataList->Count >= 1)
  6183. {
  6184. Files = StrToIntDef(DataList->Strings[0], Files);
  6185. }
  6186. else
  6187. {
  6188. DataList->Add(UnicodeString());
  6189. }
  6190. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6191. FSynchronizeProgressForm->Start();
  6192. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6193. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6194. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6195. &SynchronizeOptions);
  6196. if (Terminal->SessionData->CacheDirectories)
  6197. {
  6198. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6199. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6200. }
  6201. }
  6202. __finally
  6203. {
  6204. FAutoOperation = false;
  6205. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6206. SAFE_DESTROY(FSynchronizeProgressForm);
  6207. }
  6208. TSynchronizeParams SynchronizeParams;
  6209. SynchronizeParams.LocalDirectory = LocalDirectory;
  6210. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6211. SynchronizeParams.Mode = Mode;
  6212. SynchronizeParams.CopyParam = &CopyParam;
  6213. SynchronizeParams.Params = Params;
  6214. SynchronizeParams.Checklist = Checklist;
  6215. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6216. SynchronizeParams.StartTime = &StartTime;
  6217. SynchronizeParams.OnProcessedItem = NULL;
  6218. Result = Checklist->Count;
  6219. if (Checklist->Count > 0)
  6220. {
  6221. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6222. {
  6223. TQueueSynchronizeEvent OnQueueSynchronize = NULL;
  6224. if (Visible && FLAGCLEAR(Params, TTerminal::spTimestamp))
  6225. {
  6226. OnQueueSynchronize = DoQueueSynchronize;
  6227. }
  6228. if (!DoSynchronizeChecklistDialog(
  6229. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6230. OnQueueSynchronize, DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeExplore,
  6231. &SynchronizeParams))
  6232. {
  6233. Result = -1;
  6234. }
  6235. }
  6236. else
  6237. {
  6238. FullSynchronize(SynchronizeParams, NULL, NULL);
  6239. }
  6240. }
  6241. else
  6242. {
  6243. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6244. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6245. }
  6246. }
  6247. __finally
  6248. {
  6249. delete Checklist;
  6250. }
  6251. OperationComplete(StartTime);
  6252. }
  6253. else
  6254. {
  6255. Result = -1;
  6256. }
  6257. return Result;
  6258. }
  6259. //---------------------------------------------------------------------------
  6260. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6261. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6262. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6263. {
  6264. if (Collect)
  6265. {
  6266. DebugAssert(FSynchronizeProgressForm != NULL);
  6267. if (!FSynchronizeProgressForm->Started)
  6268. {
  6269. FSynchronizeProgressForm->Start();
  6270. }
  6271. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6272. SetTaskbarListProgressValue(CompareProgress);
  6273. }
  6274. else
  6275. {
  6276. DebugAssert(FSynchronizeProgressForm == NULL);
  6277. DebugAssert(FProgressForm != NULL);
  6278. }
  6279. }
  6280. //---------------------------------------------------------------------------
  6281. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6282. {
  6283. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6284. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6285. if (File.get() != NULL)
  6286. {
  6287. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6288. Application->ShowMainForm = false;
  6289. Application->Run();
  6290. }
  6291. }
  6292. //---------------------------------------------------------------------------
  6293. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6294. {
  6295. DebugFail();
  6296. }
  6297. //---------------------------------------------------------------------------
  6298. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6299. {
  6300. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6301. SessionData->Assign(ManagedSession->SessionData);
  6302. UpdateSessionData(SessionData.get());
  6303. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6304. if (IsAvailableTerminal(ManagedSession))
  6305. {
  6306. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6307. }
  6308. if (!ManagedSession->SessionData->HasSessionName())
  6309. {
  6310. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6311. // once IsWorkspace is cleared
  6312. SessionData->Name = UnicodeString();
  6313. }
  6314. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6315. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6316. SessionData->IsWorkspace = false;
  6317. return SessionData.release();
  6318. }
  6319. //---------------------------------------------------------------------------
  6320. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6321. {
  6322. TSessionData * SessionData = CloneCurrentSessionData();
  6323. try
  6324. {
  6325. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6326. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6327. }
  6328. __finally
  6329. {
  6330. delete SessionData;
  6331. }
  6332. }
  6333. //---------------------------------------------------------------------------
  6334. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6335. {
  6336. TTerminalManager * Manager = TTerminalManager::Instance();
  6337. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6338. if (DebugAlwaysTrue(ManagedSession != NULL))
  6339. {
  6340. // Update ManagedSession->StateData
  6341. UpdateSession(ManagedSession);
  6342. }
  6343. Manager->SaveWorkspace(DataList.get());
  6344. return DataList.release();
  6345. }
  6346. //---------------------------------------------------------------------------
  6347. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6348. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6349. {
  6350. WinConfiguration->LastWorkspace = Name;
  6351. if (!SavePasswords)
  6352. {
  6353. for (int Index = 0; Index < DataList->Count; Index++)
  6354. {
  6355. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6356. if (SessionData->Link.IsEmpty())
  6357. {
  6358. SessionData->ClearSessionPasswords();
  6359. }
  6360. }
  6361. }
  6362. StoredSessions->NewWorkspace(Name, DataList);
  6363. // modified only
  6364. StoredSessions->Save(false, Explicit);
  6365. }
  6366. //---------------------------------------------------------------------------
  6367. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6368. {
  6369. return
  6370. DefaultStr(WinConfiguration->LastWorkspace,
  6371. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6372. }
  6373. //---------------------------------------------------------------------------
  6374. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6375. {
  6376. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6377. bool AnyNonStoredSessionWithPassword = false;
  6378. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6379. bool AllNonStoredSessionsAnonymous = true;
  6380. TTerminalManager * Manager = TTerminalManager::Instance();
  6381. for (int Index = 0; Index < DataList->Count; Index++)
  6382. {
  6383. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6384. if (SessionData->Link.IsEmpty())
  6385. {
  6386. if (SessionData->HasAnySessionPassword())
  6387. {
  6388. AnyNonStoredSessionWithPassword = true;
  6389. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6390. {
  6391. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6392. }
  6393. }
  6394. if (!SameText(SessionData->UserName, AnonymousUserName))
  6395. {
  6396. AllNonStoredSessionsAnonymous = false;
  6397. }
  6398. }
  6399. }
  6400. bool SavePasswords;
  6401. bool * PSavePasswords;
  6402. bool NotRecommendedSavingPasswords =
  6403. !CustomWinConfiguration->UseMasterPassword &&
  6404. !AllNonStoredSessionsAnonymous;
  6405. if (Configuration->DisablePasswordStoring ||
  6406. !AnyNonStoredSessionWithPassword)
  6407. {
  6408. PSavePasswords = NULL;
  6409. SavePasswords = false;
  6410. }
  6411. else
  6412. {
  6413. PSavePasswords = &SavePasswords;
  6414. SavePasswords =
  6415. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6416. !NotRecommendedSavingPasswords;
  6417. }
  6418. UnicodeString Name = WorkspaceName();
  6419. bool CreateShortcut = false;
  6420. bool Result =
  6421. DoSaveWorkspaceDialog(
  6422. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6423. EnableAutoSave);
  6424. if (Result)
  6425. {
  6426. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6427. if (CreateShortcut)
  6428. {
  6429. TOperationVisualizer Visualizer;
  6430. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6431. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6432. }
  6433. if (EnableAutoSave)
  6434. {
  6435. WinConfiguration->AutoSaveWorkspace = true;
  6436. WinConfiguration->AutoWorkspace = Name;
  6437. if (PSavePasswords != NULL)
  6438. {
  6439. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6440. }
  6441. }
  6442. }
  6443. return Result;
  6444. }
  6445. //---------------------------------------------------------------------------
  6446. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6447. {
  6448. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6449. DebugAssert(Session == ManagedSession);
  6450. if (!IsLocalBrowserMode())
  6451. {
  6452. SAFE_DESTROY(Session->RemoteExplorerState);
  6453. if (WinConfiguration->PreservePanelState)
  6454. {
  6455. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6456. }
  6457. }
  6458. UpdateSessionData(Session->StateData);
  6459. }
  6460. //---------------------------------------------------------------------------
  6461. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6462. {
  6463. // Keep in sync with TSessionData::CopyStateData
  6464. DebugAssert(Data != NULL);
  6465. // This is inconsistent with how color (for example) is handled.
  6466. Data->Name = ManagedSession->SessionData->Name;
  6467. if (!IsLocalBrowserMode())
  6468. {
  6469. // cannot use RemoteDirView->Path, because it is empty if connection
  6470. // was already closed
  6471. // also only peek, we may not be connected at all atm
  6472. // so make sure we do not try retrieving current directory from the server
  6473. // (particularly with FTP)
  6474. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6475. if (!ACurrentDirectory.IsEmpty())
  6476. {
  6477. Data->RemoteDirectory = ACurrentDirectory;
  6478. }
  6479. }
  6480. Data->Color = SessionColor;
  6481. }
  6482. //---------------------------------------------------------------------------
  6483. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6484. {
  6485. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6486. DebugAssert(Toolbar != NULL);
  6487. for (int i = 0; i < Toolbar->Items->Count; i++)
  6488. {
  6489. TTBXCustomDropDownItem * DropDownItem;
  6490. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6491. if (DropDownItem != NULL)
  6492. {
  6493. ToolbarItemResize(DropDownItem,
  6494. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6495. Toolbar->NonClientWidth);
  6496. break;
  6497. }
  6498. }
  6499. }
  6500. //---------------------------------------------------------------------------
  6501. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6502. {
  6503. Item->EditWidth = Width;
  6504. }
  6505. //---------------------------------------------------------------------------
  6506. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6507. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6508. {
  6509. for (int i = 0; i < Toolbar->Items->Count; i++)
  6510. {
  6511. TTBXCustomDropDownItem * DropDownItem;
  6512. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6513. if (DropDownItem != NULL)
  6514. {
  6515. ASize.x -= DropDownItem->EditWidth;
  6516. TControl * Control = this;
  6517. ASize.x += ScaleByTextHeight(Control, 50) /* minimal combo width */;
  6518. }
  6519. }
  6520. }
  6521. //---------------------------------------------------------------------------
  6522. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6523. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6524. {
  6525. if (WinConfiguration->DDWarnLackOfTempSpace)
  6526. {
  6527. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6528. if (!ADrive.IsEmpty())
  6529. {
  6530. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6531. DebugAssert(RequiredSpace >= 0);
  6532. __int64 RequiredWithReserve;
  6533. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6534. if (FreeSpace < RequiredWithReserve)
  6535. {
  6536. unsigned int Result;
  6537. TMessageParams Params(mpNeverAskAgainCheck);
  6538. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6539. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6540. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6541. if (Result == qaNeverAskAgain)
  6542. {
  6543. WinConfiguration->DDWarnLackOfTempSpace = false;
  6544. }
  6545. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6546. }
  6547. }
  6548. }
  6549. }
  6550. //---------------------------------------------------------------------------
  6551. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6552. {
  6553. DoOpenDirectoryDialog(odAddBookmark, Side);
  6554. }
  6555. //---------------------------------------------------------------------------
  6556. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6557. {
  6558. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6559. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6560. try
  6561. {
  6562. TCustomDirView * DView = DirView(Side);
  6563. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6564. {
  6565. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6566. }
  6567. }
  6568. catch (...)
  6569. {
  6570. delete VisitedDirectories;
  6571. throw;
  6572. }
  6573. return VisitedDirectories;
  6574. }
  6575. //---------------------------------------------------------------------------
  6576. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6577. TOpenDirectoryMode Mode, TOperationSide Side)
  6578. {
  6579. bool Continue = true;
  6580. if (Mode == odAddBookmark)
  6581. {
  6582. TMessageParams Params(mpNeverAskAgainCheck);
  6583. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6584. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6585. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6586. unsigned int Answer =
  6587. MessageDialog(Message,
  6588. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6589. if (Answer == qaNeverAskAgain)
  6590. {
  6591. Continue = true;
  6592. WinConfiguration->UseSharedBookmarks = true;
  6593. }
  6594. else if (Answer == qaOK)
  6595. {
  6596. Continue = true;
  6597. WinConfiguration->UseSharedBookmarks = false;
  6598. }
  6599. else
  6600. {
  6601. Continue = false;
  6602. }
  6603. }
  6604. if (Continue)
  6605. {
  6606. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6607. try
  6608. {
  6609. UnicodeString Name = DirView(Side)->PathName;
  6610. bool Repeat;
  6611. do
  6612. {
  6613. Repeat = false;
  6614. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6615. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6616. // do not allow switching to location profiles,
  6617. // if we are not connected
  6618. HasDirView[osLocal] && IsAvailableTerminal(Terminal)))
  6619. {
  6620. TWindowLock Lock(this);
  6621. if (!TryOpenDirectory(Side, Name))
  6622. {
  6623. Repeat = true;
  6624. Mode = odBrowse;
  6625. }
  6626. }
  6627. }
  6628. while (Repeat);
  6629. }
  6630. __finally
  6631. {
  6632. delete VisitedDirectories;
  6633. }
  6634. }
  6635. }
  6636. //---------------------------------------------------------------------------
  6637. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6638. {
  6639. DebugAssert(!Terminal->CommandSessionOpened);
  6640. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6641. }
  6642. //---------------------------------------------------------------------------
  6643. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6644. {
  6645. bool Result = Terminal->IsCapable[Capability] ||
  6646. Terminal->CommandSessionOpened;
  6647. if (!Result)
  6648. {
  6649. // We might get here for example when "checksum" synchronization is requested from command-line
  6650. // on server that supports neither checksum nor shell
  6651. if (!Terminal->IsCapable[fcSecondaryShell])
  6652. {
  6653. NotSupported();
  6654. }
  6655. else if (!GUIConfiguration->ConfirmCommandSession)
  6656. {
  6657. Result = true;
  6658. }
  6659. else
  6660. {
  6661. TMessageParams Params(mpNeverAskAgainCheck);
  6662. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6663. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6664. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6665. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6666. if (Answer == qaNeverAskAgain)
  6667. {
  6668. GUIConfiguration->ConfirmCommandSession = false;
  6669. Result = true;
  6670. }
  6671. else if (Answer == qaOK)
  6672. {
  6673. Result = true;
  6674. }
  6675. }
  6676. if (Result)
  6677. {
  6678. Result = CommandSessionFallback();
  6679. }
  6680. }
  6681. return Result;
  6682. }
  6683. //---------------------------------------------------------------------------
  6684. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6685. {
  6686. if (EnsureCommandSessionFallback(fcAnyCommand))
  6687. {
  6688. DoConsoleDialog(Terminal, Command);
  6689. }
  6690. }
  6691. //---------------------------------------------------------------------------
  6692. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6693. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6694. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6695. {
  6696. if (!IsSideLocalBrowser(osRemote) &&
  6697. IsFileControl(DropSourceControl, osRemote) &&
  6698. (FDDExtMapFile != NULL))
  6699. {
  6700. Accept = true;
  6701. }
  6702. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6703. DebugAssert(FDDTargetControl != NULL);
  6704. }
  6705. //---------------------------------------------------------------------------
  6706. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6707. _di_IDataObject DataObj, int KeyState,
  6708. const TPoint & Point, int & Effect, bool & Accept)
  6709. {
  6710. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6711. }
  6712. //---------------------------------------------------------------------------
  6713. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6714. _di_IDataObject DataObj, int KeyState,
  6715. const TPoint & Point, int & Effect, bool & Accept)
  6716. {
  6717. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6718. }
  6719. //---------------------------------------------------------------------------
  6720. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6721. TObject * Sender)
  6722. {
  6723. DebugUsedParam(Sender);
  6724. DebugAssert(FDDTargetControl == Sender);
  6725. FDDTargetControl = NULL;
  6726. }
  6727. //---------------------------------------------------------------------------
  6728. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave(int)
  6729. {
  6730. FileControlDDDragLeave(SessionsPageControl);
  6731. }
  6732. //---------------------------------------------------------------------------
  6733. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave(int)
  6734. {
  6735. FileControlDDDragLeave(QueueView3);
  6736. }
  6737. //---------------------------------------------------------------------------
  6738. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6739. {
  6740. DebugAssert(!IsSideLocalBrowser(Side));
  6741. DebugUsedParam(Side);
  6742. bool Edit = false;
  6743. TRemoteFile * File = NULL;
  6744. UnicodeString FileName;
  6745. UnicodeString PointTo;
  6746. bool SymbolicLink = true;
  6747. if (RemoteDirView->ItemFocused)
  6748. {
  6749. DebugAssert(RemoteDirView->ItemFocused->Data);
  6750. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6751. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6752. if (Edit)
  6753. {
  6754. FileName = File->FileName;
  6755. PointTo = File->LinkTo;
  6756. }
  6757. else if (!File->IsParentDirectory)
  6758. {
  6759. PointTo = File->FileName;
  6760. }
  6761. }
  6762. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6763. Terminal->IsCapable[fcHardLink]))
  6764. {
  6765. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6766. if (Edit)
  6767. {
  6768. DebugAssert(File->FileName == FileName);
  6769. int Params = dfNoRecursive;
  6770. Terminal->ExceptionOnFail = true;
  6771. try
  6772. {
  6773. Terminal->DeleteFile(L"", File, &Params);
  6774. }
  6775. __finally
  6776. {
  6777. Terminal->ExceptionOnFail = false;
  6778. }
  6779. }
  6780. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6781. }
  6782. }
  6783. //---------------------------------------------------------------------------
  6784. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6785. {
  6786. return
  6787. (IsSideLocalBrowser(Side) ||
  6788. (HasAvailableTerminal() &&
  6789. Terminal->ResolvingSymlinks &&
  6790. Terminal->IsCapable[fcSymbolicLink]));
  6791. }
  6792. //---------------------------------------------------------------------------
  6793. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6794. {
  6795. return
  6796. !IsSideLocalBrowser(FCurrentSide) &&
  6797. (RemoteDirView->ItemFocused != NULL) &&
  6798. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6799. Terminal->SessionData->ResolveSymlinks;
  6800. }
  6801. //---------------------------------------------------------------------------
  6802. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6803. {
  6804. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6805. FForceExecution = true;
  6806. try
  6807. {
  6808. DirView(osCurrent)->ExecuteCurrentFile();
  6809. }
  6810. __finally
  6811. {
  6812. FForceExecution = false;
  6813. }
  6814. }
  6815. //---------------------------------------------------------------------------
  6816. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6817. {
  6818. TEditorData ExternalEditor;
  6819. ExternalEditor.Editor = edExternal;
  6820. bool Remember = false;
  6821. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6822. {
  6823. if (Remember)
  6824. {
  6825. TEditorList * EditorList = new TEditorList;
  6826. try
  6827. {
  6828. *EditorList = *WinConfiguration->EditorList;
  6829. bool Found = false;
  6830. int i = 0;
  6831. while (!Found && (i < EditorList->Count))
  6832. {
  6833. const TEditorPreferences * Editor = EditorList->Editors[i];
  6834. if ((Editor->Data->Editor == edExternal) &&
  6835. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6836. {
  6837. Found = true;
  6838. }
  6839. i++;
  6840. }
  6841. if (!Found)
  6842. {
  6843. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6844. WinConfiguration->EditorList = EditorList;
  6845. }
  6846. }
  6847. __finally
  6848. {
  6849. delete EditorList;
  6850. }
  6851. }
  6852. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6853. }
  6854. }
  6855. //---------------------------------------------------------------------------
  6856. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6857. {
  6858. if (FFileFindTerminal == ATerminal)
  6859. {
  6860. FFileFindTerminal = NULL;
  6861. HideFileFindDialog();
  6862. }
  6863. if (FClipboardTerminal == ATerminal)
  6864. {
  6865. ClipboardClear(); // implies ClipboardStop
  6866. }
  6867. if ((FOnSynchronizeAbort != NULL) &&
  6868. (ATerminal == FManagedSession))
  6869. {
  6870. FOnSynchronizeAbort(NULL);
  6871. }
  6872. }
  6873. //---------------------------------------------------------------------------
  6874. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6875. {
  6876. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6877. DetachTerminal(Sender);
  6878. }
  6879. //---------------------------------------------------------------------------
  6880. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6881. const UnicodeString FileName, TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6882. {
  6883. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6884. if (Data->Terminal == Terminal)
  6885. {
  6886. Data->Terminal = ATerminal;
  6887. }
  6888. }
  6889. //---------------------------------------------------------------------------
  6890. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6891. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6892. {
  6893. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6894. DebugAssert(Terminal != NULL);
  6895. if (Data->Terminal == Terminal)
  6896. {
  6897. Data->Terminal = NULL;
  6898. }
  6899. }
  6900. //---------------------------------------------------------------------------
  6901. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6902. {
  6903. return NULL;
  6904. }
  6905. //---------------------------------------------------------------------------
  6906. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6907. {
  6908. UpdateControls();
  6909. SessionColor = TColor(0);
  6910. UpdateRemotePathComboBox(false);
  6911. NeedSession(false);
  6912. }
  6913. //---------------------------------------------------------------------------
  6914. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6915. {
  6916. try
  6917. {
  6918. // Cache, as the login dialog can change its value.
  6919. // See also DoShow. Also see TTerminalManager::NewSession.
  6920. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6921. try
  6922. {
  6923. if (ShowLogin)
  6924. {
  6925. bool ReloadSessions = !Startup;
  6926. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6927. }
  6928. }
  6929. __finally
  6930. {
  6931. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6932. // (so there was no chance for the user to open any session yet)
  6933. if ((ShowLogin || !Startup) &&
  6934. !WinConfiguration->KeepOpenWhenNoSession &&
  6935. // this rules out the implicit Commander's local-local browser
  6936. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6937. {
  6938. TerminateApplication();
  6939. }
  6940. }
  6941. }
  6942. catch (EAbort &)
  6943. {
  6944. // swallow
  6945. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6946. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6947. }
  6948. }
  6949. //---------------------------------------------------------------------------
  6950. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6951. {
  6952. TTerminalManager * Manager = TTerminalManager::Instance();
  6953. DebugAssert(!Manager->Updating);
  6954. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6955. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6956. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6957. SessionsPageControl->LockDrawing();
  6958. try
  6959. {
  6960. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6961. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6962. {
  6963. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6964. }
  6965. for (int Index = 0; Index <= Manager->Count; Index++)
  6966. {
  6967. TThemeTabSheet * TabSheet;
  6968. if (Index >= SessionsPageControl->PageCount)
  6969. {
  6970. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6971. TabSheet->PageControl = SessionsPageControl;
  6972. }
  6973. else
  6974. {
  6975. TabSheet = SessionsPageControl->Pages[Index];
  6976. }
  6977. bool IsSessionTab = (Index < Manager->Count);
  6978. if (IsSessionTab)
  6979. {
  6980. TTerminal * Terminal = Manager->Sessions[Index];
  6981. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6982. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  6983. UpdateSessionTab(TabSheet);
  6984. }
  6985. else
  6986. {
  6987. TabSheet->Tag = 0; // not really needed
  6988. TabSheet->Shadowed = false;
  6989. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6990. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  6991. // 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)
  6992. UpdateNewTabTab();
  6993. }
  6994. }
  6995. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6996. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6997. {
  6998. SessionsPageControl->UpdateTabsCaptionTruncation();
  6999. }
  7000. }
  7001. __finally
  7002. {
  7003. SessionsPageControl->UnlockDrawing();
  7004. }
  7005. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  7006. }
  7007. //---------------------------------------------------------------------------
  7008. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  7009. {
  7010. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  7011. }
  7012. //---------------------------------------------------------------------------
  7013. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  7014. {
  7015. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  7016. }
  7017. //---------------------------------------------------------------------------
  7018. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  7019. {
  7020. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  7021. }
  7022. //---------------------------------------------------------------------------
  7023. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  7024. {
  7025. TThemeTabSheet * TabSheet = GetNewTabTab();
  7026. UnicodeString TabCaption;
  7027. if (WinConfiguration->SelectiveToolbarText)
  7028. {
  7029. TabCaption = GetNewTabTabCaption();
  7030. }
  7031. TabSheet->BaseCaption = TabCaption;
  7032. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  7033. }
  7034. //---------------------------------------------------------------------------
  7035. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  7036. {
  7037. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  7038. }
  7039. //---------------------------------------------------------------------------
  7040. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  7041. {
  7042. DebugFail();
  7043. return UnicodeString();
  7044. }
  7045. //---------------------------------------------------------------------------
  7046. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  7047. {
  7048. if (DebugAlwaysTrue(TabSheet != NULL))
  7049. {
  7050. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  7051. if (DebugAlwaysTrue(ASession != NULL))
  7052. {
  7053. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  7054. if (ASession->LocalBrowser)
  7055. {
  7056. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  7057. }
  7058. else
  7059. {
  7060. TabSheet->ImageIndex = AddSessionColor(Color);
  7061. }
  7062. TTerminalManager * Manager = TTerminalManager::Instance();
  7063. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  7064. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  7065. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  7066. }
  7067. }
  7068. }
  7069. //---------------------------------------------------------------------------
  7070. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  7071. {
  7072. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  7073. }
  7074. //---------------------------------------------------------------------------
  7075. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  7076. {
  7077. DebugAssert(SessionsPageControl->ActivePage != NULL);
  7078. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  7079. bool Result = (Session != NULL);
  7080. if (Result)
  7081. {
  7082. TTerminalManager::Instance()->ActiveSession = Session;
  7083. }
  7084. else
  7085. {
  7086. try
  7087. {
  7088. NewTab();
  7089. }
  7090. __finally
  7091. {
  7092. SessionListChanged();
  7093. }
  7094. FSessionsPageControlNewTabTime = Now();
  7095. }
  7096. return Result;
  7097. }
  7098. //---------------------------------------------------------------------------
  7099. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  7100. {
  7101. TWindowLock Lock(this);
  7102. SessionTabSwitched();
  7103. }
  7104. //---------------------------------------------------------------------------
  7105. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  7106. {
  7107. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  7108. DebugAssert(TransferList != NULL);
  7109. UnicodeString Name;
  7110. if (TransferList->ItemIndex <= 0)
  7111. {
  7112. Name = L"";
  7113. }
  7114. else
  7115. {
  7116. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7117. }
  7118. if (FCopyParamAutoSelected.IsEmpty())
  7119. {
  7120. // if previous preset was not autoselected, make new preset the "default"
  7121. FCopyParamDefault = Name;
  7122. }
  7123. GUIConfiguration->CopyParamCurrent = Name;
  7124. }
  7125. //---------------------------------------------------------------------------
  7126. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7127. {
  7128. // sanity check
  7129. bool ExistingPreset =
  7130. (FTransferListHoverIndex >= 0) &&
  7131. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7132. DebugAssert(ExistingPreset);
  7133. if (ExistingPreset)
  7134. {
  7135. HDC DC = GetDC(0);
  7136. TCanvas * Canvas = new TCanvas();
  7137. try
  7138. {
  7139. Canvas->Handle = DC;
  7140. Canvas->Font = GetToolbarFont(this);
  7141. UnicodeString Name;
  7142. if (FTransferListHoverIndex == 0)
  7143. {
  7144. Name = L"";
  7145. }
  7146. else
  7147. {
  7148. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7149. }
  7150. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7151. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7152. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7153. static_cast<TObject*>(GetComponent(fcTransferList)));
  7154. UnicodeString InfoStr =
  7155. GUIConfiguration->CopyParamPreset[Name].
  7156. GetInfoStr(L"; ",
  7157. FLAGMASK(HasAvailableTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7158. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7159. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7160. {
  7161. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7162. {
  7163. InfoStr.SetLength(InfoStr.Length() - 1);
  7164. }
  7165. InfoStr += Ellipsis;
  7166. }
  7167. // UpdateCaption does not cause invalidation of whole submenu, while
  7168. // setting Caption property does.
  7169. // also it probably does not resize the label, even if necessary
  7170. // (we do not want that anyway)
  7171. TransferLabel->UpdateCaption(InfoStr);
  7172. }
  7173. __finally
  7174. {
  7175. Canvas->Handle = NULL;
  7176. ReleaseDC(0, DC);
  7177. delete Canvas;
  7178. }
  7179. }
  7180. }
  7181. //---------------------------------------------------------------------------
  7182. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7183. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7184. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7185. {
  7186. if (FTransferListHoverIndex != AHoverIndex)
  7187. {
  7188. FTransferListHoverIndex = AHoverIndex;
  7189. UpdateTransferLabel();
  7190. }
  7191. }
  7192. //---------------------------------------------------------------------------
  7193. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7194. {
  7195. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7196. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7197. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7198. {
  7199. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7200. {
  7201. if (!NonVisualDataModule->Busy)
  7202. {
  7203. OpenDirectory(GetSide(osCurrent));
  7204. }
  7205. Message.Result = 1;
  7206. }
  7207. else
  7208. {
  7209. TForm::Dispatch(&Message);
  7210. }
  7211. }
  7212. else
  7213. {
  7214. TForm::Dispatch(&Message);
  7215. }
  7216. }
  7217. //---------------------------------------------------------------------------
  7218. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7219. {
  7220. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7221. if ((FIgnoreNextDialogChar != 0) &&
  7222. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7223. {
  7224. Message.Result = 1;
  7225. }
  7226. else
  7227. {
  7228. TForm::Dispatch(&Message);
  7229. }
  7230. FIgnoreNextDialogChar = 0;
  7231. }
  7232. //---------------------------------------------------------------------------
  7233. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7234. {
  7235. // The four low-order bits are used internally by Windows
  7236. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7237. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7238. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7239. // 61730 - restore thru double click - undocumented
  7240. // 61490 - maximize thru double click - undocumented
  7241. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7242. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7243. {
  7244. SysResizing(Cmd);
  7245. }
  7246. TForm::Dispatch(&Message);
  7247. }
  7248. //---------------------------------------------------------------------------
  7249. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7250. {
  7251. AppLog(L"Windows session end query");
  7252. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7253. // Also there no point returning TRUE as we are not able to
  7254. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7255. // Hence the process termination might be safer :)
  7256. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7257. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7258. {
  7259. Message.Result = FALSE;
  7260. }
  7261. else
  7262. {
  7263. Message.Result = TRUE;
  7264. }
  7265. // Do not call default handling as that triggers OnCloseQuery,
  7266. // where our implementation will popup confirmation dialogs, what we do not want,
  7267. // as per Vista guidelines:
  7268. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7269. }
  7270. //---------------------------------------------------------------------------
  7271. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7272. {
  7273. AppLog(L"Windows session end");
  7274. if (Message.EndSession && IsApplicationMinimized())
  7275. {
  7276. // WORKAROUND
  7277. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7278. // when it receives WM_ENDSESSION,
  7279. // but that sometimes (particularly when application is minimized) cause crashes.
  7280. // Crash popups message that blocks log off.
  7281. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7282. // so we call ExitProcess() immediately, not even trying to cleanup.
  7283. // It still causes beep, so there's likely some popup, but it does not block
  7284. // log off.
  7285. ExitProcess(0);
  7286. }
  7287. TForm::Dispatch(&Message);
  7288. }
  7289. #ifdef _DEBUG
  7290. //---------------------------------------------------------------------------
  7291. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7292. {
  7293. TForm::Dispatch(&Message);
  7294. }
  7295. #endif
  7296. //---------------------------------------------------------------------------
  7297. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7298. {
  7299. }
  7300. //---------------------------------------------------------------------------
  7301. void __fastcall TCustomScpExplorerForm::DoShow()
  7302. {
  7303. // Called from TCustomScpExplorerForm::CMShowingChanged
  7304. // only now are the controls resized finally, so the size constraints
  7305. // will not conflict with possibly very small window size
  7306. RestoreFormParams();
  7307. // This indicates that the form was rescaled after parameters were loaded and
  7308. // as most probably the parameters were actually saved with the current form scaling
  7309. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7310. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7311. // and no rounding problems will occur.
  7312. // See also RestoreForm.
  7313. // (we should be safe to call RestoreParams unconditionally)
  7314. if (PixelsPerInch != Screen->PixelsPerInch)
  7315. {
  7316. RestoreParams();
  7317. }
  7318. FixControlsPlacement();
  7319. if (Position == poDefaultPosOnly)
  7320. {
  7321. CutFormToDesktop(this);
  7322. }
  7323. TForm::DoShow();
  7324. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7325. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7326. // This was previously in NeedSession, where other related code is.
  7327. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7328. // unpleasantly shows briefly.
  7329. if ((ManagedSession == NULL) &&
  7330. !WinConfiguration->ShowLoginWhenNoSession &&
  7331. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7332. // This detects if workspace was saved the last time the main widow was closed
  7333. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7334. {
  7335. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7336. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7337. }
  7338. // Before main window displays
  7339. if (ManagedSession == NULL)
  7340. {
  7341. StartingWithoutSession();
  7342. }
  7343. UpdatePixelsPerInchMainWindowCounter();
  7344. FShowing = true;
  7345. }
  7346. //---------------------------------------------------------------------------
  7347. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7348. {
  7349. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7350. }
  7351. //---------------------------------------------------------------------------
  7352. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7353. {
  7354. SessionListChanged();
  7355. InitStatusBar();
  7356. UpdateControls();
  7357. }
  7358. //---------------------------------------------------------------------------
  7359. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7360. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7361. TNotifyEvent OnBalloonClick, TObject * UserData)
  7362. {
  7363. bool Do;
  7364. UnicodeString Message;
  7365. if (E == NULL)
  7366. {
  7367. Message = Str;
  7368. Do = true;
  7369. }
  7370. else
  7371. {
  7372. Do = ExceptionMessage(E, Message);
  7373. }
  7374. if (Do && WinConfiguration->BalloonNotifications)
  7375. {
  7376. UnicodeString Title;
  7377. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7378. {
  7379. Message = TrimLeft(Message);
  7380. }
  7381. else
  7382. {
  7383. Message = UnformatMessage(Message);
  7384. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7385. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7386. Title = LoadResourceString(Captions[Type]);
  7387. if (Terminal != NULL)
  7388. {
  7389. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7390. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7391. }
  7392. }
  7393. if (Seconds == 0)
  7394. {
  7395. Seconds = WinConfiguration->NotificationsTimeout;
  7396. }
  7397. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7398. }
  7399. }
  7400. //---------------------------------------------------------------------------
  7401. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7402. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7403. UnicodeString HelpKeyword, const TMessageParams * Params,
  7404. TTerminal * Terminal)
  7405. {
  7406. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7407. (FOnFeedSynchronizeError != NULL)) &&
  7408. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7409. {
  7410. if (FOnFeedSynchronizeError != NULL)
  7411. {
  7412. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7413. }
  7414. else
  7415. {
  7416. DebugAssert(FErrorList != NULL);
  7417. TStringList * MoreMessagesCopy = NULL;
  7418. if (MoreMessages)
  7419. {
  7420. MoreMessagesCopy = new TStringList();
  7421. MoreMessagesCopy->Assign(MoreMessages);
  7422. }
  7423. FErrorList->AddObject(Message, MoreMessagesCopy);
  7424. }
  7425. PopupTrayBalloon(Terminal, Message, Type);
  7426. return ContinueAnswer(Answers);
  7427. }
  7428. else
  7429. {
  7430. bool UseBalloon = FTrayIcon->Visible;
  7431. if (UseBalloon)
  7432. {
  7433. PopupTrayBalloon(Terminal, Message, Type);
  7434. }
  7435. unsigned int Result;
  7436. try
  7437. {
  7438. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7439. }
  7440. __finally
  7441. {
  7442. // cancel only balloon we popped up, otherwise we may cancel notification
  7443. // balloon that was there before the message dialog
  7444. // (such as "dd confirmation opt in balloon)
  7445. if (UseBalloon)
  7446. {
  7447. FTrayIcon->CancelBalloon();
  7448. }
  7449. }
  7450. return Result;
  7451. }
  7452. }
  7453. //---------------------------------------------------------------------------
  7454. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7455. TTerminal * Terminal, Exception * E)
  7456. {
  7457. if (FTrayIcon->Visible)
  7458. {
  7459. PopupTrayBalloon(Terminal, L"", qtError, E);
  7460. }
  7461. // particularly prevent opening new session from jump list,
  7462. // while exception is shown
  7463. NonVisualDataModule->StartBusy();
  7464. try
  7465. {
  7466. ShowExtendedExceptionEx(Terminal, E);
  7467. }
  7468. __finally
  7469. {
  7470. NonVisualDataModule->EndBusy();
  7471. FTrayIcon->CancelBalloon();
  7472. }
  7473. }
  7474. //---------------------------------------------------------------------------
  7475. void __fastcall TCustomScpExplorerForm::SessionReady()
  7476. {
  7477. InitStatusBar();
  7478. // cannot rely on active page being page for active terminal,
  7479. // as it can happen that active page is the "new session" page
  7480. // (e.g. when reconnecting active terminal, while login dialog
  7481. // invoked from "new session" page is modal)
  7482. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7483. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7484. }
  7485. //---------------------------------------------------------------------------
  7486. void TCustomScpExplorerForm::InactiveTerminalNotify(
  7487. TManagedTerminal * Terminal, const UnicodeString & Message, TQueryType Type, Exception * E)
  7488. {
  7489. Notify(Terminal, Message, Type, false, NULL, NULL, E);
  7490. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7491. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7492. {
  7493. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7494. }
  7495. }
  7496. //---------------------------------------------------------------------------
  7497. void TCustomScpExplorerForm::Notify(
  7498. TManagedTerminal * Terminal, const UnicodeString & AMessage, TQueryType Type,
  7499. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7500. {
  7501. UnicodeString Message = AMessage;
  7502. if ((E == NULL) ||
  7503. ExceptionMessage(E, Message))
  7504. {
  7505. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7506. if (Important)
  7507. {
  7508. Seconds *= 5;
  7509. }
  7510. UnicodeString NoteMessage(UnformatMessage(Message));
  7511. if (Terminal != NULL)
  7512. {
  7513. NoteMessage = TTerminalManager::Instance()->FormatTerminalNoteMessage(Terminal, NoteMessage);
  7514. }
  7515. if (WinConfiguration->BalloonNotifications)
  7516. {
  7517. AddNote(NoteMessage);
  7518. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7519. }
  7520. else
  7521. {
  7522. FlashOnBackground();
  7523. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7524. }
  7525. }
  7526. }
  7527. //---------------------------------------------------------------------------
  7528. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7529. {
  7530. RestoreApp();
  7531. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7532. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7533. !NonVisualDataModule->Busy)
  7534. {
  7535. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7536. TTerminalManager::Instance()->ActiveSession = Terminal;
  7537. if (!ComponentVisible[fcQueueView])
  7538. {
  7539. ToggleQueueVisibility();
  7540. GoToQueue();
  7541. }
  7542. }
  7543. }
  7544. //---------------------------------------------------------------------------
  7545. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7546. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7547. {
  7548. UnicodeString Message;
  7549. TNotifyEvent OnClick = NULL;
  7550. TObject * UserData = NULL;
  7551. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7552. switch (Event)
  7553. {
  7554. case qeEmptyButMonitored:
  7555. if ((ATerminal != Terminal) || QueueInvisible)
  7556. {
  7557. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7558. OnClick = QueueEmptyNoteClicked;
  7559. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7560. TerminalNoteData->Terminal = ATerminal;
  7561. UserData = TerminalNoteData;
  7562. }
  7563. break;
  7564. case qeEmpty:
  7565. OperationComplete(ATerminal->QueueOperationStart);
  7566. break;
  7567. case qePendingUserAction:
  7568. if ((ATerminal != Terminal) ||
  7569. (QueueInvisible && !IsQueueAutoPopup()))
  7570. {
  7571. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7572. }
  7573. break;
  7574. default:
  7575. DebugFail();
  7576. }
  7577. if (!Message.IsEmpty())
  7578. {
  7579. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7580. }
  7581. }
  7582. //---------------------------------------------------------------------------
  7583. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7584. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7585. {
  7586. if (FDDExtMapFile != NULL)
  7587. {
  7588. CloseHandle(FDDExtMapFile);
  7589. FDDExtMapFile = NULL;
  7590. }
  7591. if (WinConfiguration->DDFakeFile)
  7592. {
  7593. DDFakeFileInitDrag(FileList, Created);
  7594. }
  7595. }
  7596. //---------------------------------------------------------------------------
  7597. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7598. {
  7599. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7600. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7601. {
  7602. FFakeFileDropTarget = FileName;
  7603. }
  7604. }
  7605. //---------------------------------------------------------------------------
  7606. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7607. {
  7608. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7609. if (!ForceDirectories(ApiPath(Result)))
  7610. {
  7611. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7612. }
  7613. FileSetAttr(ApiPath(Result), faHidden);
  7614. return Result;
  7615. }
  7616. //---------------------------------------------------------------------------
  7617. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7618. bool & Created)
  7619. {
  7620. FFakeFileDropTarget = UnicodeString();
  7621. FDragFakeDirectory = CreateFakeTransferDirectory();
  7622. FileList->AddItem(NULL, FDragFakeDirectory);
  7623. Created = true;
  7624. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7625. {
  7626. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7627. }
  7628. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7629. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7630. {
  7631. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7632. TDragExtCommStruct* CommStruct;
  7633. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7634. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7635. DebugAssert(CommStruct != NULL);
  7636. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7637. CommStruct->Dragging = true;
  7638. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7639. LENOF(CommStruct->DropDest));
  7640. NULL_TERMINATE(CommStruct->DropDest);
  7641. UnmapViewOfFile(CommStruct);
  7642. }
  7643. }
  7644. //---------------------------------------------------------------------------
  7645. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7646. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7647. {
  7648. bool Result;
  7649. DebugAssert(!IsLocalBrowserMode());
  7650. if (Sender == RemoteDirView)
  7651. {
  7652. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7653. }
  7654. else
  7655. {
  7656. DebugAssert(Sender == RemoteDriveView);
  7657. TStrings * FileList = RemoteDriveView->DragFileList();
  7658. try
  7659. {
  7660. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7661. }
  7662. __finally
  7663. {
  7664. delete FileList;
  7665. }
  7666. }
  7667. if (FDDTargetControl == RemoteDriveView)
  7668. {
  7669. RemoteDriveView->UpdateDropTarget();
  7670. }
  7671. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7672. // or from tree view to dir view.
  7673. // foMove happens when file/dir is dragged from remote tree view outside of
  7674. // application via dragex
  7675. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7676. (DropSourceControl == RemoteDriveView))
  7677. {
  7678. RemoteDriveView->UpdateDropSource();
  7679. }
  7680. return Result;
  7681. }
  7682. //---------------------------------------------------------------------------
  7683. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7684. {
  7685. DebugAssert(!IsLocalBrowserMode());
  7686. // This also handles drops of remote files to queue.
  7687. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7688. SAFE_DESTROY(FDDFileList);
  7689. if (!FFakeFileDropTarget.IsEmpty())
  7690. {
  7691. RemoveDir(ApiPath(FFakeFileDropTarget));
  7692. }
  7693. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7694. {
  7695. try
  7696. {
  7697. TDragResult DDResult = (Sender == RemoteDirView) ?
  7698. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7699. // Focus is moved to the target application,
  7700. // but as we are going to present the UI, we need to steal the focus back.
  7701. // This most likely won't work though (windows does not allow application
  7702. // to steal focus most of the time)
  7703. Application->BringToFront();
  7704. // On older version of Windows we never got drMove here, see also comment below.
  7705. // On Windows 10, we get the "move".
  7706. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7707. {
  7708. UnicodeString TargetDirectory;
  7709. TFileOperation Operation;
  7710. // drInvalid may mean drMove, see comment below
  7711. switch (DDResult)
  7712. {
  7713. case drCopy:
  7714. Operation = foCopy;
  7715. break;
  7716. case drMove:
  7717. Operation = foMove;
  7718. break;
  7719. default:
  7720. DebugFail();
  7721. case drInvalid:
  7722. // prefer "copy" for safety
  7723. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7724. break;
  7725. }
  7726. TTransferOperationParam Param;
  7727. UnicodeString CounterName;
  7728. bool ForceQueue;
  7729. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7730. {
  7731. // we get drInvalid both if d&d was intercepted by ddext,
  7732. // and when users drops on no-drop location.
  7733. // we tell the difference by existence of response from ddext,
  7734. // so we ignore absence of response in this case
  7735. if (DDResult != drInvalid)
  7736. {
  7737. // here we know that the extension is installed,
  7738. // as it is checked as soon as drag&drop starts from
  7739. // RemoteFileControlDDCreateDragFileList
  7740. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7741. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7742. {
  7743. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7744. }
  7745. else
  7746. {
  7747. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7748. }
  7749. }
  7750. }
  7751. else
  7752. {
  7753. // download using fake file
  7754. Param.Temp = false;
  7755. Param.DragDrop = true;
  7756. if (ForceQueue)
  7757. {
  7758. Param.Queue = asOn;
  7759. }
  7760. if (Sender == RemoteDirView)
  7761. {
  7762. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7763. }
  7764. if (RemoteFileControlFileOperation(Sender, Operation,
  7765. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7766. {
  7767. Configuration->Usage->Inc(CounterName);
  7768. }
  7769. }
  7770. }
  7771. }
  7772. __finally
  7773. {
  7774. CloseHandle(FDDExtMapFile);
  7775. FDDExtMapFile = NULL;
  7776. delete FDragFakeMonitors;
  7777. FDragFakeMonitors = NULL;
  7778. RemoveDir(ApiPath(FDragFakeDirectory));
  7779. FDragFakeDirectory = L"";
  7780. FFakeFileDropTarget = UnicodeString();
  7781. }
  7782. }
  7783. if (FDragDropSshTerminate.get() != NULL)
  7784. {
  7785. FDragDropSshTerminate->Rethrow();
  7786. }
  7787. }
  7788. //---------------------------------------------------------------------------
  7789. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7790. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7791. {
  7792. // Remember drop effect so we know (when user drops files), if we copy or move
  7793. FLastDropEffect = dwEffect;
  7794. }
  7795. //---------------------------------------------------------------------------
  7796. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7797. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7798. {
  7799. bool Result;
  7800. if (FDDTargetControl == QueueView3)
  7801. {
  7802. Directory = DefaultDownloadTargetDirectory();
  7803. Result = true;
  7804. CounterName = L"DownloadsDragDropQueue";
  7805. ForceQueue = true;
  7806. }
  7807. else if (!FFakeFileDropTarget.IsEmpty())
  7808. {
  7809. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7810. Result = true;
  7811. ForceQueue = false;
  7812. CounterName = L"DownloadsDragDropFakeFile";
  7813. }
  7814. else
  7815. {
  7816. ForceQueue = false;
  7817. Enabled = false;
  7818. try
  7819. {
  7820. int Timer = 0;
  7821. Result = false;
  7822. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7823. {
  7824. {
  7825. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7826. TDragExtCommStruct* CommStruct;
  7827. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7828. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7829. DebugAssert(CommStruct != NULL);
  7830. Result = !CommStruct->Dragging;
  7831. if (Result)
  7832. {
  7833. Directory = ExtractFilePath(CommStruct->DropDest);
  7834. CounterName = L"DownloadsDragDropExternalExt";
  7835. }
  7836. UnmapViewOfFile(CommStruct);
  7837. }
  7838. if (!Result)
  7839. {
  7840. Sleep(50);
  7841. Timer += 50;
  7842. Application->ProcessMessages();
  7843. }
  7844. }
  7845. }
  7846. __finally
  7847. {
  7848. Enabled = true;
  7849. }
  7850. }
  7851. return Result;
  7852. }
  7853. //---------------------------------------------------------------------------
  7854. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7855. const UnicodeString TempDir, int SecDelay)
  7856. {
  7857. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7858. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7859. if (FDelayedDeletionTimer == NULL)
  7860. {
  7861. DebugAssert(HandleAllocated());
  7862. FDelayedDeletionTimer = new TTimer(this);
  7863. FDelayedDeletionTimer->Interval = 10000;
  7864. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7865. }
  7866. else
  7867. {
  7868. FDelayedDeletionTimer->Enabled = true;
  7869. }
  7870. }
  7871. //---------------------------------------------------------------------------
  7872. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7873. {
  7874. DebugAssert(FDelayedDeletionList != NULL);
  7875. TDateTime N = Now();
  7876. TDateTime Alert;
  7877. UnicodeString Directory;
  7878. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7879. {
  7880. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7881. if ((N >= Alert) || (Sender == NULL))
  7882. {
  7883. Directory = FDelayedDeletionList->Strings[Index];
  7884. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7885. {
  7886. FDelayedDeletionList->Delete(Index);
  7887. }
  7888. }
  7889. }
  7890. if (FDelayedDeletionList->Count == 0)
  7891. {
  7892. FDelayedDeletionTimer->Enabled = false;
  7893. }
  7894. }
  7895. //---------------------------------------------------------------------------
  7896. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7897. {
  7898. DebugAssert(!IsLocalBrowserMode());
  7899. if (IsFileControl(FDDTargetControl, osRemote) ||
  7900. (FDDTargetControl == SessionsPageControl))
  7901. {
  7902. TManagedTerminal * TargetTerminal = NULL;
  7903. TFileOperation Operation = foNone;
  7904. if (FDDTargetControl == SessionsPageControl)
  7905. {
  7906. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7907. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7908. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7909. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7910. if (IsAvailableTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7911. {
  7912. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7913. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7914. {
  7915. Operation = foRemoteMove;
  7916. }
  7917. else
  7918. {
  7919. Operation = foRemoteCopy;
  7920. }
  7921. }
  7922. }
  7923. else
  7924. {
  7925. if (FLastDropEffect == DROPEFFECT_MOVE)
  7926. {
  7927. Operation = foRemoteMove;
  7928. }
  7929. else if (FLastDropEffect == DROPEFFECT_COPY)
  7930. {
  7931. Operation = foRemoteCopy;
  7932. }
  7933. }
  7934. if (Operation != foNone)
  7935. {
  7936. RemoteFileControlFileOperation(DropSourceControl,
  7937. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7938. }
  7939. // abort drag&drop
  7940. Abort();
  7941. }
  7942. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7943. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7944. (FDDTargetControl != QueueView3))
  7945. {
  7946. DebugAssert(!FDragTempDir.IsEmpty());
  7947. TTransferType Type;
  7948. UnicodeString TempDir = FDragTempDir;
  7949. // We clear FDragTempDir before calling
  7950. // just in case it fail (raises exception)
  7951. FDragTempDir = L"";
  7952. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7953. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7954. // empty directory parameter means temp directory -> don't display it!
  7955. UnicodeString TargetDir = L"";
  7956. int Options = 0;
  7957. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7958. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7959. {
  7960. Abort();
  7961. }
  7962. // TargetDir is set when dropped on local file control
  7963. // (this was workaround for legacy dirview event handling, now it should be
  7964. // made prettier)
  7965. if (TargetDir.IsEmpty())
  7966. {
  7967. TargetDir = TempDir;
  7968. if (ForceDirectories(ApiPath(TargetDir)))
  7969. {
  7970. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7971. FPendingTempSpaceWarn = true;
  7972. try
  7973. {
  7974. FDragDropOperation = true;
  7975. int Params = cpTemporary |
  7976. (Type == ttMove ? cpDelete : 0);
  7977. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7978. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7979. }
  7980. __finally
  7981. {
  7982. FDragDropOperation = false;
  7983. FPendingTempSpaceWarn = false;
  7984. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7985. }
  7986. }
  7987. else
  7988. {
  7989. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7990. }
  7991. }
  7992. }
  7993. }
  7994. //---------------------------------------------------------------------------
  7995. void __fastcall TCustomScpExplorerForm::DDDownload(
  7996. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7997. {
  7998. DebugAssert(!IsLocalBrowserMode());
  7999. TAutoBatch AutoBatch(this);
  8000. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  8001. UpdateCopyParamCounters(*CopyParam);
  8002. FMoveToQueue = false;
  8003. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  8004. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  8005. {
  8006. RemoteDriveView->UpdateDropSource();
  8007. }
  8008. }
  8009. //---------------------------------------------------------------------------
  8010. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  8011. {
  8012. public:
  8013. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  8014. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  8015. {
  8016. }
  8017. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  8018. {
  8019. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  8020. TDataObjectFilesEx::AllowData(FormatEtc);
  8021. }
  8022. };
  8023. //---------------------------------------------------------------------------
  8024. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  8025. TObject * Sender, TDataObject *& DataObject)
  8026. {
  8027. if (FDDExtMapFile != NULL)
  8028. {
  8029. TFileList * FileList = DragDropFiles(Sender)->FileList;
  8030. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  8031. {
  8032. Abort();
  8033. }
  8034. if (FileList->Count > 0)
  8035. {
  8036. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  8037. if (!FilesObject->IsValid(true, true))
  8038. {
  8039. FilesObject->_Release();
  8040. }
  8041. else
  8042. {
  8043. DataObject = FilesObject;
  8044. }
  8045. }
  8046. }
  8047. }
  8048. //---------------------------------------------------------------------------
  8049. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  8050. {
  8051. DebugFail();
  8052. }
  8053. //---------------------------------------------------------------------------
  8054. void __fastcall TCustomScpExplorerForm::GoToTree()
  8055. {
  8056. ComponentVisible[fcRemoteTree] = true;
  8057. DriveView(osRemote)->SetFocus();
  8058. }
  8059. //---------------------------------------------------------------------------
  8060. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  8061. TPanelExport Export)
  8062. {
  8063. TCustomDirView * DirView = this->DirView(Side);
  8064. std::unique_ptr<TStrings> ExportData(new TStringList());
  8065. switch (Export)
  8066. {
  8067. case pePath:
  8068. ExportData->Add(DirView->PathName);
  8069. break;
  8070. case peFileList:
  8071. case peFullFileList:
  8072. {
  8073. bool FullPath = (Export == peFullFileList);
  8074. DirView->CreateFileList(false, FullPath, ExportData.get());
  8075. for (int Index = 0; Index < ExportData->Count; Index++)
  8076. {
  8077. if (ExportData->Strings[Index].Pos(L" ") > 0)
  8078. {
  8079. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  8080. }
  8081. }
  8082. }
  8083. break;
  8084. default:
  8085. DebugFail();
  8086. }
  8087. return ExportData.release();
  8088. }
  8089. //---------------------------------------------------------------------------
  8090. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  8091. TPanelExport Export, TPanelExportDestination Destination)
  8092. {
  8093. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  8094. PanelExportStore(Side, Export, Destination, ExportData.get());
  8095. }
  8096. //---------------------------------------------------------------------------
  8097. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  8098. TPanelExport /*Export*/, TPanelExportDestination Destination,
  8099. TStrings * ExportData)
  8100. {
  8101. if (Destination == pedClipboard)
  8102. {
  8103. TInstantOperationVisualizer Visualizer;
  8104. CopyToClipboard(ExportData);
  8105. }
  8106. else
  8107. {
  8108. DebugFail();
  8109. }
  8110. }
  8111. //---------------------------------------------------------------------------
  8112. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8113. {
  8114. TCustomDirView * DirView = this->DirView(Side);
  8115. UnicodeString Mask = DirView->Mask;
  8116. if (DoFilterMaskDialog(DirView, Mask))
  8117. {
  8118. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8119. Configuration->Usage->Inc(L"Filters");
  8120. }
  8121. }
  8122. //---------------------------------------------------------------------------
  8123. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8124. {
  8125. return FQueueController->DefaultOperation();
  8126. }
  8127. //---------------------------------------------------------------------------
  8128. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8129. TQueueOperation Operation, void ** Param)
  8130. {
  8131. switch (Operation)
  8132. {
  8133. case qoPreferences:
  8134. return true;
  8135. case qoGoTo:
  8136. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8137. case qoOnceEmpty:
  8138. return IsAnythingQueued();
  8139. default:
  8140. return FQueueController->AllowOperation(Operation, Param);
  8141. }
  8142. }
  8143. //---------------------------------------------------------------------------
  8144. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8145. {
  8146. if (DebugAlwaysTrue(QueueView3->Visible))
  8147. {
  8148. QueueView3->SetFocus();
  8149. }
  8150. }
  8151. //---------------------------------------------------------------------------
  8152. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8153. TQueueOperation Operation, void * Param)
  8154. {
  8155. if (Operation == qoGoTo)
  8156. {
  8157. GoToQueue();
  8158. }
  8159. else if (Operation == qoPreferences)
  8160. {
  8161. PreferencesDialog(pmQueue);
  8162. }
  8163. else
  8164. {
  8165. FQueueController->ExecuteOperation(Operation, Param);
  8166. }
  8167. }
  8168. //---------------------------------------------------------------------------
  8169. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8170. {
  8171. return (Queue != NULL) && Queue->Enabled;
  8172. }
  8173. //---------------------------------------------------------------------------
  8174. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8175. {
  8176. DebugAssert(Queue != NULL);
  8177. if (Queue != NULL)
  8178. {
  8179. Queue->Enabled = !Queue->Enabled;
  8180. }
  8181. }
  8182. //---------------------------------------------------------------------------
  8183. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8184. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8185. {
  8186. FQueueActedItem = QueueView3->ItemFocused;
  8187. }
  8188. //---------------------------------------------------------------------------
  8189. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8190. {
  8191. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8192. }
  8193. //---------------------------------------------------------------------------
  8194. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8195. {
  8196. return
  8197. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8198. (QueueDock->Visible ? QueueDock->Height : 0) +
  8199. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8200. }
  8201. //---------------------------------------------------------------------------
  8202. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8203. {
  8204. return ScaleByTextHeight(this, 48);
  8205. }
  8206. //---------------------------------------------------------------------------
  8207. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8208. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8209. {
  8210. // when queue is hidden by double-clicking splitter, stray attempt to
  8211. // resize the panel with strange value arrives, make sure it is ignored
  8212. if (ComponentVisible[fcQueueView])
  8213. {
  8214. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8215. if (NewSize > MaxHeightLimit)
  8216. {
  8217. NewSize = MaxHeightLimit;
  8218. }
  8219. int MinHeightLimit =
  8220. GetStaticQueuePanelComponentsHeight() +
  8221. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8222. GetMinQueueViewHeight();
  8223. if (NewSize < MinHeightLimit)
  8224. {
  8225. NewSize = MinHeightLimit;
  8226. }
  8227. }
  8228. else
  8229. {
  8230. Accept = false;
  8231. }
  8232. }
  8233. //---------------------------------------------------------------------------
  8234. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8235. {
  8236. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8237. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8238. if (QueueViewHeight < GetMinQueueViewHeight())
  8239. {
  8240. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8241. }
  8242. }
  8243. //---------------------------------------------------------------------------
  8244. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8245. TDragObject *& /*DragObject*/)
  8246. {
  8247. FQueueActedItem = QueueView3->ItemFocused;
  8248. FQueueScrollOnDragOver->StartDrag();
  8249. }
  8250. //---------------------------------------------------------------------------
  8251. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8252. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8253. {
  8254. FQueueScrollOnDragOver->EndDrag();
  8255. }
  8256. //---------------------------------------------------------------------------
  8257. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8258. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8259. {
  8260. Accept = true;
  8261. if (Source == QueueView3)
  8262. {
  8263. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8264. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8265. if (Accept)
  8266. {
  8267. TQueueItemProxy * QueueItem;
  8268. TQueueItemProxy * DestQueueItem;
  8269. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8270. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8271. Accept = (QueueItem != DestQueueItem) &&
  8272. (QueueItem->Status == TQueueItem::qsPending) &&
  8273. (DestQueueItem->Status == TQueueItem::qsPending);
  8274. }
  8275. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8276. }
  8277. }
  8278. //---------------------------------------------------------------------------
  8279. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8280. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8281. {
  8282. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8283. {
  8284. TQueueItemProxy * QueueItem;
  8285. TQueueItemProxy * DestQueueItem;
  8286. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8287. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8288. QueueItem->Move(DestQueueItem);
  8289. }
  8290. }
  8291. //---------------------------------------------------------------------------
  8292. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8293. {
  8294. if ((QueueView3->ItemFocused == NULL) &&
  8295. (QueueView3->Items->Count > 0))
  8296. {
  8297. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8298. }
  8299. QueueLabelUpdateStatus();
  8300. }
  8301. //---------------------------------------------------------------------------
  8302. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8303. {
  8304. QueueLabelUpdateStatus();
  8305. }
  8306. //---------------------------------------------------------------------------
  8307. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8308. {
  8309. QueueLabel->UpdateStatus();
  8310. }
  8311. //---------------------------------------------------------------------------
  8312. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8313. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8314. {
  8315. if (Selected)
  8316. {
  8317. NonVisualDataModule->UpdateNonVisibleActions();
  8318. }
  8319. }
  8320. //---------------------------------------------------------------------------
  8321. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8322. {
  8323. TDragDropFilesEx * Result = NULL;
  8324. if (Sender == SessionsPageControl)
  8325. {
  8326. Result = FSessionsDragDropFilesEx;
  8327. }
  8328. else if (Sender == QueueView3)
  8329. {
  8330. Result = FQueueDragDropFilesEx;
  8331. }
  8332. else
  8333. {
  8334. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8335. if (DirView != NULL)
  8336. {
  8337. Result = DirView->DragDropFilesEx;
  8338. }
  8339. else
  8340. {
  8341. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8342. if (DriveView != NULL)
  8343. {
  8344. Result = DriveView->DragDropFilesEx;
  8345. }
  8346. }
  8347. }
  8348. DebugAssert(Result != NULL);
  8349. return Result;
  8350. }
  8351. //---------------------------------------------------------------------------
  8352. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8353. {
  8354. return (DView->SelCount == DView->FilesCount);
  8355. }
  8356. //---------------------------------------------------------------------------
  8357. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8358. {
  8359. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8360. }
  8361. //---------------------------------------------------------------------------
  8362. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8363. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8364. {
  8365. DebugAssert(!IsLocalBrowserMode());
  8366. TFileOperation Operation;
  8367. switch (Effect)
  8368. {
  8369. case DROPEFFECT_MOVE:
  8370. Operation = foMove;
  8371. break;
  8372. case DROPEFFECT_COPY:
  8373. // occures on WinXP (reported by user)
  8374. default:
  8375. Operation = foCopy;
  8376. break;
  8377. };
  8378. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8379. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8380. if (DragDropFilesEx->FileList->Count > 0)
  8381. {
  8382. TStrings * FileList = new TStringList();
  8383. try
  8384. {
  8385. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8386. {
  8387. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8388. }
  8389. FDragDropOperation = true;
  8390. TTransferOperationParam Param;
  8391. Param.TargetDirectory = TargetPath;
  8392. // upload, no temp dirs
  8393. Param.Temp = false;
  8394. Param.DragDrop = DragDrop;
  8395. Param.Options =
  8396. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8397. if (ForceQueue)
  8398. {
  8399. Param.Queue = asOn;
  8400. }
  8401. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8402. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8403. {
  8404. if (IsFileControl(DropSourceControl, osLocal))
  8405. {
  8406. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8407. }
  8408. else
  8409. {
  8410. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8411. }
  8412. }
  8413. }
  8414. __finally
  8415. {
  8416. FDragDropOperation = false;
  8417. delete FileList;
  8418. }
  8419. }
  8420. }
  8421. //---------------------------------------------------------------------------
  8422. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8423. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8424. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8425. {
  8426. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8427. }
  8428. //---------------------------------------------------------------------------
  8429. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8430. TObject * Sender, int grfKeyState, int & dwEffect)
  8431. {
  8432. DebugAssert(!IsLocalBrowserMode());
  8433. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8434. if ((dwEffect != DROPEFFECT_NONE) &&
  8435. IsFileControl(DropSourceControl, osRemote))
  8436. {
  8437. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8438. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8439. (RemoteDirView->DropTarget == NULL))
  8440. {
  8441. dwEffect = DROPEFFECT_NONE;
  8442. }
  8443. else
  8444. {
  8445. if (dwEffect == DROPEFFECT_COPY)
  8446. {
  8447. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8448. // currently we support copying always (at least via temporary directory);
  8449. // remove associated checks once this all proves stable and working
  8450. bool CopyCapable = true;
  8451. // if we do not support neither of operations, there's no discussion
  8452. if (!MoveCapable && !CopyCapable)
  8453. {
  8454. dwEffect = DROPEFFECT_NONE;
  8455. }
  8456. else
  8457. {
  8458. // The default effect inside remote panel is move,
  8459. // unless we do not support it, but support copy
  8460. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8461. {
  8462. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8463. }
  8464. else
  8465. {
  8466. // with ctrl-down, we want copy unless it is not supported
  8467. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8468. }
  8469. }
  8470. }
  8471. }
  8472. }
  8473. }
  8474. //---------------------------------------------------------------------------
  8475. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8476. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8477. {
  8478. DebugAssert(!IsLocalBrowserMode());
  8479. if (FDDTotalSize >= 0)
  8480. {
  8481. if (File->IsDirectory)
  8482. {
  8483. FDDTotalSize = -1;
  8484. }
  8485. else
  8486. {
  8487. FDDTotalSize += File->Size;
  8488. }
  8489. }
  8490. DebugAssert(!FDragTempDir.IsEmpty());
  8491. // TODO: this is quite ineffective
  8492. // TODO: what if invalid character replacement is disabled?
  8493. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8494. UnicodeString TransferFileName;
  8495. if (Sender == RemoteDriveView)
  8496. {
  8497. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8498. }
  8499. else
  8500. {
  8501. TransferFileName = File->FileName;
  8502. }
  8503. FDDFileList->AddObject(TransferFileName, File);
  8504. }
  8505. //---------------------------------------------------------------------------
  8506. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8507. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8508. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8509. {
  8510. // sometimes we do not get DDEnd so the list is not released
  8511. SAFE_DESTROY(FDDFileList);
  8512. FDDFileList = new TStringList();
  8513. FDragTempDir = WinConfiguration->TemporaryDir();
  8514. FDDTotalSize = 0;
  8515. FDragDropSshTerminate.reset(NULL);
  8516. }
  8517. //---------------------------------------------------------------------------
  8518. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8519. TObject * /*Sender*/, LongBool /*FEscapePressed*/, int /*grfKeyState*/,
  8520. HRESULT & Result)
  8521. {
  8522. if (Result == DRAGDROP_S_DROP)
  8523. {
  8524. try
  8525. {
  8526. GlobalDragImageList->HideDragImage();
  8527. try
  8528. {
  8529. RemoteFileControlDDTargetDrop();
  8530. }
  8531. catch(ESshTerminate & E)
  8532. {
  8533. FDragDropSshTerminate.reset(E.Clone());
  8534. }
  8535. }
  8536. catch (Exception &E)
  8537. {
  8538. // If downloading fails we need to cancel drag&drop, otherwise
  8539. // Explorer shows error
  8540. // But by the way exception probably never reach this point as
  8541. // it's catched on way.
  8542. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8543. Result = DRAGDROP_S_CANCEL;
  8544. ShowExtendedException(Terminal, &E);
  8545. }
  8546. }
  8547. }
  8548. //---------------------------------------------------------------------------
  8549. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8550. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8551. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8552. {
  8553. TFileMasks::TParams MaskParams;
  8554. MaskParams.Size = Size;
  8555. MaskParams.Modification = Modification;
  8556. // this does not re-parse the mask if it is the same as the last time
  8557. FDirViewMatchMask = Masks;
  8558. bool ImplicitMatch;
  8559. Matches =
  8560. // Local and RecurseInclude parameters have no effect as there's no path.
  8561. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8562. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8563. (AllowImplicitMatches || !ImplicitMatch);
  8564. }
  8565. //---------------------------------------------------------------------------
  8566. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8567. TObject * Sender, TListItem * Item, WORD & Indexes)
  8568. {
  8569. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8570. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8571. {
  8572. Indexes |= oiPartial;
  8573. }
  8574. }
  8575. //---------------------------------------------------------------------------
  8576. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8577. {
  8578. return
  8579. DirViewEnabled(osCurrent) &&
  8580. DirView(osCurrent)->CanPasteFromClipBoard();
  8581. }
  8582. //---------------------------------------------------------------------------
  8583. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8584. {
  8585. bool Result = false;
  8586. if (CanPasteToDirViewFromClipBoard())
  8587. {
  8588. Result = true;
  8589. }
  8590. else
  8591. {
  8592. UnicodeString ClipboardText;
  8593. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8594. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8595. {
  8596. if (StoredSessions->IsUrl(ClipboardText))
  8597. {
  8598. Result = true;
  8599. }
  8600. else
  8601. {
  8602. Result = DirViewEnabled(osCurrent);
  8603. }
  8604. }
  8605. }
  8606. return Result;
  8607. }
  8608. //---------------------------------------------------------------------------
  8609. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8610. {
  8611. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8612. if (DoesClipboardContainOurFiles())
  8613. {
  8614. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8615. {
  8616. DebugAssert(!IsLocalBrowserMode());
  8617. TTerminalManager * Manager = TTerminalManager::Instance();
  8618. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8619. Manager->ActiveSession = FClipboardTerminal;
  8620. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8621. }
  8622. }
  8623. else if (CanPasteToDirViewFromClipBoard())
  8624. {
  8625. DirView(osCurrent)->PasteFromClipBoard();
  8626. }
  8627. else
  8628. {
  8629. UnicodeString ClipboardText;
  8630. if (NonEmptyTextFromClipboard(ClipboardText))
  8631. {
  8632. if (StoredSessions->IsUrl(ClipboardText))
  8633. {
  8634. NewSession(ClipboardText);
  8635. }
  8636. else
  8637. {
  8638. DirView(osCurrent)->Path = ClipboardText;
  8639. }
  8640. }
  8641. }
  8642. }
  8643. //---------------------------------------------------------------------------
  8644. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8645. {
  8646. // TBD
  8647. }
  8648. //---------------------------------------------------------------------------
  8649. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8650. {
  8651. TCustomDirView * ADirView = DirView(Side);
  8652. ADirView->SelectAll(Mode);
  8653. ADirView->SetFocus();
  8654. }
  8655. //---------------------------------------------------------------------------
  8656. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8657. {
  8658. TCustomDirView * ADirView = DirView(Side);
  8659. TFileFilter Filter;
  8660. DefaultFileFilter(Filter);
  8661. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8662. {
  8663. Configuration->Usage->Inc(L"MaskSelections");
  8664. ADirView->SelectFiles(Filter, Select);
  8665. ADirView->SetFocus();
  8666. }
  8667. }
  8668. //---------------------------------------------------------------------------
  8669. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8670. {
  8671. TCustomDirView * ADirView = DirView(Side);
  8672. ADirView->RestoreSelectedNames();
  8673. ADirView->SetFocus();
  8674. }
  8675. //---------------------------------------------------------------------------
  8676. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8677. {
  8678. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8679. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8680. {
  8681. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8682. UnicodeString Ext;
  8683. if (!IsSideLocalBrowser(osCurrent))
  8684. {
  8685. Ext = UnixExtractFileExt(FileName);
  8686. }
  8687. else
  8688. {
  8689. Ext = ExtractFileExt(FileName);
  8690. }
  8691. if (Ext.IsEmpty())
  8692. {
  8693. Ext = L".";
  8694. }
  8695. TFileFilter Filter;
  8696. Filter.Masks = FORMAT(L"*%s", (Ext));
  8697. Filter.Directories = false;
  8698. CurrentDirView->SelectFiles(Filter, Select);
  8699. }
  8700. }
  8701. //---------------------------------------------------------------------------
  8702. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8703. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8704. {
  8705. UnicodeString Result;
  8706. if (FIncrementalSearchState.Searching && (Side == GetSide(osCurrent)))
  8707. {
  8708. Result = FormatIncrementalSearchStatus(FIncrementalSearchState);
  8709. }
  8710. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8711. {
  8712. // noop
  8713. }
  8714. else
  8715. {
  8716. Result =
  8717. FMTLOAD(FILE_INFO_FORMAT,
  8718. (FormatBytes(FileInfo.SelectedSize),
  8719. FormatBytes(FileInfo.FilesSize),
  8720. FormatNumber(FileInfo.SelectedCount),
  8721. FormatNumber(FileInfo.FilesCount)));
  8722. }
  8723. return Result;
  8724. }
  8725. //---------------------------------------------------------------------------
  8726. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8727. TTBXStatusPanel * Panel, TOperationSide Side)
  8728. {
  8729. if (Panel->Index == 1)
  8730. {
  8731. ToggleShowHiddenFiles();
  8732. }
  8733. else if (Panel->Index == 2)
  8734. {
  8735. Filter(Side);
  8736. }
  8737. }
  8738. //---------------------------------------------------------------------------
  8739. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8740. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8741. {
  8742. DebugAssert(!StatusBar->SimplePanel);
  8743. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8744. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8745. }
  8746. //---------------------------------------------------------------------------
  8747. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8748. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8749. {
  8750. DebugAssert(StatusBar->Panels->Count >= 3);
  8751. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8752. if (FileInfo.HiddenCount > 0)
  8753. {
  8754. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8755. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8756. }
  8757. else
  8758. {
  8759. HiddenFilesPanel->ViewPriority = 0;
  8760. // not really necessary, just to cleanup no-longer-valid data
  8761. HiddenFilesPanel->Caption = L"";
  8762. }
  8763. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8764. if (FileInfo.FilteredCount > 0)
  8765. {
  8766. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8767. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8768. }
  8769. else
  8770. {
  8771. FilteredFilesPanel->ViewPriority = 0;
  8772. // not really necessary, just to cleanup no-longer-valid data
  8773. FilteredFilesPanel->Caption = L"";
  8774. }
  8775. }
  8776. //---------------------------------------------------------------------------
  8777. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8778. TObject * /*Sender*/)
  8779. {
  8780. if (DirView(osOther)->Enabled)
  8781. {
  8782. DirView(osOther)->SetFocus();
  8783. }
  8784. }
  8785. //---------------------------------------------------------------------------
  8786. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8787. {
  8788. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8789. switch (Config.Show)
  8790. {
  8791. case qvShow:
  8792. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8793. {
  8794. Config.Show = qvHide;
  8795. }
  8796. else
  8797. {
  8798. Config.Show = Config.LastHideShow;
  8799. }
  8800. break;
  8801. case qvHideWhenEmpty:
  8802. if (ComponentVisible[fcQueueView])
  8803. {
  8804. Config.Show = qvHide;
  8805. }
  8806. else
  8807. {
  8808. Config.LastHideShow = Config.Show;
  8809. Config.Show = qvShow;
  8810. }
  8811. break;
  8812. case qvHide:
  8813. Config.LastHideShow = Config.Show;
  8814. Config.Show = qvShow;
  8815. break;
  8816. }
  8817. WinConfiguration->QueueView = Config;
  8818. }
  8819. //---------------------------------------------------------------------------
  8820. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8821. {
  8822. UnicodeString Result;
  8823. if (Terminal != NULL)
  8824. {
  8825. switch (WinConfiguration->PathInCaption)
  8826. {
  8827. case picShort:
  8828. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8829. break;
  8830. case picFull:
  8831. Result = Terminal->CurrentDirectory;
  8832. break;
  8833. }
  8834. }
  8835. return Result;
  8836. }
  8837. //---------------------------------------------------------------------------
  8838. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8839. {
  8840. TColor Result = GetWindowColor(FSessionColor);
  8841. return Result;
  8842. }
  8843. //---------------------------------------------------------------------------
  8844. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8845. {
  8846. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8847. return Result;
  8848. }
  8849. //---------------------------------------------------------------------------
  8850. void TCustomScpExplorerForm::UpdatePanelControls(TCustomDirView * ADirView, TCustomDriveView * ADriveView)
  8851. {
  8852. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8853. ADirView->DarkMode = UseDarkTheme;
  8854. ADriveView->DarkMode = UseDarkTheme;
  8855. }
  8856. //---------------------------------------------------------------------------
  8857. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8858. {
  8859. if (!FSessionChanging)
  8860. {
  8861. TTerminalManager::Instance()->UpdateAppTitle();
  8862. }
  8863. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8864. // background to gray on Windows 7 (works on Windows 10).
  8865. // See also EnableControl
  8866. if (Showing)
  8867. {
  8868. if (ManagedSession != NULL)
  8869. {
  8870. // Update path when it changes
  8871. if ((SessionsPageControl->ActivePage != NULL) &&
  8872. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8873. {
  8874. UpdateSessionTab(SessionsPageControl->ActivePage);
  8875. }
  8876. }
  8877. NonVisualDataModule->ReconnectSessionAction->Update();
  8878. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8879. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8880. CenterReconnectToolbar();
  8881. // The only place, where we use IsOpenedTerminal and not IsAvailableTerminal
  8882. // (i.e. not checking for reconnecting status)
  8883. // Otherwise it causes flicker [particularly in dark mode] during the short time
  8884. // between the authentication window is closed and FOpeningTerminal is cleared.
  8885. // Should be solved smarter.
  8886. bool HasTerminal = TTerminalManager::Instance()->IsOpenedTerminal(Terminal);
  8887. RemoteDirView->Enabled = HasTerminal;
  8888. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8889. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8890. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8891. RemoteDriveView->Color = RemoteDirView->Color;
  8892. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8893. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8894. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8895. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8896. QueueFileList->Enabled = QueueView3->Enabled;
  8897. QueueFileList->Color = QueueView3->Color;
  8898. QueueFileList->Font->Color = QueueView3->Font->Color;
  8899. QueueLabelUpdateStatus();
  8900. UpdatePanelControls(RemoteDirView, RemoteDriveView);
  8901. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8902. if (FImmersiveDarkMode != UseDarkTheme)
  8903. {
  8904. UpdateDarkMode();
  8905. }
  8906. SessionsPageControl->TabTheme = UseDarkTheme ? CurrentTheme : NULL;
  8907. QueueView3->DarkMode = UseDarkTheme;
  8908. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8909. bool HiContrast = WinConfiguration->HiContrast;
  8910. UnicodeString NewHiContrastThemeName = HiContrast ? GetThemeName(!UseDarkTheme) : EmptyStr;
  8911. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8912. {
  8913. ReleaseHiContrastTheme();
  8914. if (!NewHiContrastThemeName.IsEmpty())
  8915. {
  8916. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8917. }
  8918. }
  8919. SessionsPageControl->ActiveTabTheme = HiContrast ? DebugNotNull(FHiContrastTheme) : NULL;
  8920. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8921. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8922. }
  8923. }
  8924. //---------------------------------------------------------------------------
  8925. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8926. {
  8927. UpdateControls();
  8928. }
  8929. //---------------------------------------------------------------------------
  8930. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8931. TObject * Sender)
  8932. {
  8933. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8934. DebugAssert(DirView != NULL);
  8935. DoDirViewLoaded(DirView);
  8936. TransferPresetAutoSelect();
  8937. TUnixDirView * UnixDirView = dynamic_cast<TUnixDirView *>(DirView);
  8938. if (UnixDirView != NULL)
  8939. {
  8940. TManagedTerminal * ATerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(UnixDirView->Terminal));
  8941. TTerminalManager::Instance()->TerminalLoadedDirectory(ATerminal);
  8942. }
  8943. }
  8944. //---------------------------------------------------------------------------
  8945. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8946. {
  8947. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8948. // first run after installation
  8949. if (double(Updates.LastCheck) == 0)
  8950. {
  8951. AppLog(L"First run, scheduling updates check for the next run");
  8952. // make sure next time there will be an update (if enabled)
  8953. Updates.LastCheck = TDateTime(1);
  8954. WinConfiguration->Updates = Updates;
  8955. }
  8956. else
  8957. {
  8958. TDateTime Period;
  8959. if (IsUWP() && !IsOfficialPackage())
  8960. {
  8961. Period = DefaultUpdatesPeriod;
  8962. AppLog(L"Thirdparty UWP package, using default updates check period");
  8963. }
  8964. else
  8965. {
  8966. Period = Updates.Period;
  8967. }
  8968. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8969. if (double(Period) > 0)
  8970. {
  8971. TDateTime Interval = Now() - Updates.LastCheck;
  8972. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8973. if (Interval >= Period)
  8974. {
  8975. StartUpdateThread(UpdatesChecked);
  8976. }
  8977. }
  8978. }
  8979. }
  8980. //---------------------------------------------------------------------------
  8981. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8982. {
  8983. AppLog(L"Updates check done");
  8984. UnicodeString Message;
  8985. bool New;
  8986. TQueryType Type;
  8987. GetUpdatesMessage(Message, New, Type, false);
  8988. if (!Message.IsEmpty())
  8989. {
  8990. AppLogFmt(L"Updates check message: %s", (Message));
  8991. if (New)
  8992. {
  8993. AppLog(L"New version detected");
  8994. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8995. }
  8996. if (!New && (Type != qtWarning))
  8997. {
  8998. AppLog(L"Posting non-critical updates note");
  8999. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked);
  9000. }
  9001. else
  9002. {
  9003. AppLog(L"Posting new version or critical message notification");
  9004. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  9005. }
  9006. if (New)
  9007. {
  9008. Configuration->Usage->Inc(L"UpdateNotifications");
  9009. }
  9010. }
  9011. }
  9012. //---------------------------------------------------------------------------
  9013. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  9014. {
  9015. RestoreApp();
  9016. bool CanDisplay = !NonVisualDataModule->Busy;
  9017. if (!CanDisplay && (Screen->ActiveForm != NULL))
  9018. {
  9019. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  9020. }
  9021. if (CanDisplay)
  9022. {
  9023. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  9024. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  9025. NonVisualDataModule->StartBusy();
  9026. try
  9027. {
  9028. CheckForUpdates(true);
  9029. }
  9030. __finally
  9031. {
  9032. NonVisualDataModule->EndBusy();
  9033. }
  9034. }
  9035. else
  9036. {
  9037. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  9038. }
  9039. }
  9040. //---------------------------------------------------------------------------
  9041. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  9042. TCopyParamRuleData & Data)
  9043. {
  9044. DebugAssert(Terminal != NULL);
  9045. Data.HostName = Terminal->SessionData->HostNameExpanded;
  9046. Data.UserName = Terminal->SessionData->UserNameExpanded;
  9047. Data.RemoteDirectory = RemoteDirView->PathName;
  9048. }
  9049. //---------------------------------------------------------------------------
  9050. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  9051. {
  9052. // Terminal can be null when we are changing local directory implicitly,
  9053. // because it has been deleted, while no session is connected
  9054. // (Login dialog is open)
  9055. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  9056. {
  9057. DebugAssert(!IsLocalBrowserMode());
  9058. TCopyParamRuleData Data;
  9059. GetTransferPresetAutoSelectData(Data);
  9060. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  9061. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  9062. if (CopyParamIndex < 0)
  9063. {
  9064. // there is no preset that matches autoselection
  9065. // set preset that we consider "default"
  9066. FCopyParamAutoSelected = L""; // forget last autoselected preset
  9067. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  9068. }
  9069. else
  9070. {
  9071. // there is preset matching autoselection
  9072. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  9073. if (CopyParamName == FCopyParamAutoSelected)
  9074. {
  9075. // autoselected the same preset as the last time
  9076. // make no change (i.e. preserve custom user preset, if any)
  9077. }
  9078. else
  9079. {
  9080. // autoselected the different preset then the last time (or there
  9081. // was default preset set)
  9082. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  9083. GUIConfiguration->CopyParamCurrent = CopyParamName;
  9084. }
  9085. }
  9086. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  9087. {
  9088. if (CopyParamIndex >= 0)
  9089. {
  9090. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  9091. }
  9092. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  9093. try
  9094. {
  9095. int Fmt =
  9096. (CopyParamIndex < 0) ?
  9097. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  9098. COPY_PARAM_AUTOSELECTED;
  9099. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  9100. Data->Message = MainInstructions(Message);
  9101. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  9102. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  9103. CopyParamAttrs);
  9104. if (CopyParamIndex >= 0)
  9105. {
  9106. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  9107. Info = FORMAT(L"%s\n \n%s", (Info,
  9108. FMTLOAD(COPY_PARAM_RULE,
  9109. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  9110. }
  9111. Data->Message += L"\n\n" + Info;
  9112. if (WinConfiguration->CopyParamAutoSelectNotice)
  9113. {
  9114. TransferPresetNoteMessage(Data, true);
  9115. }
  9116. else
  9117. {
  9118. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  9119. Data = NULL; // ownership passed
  9120. }
  9121. }
  9122. __finally
  9123. {
  9124. delete Data;
  9125. }
  9126. }
  9127. }
  9128. }
  9129. //---------------------------------------------------------------------------
  9130. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9131. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9132. {
  9133. DebugAssert(NoteData != NULL);
  9134. DebugAssert(!IsLocalBrowserMode());
  9135. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9136. TQueryButtonAlias Aliases[1];
  9137. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9138. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9139. Params.Aliases = Aliases;
  9140. Params.AliasesCount = LENOF(Aliases);
  9141. unsigned int Result =
  9142. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9143. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9144. switch (Result)
  9145. {
  9146. case qaNeverAskAgain:
  9147. DebugAssert(AllowNeverAskAgain);
  9148. WinConfiguration->CopyParamAutoSelectNotice = false;
  9149. break;
  9150. case qaIgnore:
  9151. PreferencesDialog(pmPresets);
  9152. break;
  9153. }
  9154. }
  9155. //---------------------------------------------------------------------------
  9156. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9157. {
  9158. // as of now useless, as this is used for notes only, never for balloons, ...
  9159. RestoreApp();
  9160. // .. and we should never be busy here
  9161. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9162. {
  9163. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9164. }
  9165. }
  9166. //---------------------------------------------------------------------------
  9167. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9168. TPreferencesMode APreferencesMode)
  9169. {
  9170. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9171. TCopyParamRuleData Data;
  9172. if (Terminal != NULL)
  9173. {
  9174. PreferencesData.reset(new TPreferencesDialogData());
  9175. GetTransferPresetAutoSelectData(Data);
  9176. PreferencesData->CopyParamRuleData = &Data;
  9177. }
  9178. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9179. }
  9180. //---------------------------------------------------------------------------
  9181. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9182. const TCustomCommandType & Command)
  9183. {
  9184. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9185. {
  9186. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9187. }
  9188. }
  9189. //---------------------------------------------------------------------------
  9190. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9191. {
  9192. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9193. TCustomCommandType Command;
  9194. // make sure we use local custom command when remote are not supported
  9195. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9196. {
  9197. Command = FLastCustomCommand;
  9198. }
  9199. else
  9200. {
  9201. Command.Params = Command.Params | ccLocal;
  9202. }
  9203. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9204. FEditingFocusedAdHocCommand = OnFocused;
  9205. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9206. int Options =
  9207. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9208. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9209. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9210. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9211. {
  9212. FLastCustomCommand = Command;
  9213. UpdateCustomCommandsToolbar();
  9214. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9215. }
  9216. }
  9217. //---------------------------------------------------------------------------
  9218. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9219. {
  9220. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9221. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9222. DebugAssert(State > 0);
  9223. if (State <= 0)
  9224. {
  9225. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9226. }
  9227. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9228. }
  9229. //---------------------------------------------------------------------------
  9230. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9231. TCustomCommandType & Command, int & State)
  9232. {
  9233. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9234. if (Result)
  9235. {
  9236. Command = FLastCustomCommand;
  9237. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9238. }
  9239. return Result;
  9240. }
  9241. //---------------------------------------------------------------------------
  9242. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9243. {
  9244. ResetIncrementalSearch();
  9245. }
  9246. //---------------------------------------------------------------------------
  9247. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9248. {
  9249. DebugAssert(ComponentVisible[Component]);
  9250. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9251. }
  9252. //---------------------------------------------------------------------------
  9253. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9254. {
  9255. // when queue panel is resized here directly, the status bar is stretched
  9256. // over whole space the panel occupied
  9257. PostComponentHide(fcQueueView);
  9258. }
  9259. //---------------------------------------------------------------------------
  9260. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9261. {
  9262. ComponentVisible[fcQueueFileList] = false;
  9263. }
  9264. //---------------------------------------------------------------------------
  9265. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9266. {
  9267. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9268. // Scrollbars colors are refreshed by WM_THEMECHANGED.
  9269. RefreshColorMode();
  9270. ResetSysDarkTheme();
  9271. ConfigurationChanged();
  9272. ConfigureInterface();
  9273. // To update references to recreated/destroyed themes in SessionsPageControl
  9274. UpdateControls();
  9275. }
  9276. //---------------------------------------------------------------------------
  9277. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9278. {
  9279. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9280. if (!FInvalid &&
  9281. (Message.LParam != 0) &&
  9282. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9283. {
  9284. ThemeChanged();
  9285. }
  9286. TForm::Dispatch(&Message);
  9287. }
  9288. //---------------------------------------------------------------------------
  9289. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9290. {
  9291. TMessage * M = static_cast<TMessage*>(Message);
  9292. switch (M->Msg)
  9293. {
  9294. case CM_DIALOGCHAR:
  9295. CMDialogChar(*M);
  9296. break;
  9297. case WM_APPCOMMAND:
  9298. WMAppCommand(*M);
  9299. break;
  9300. case WM_SYSCOMMAND:
  9301. WMSysCommand(*M);
  9302. break;
  9303. case WM_QUERYENDSESSION:
  9304. WMQueryEndSession(*M);
  9305. break;
  9306. case WM_ENDSESSION:
  9307. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9308. break;
  9309. #ifdef _DEBUG
  9310. case WM_WINDOWPOSCHANGED:
  9311. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9312. break;
  9313. case CM_CUSTOMSTYLECHANGED:
  9314. TForm::Dispatch(Message);
  9315. break;
  9316. #endif
  9317. case WM_COMPONENT_HIDE:
  9318. {
  9319. Byte Component = static_cast<Byte>(M->WParam);
  9320. // sanity check
  9321. if (ComponentVisible[Component])
  9322. {
  9323. // special treatment
  9324. if (Component == fcQueueView)
  9325. {
  9326. ToggleQueueVisibility();
  9327. DebugAssert(!ComponentVisible[fcQueueView]);
  9328. }
  9329. else
  9330. {
  9331. ComponentVisible[Component] = false;
  9332. }
  9333. }
  9334. }
  9335. break;
  9336. case WM_COPYDATA:
  9337. WMCopyData(*M);
  9338. break;
  9339. case WM_MANAGES_CAPTION:
  9340. // caption managed in TTerminalManager::UpdateAppTitle()
  9341. M->Result = 1;
  9342. break;
  9343. case WM_WANTS_MOUSEWHEEL:
  9344. M->Result = 1;
  9345. break;
  9346. case CM_SHOWINGCHANGED:
  9347. CMShowingChanged(*M);
  9348. break;
  9349. case WM_CLOSE:
  9350. WMClose(*M);
  9351. break;
  9352. case WM_DPICHANGED:
  9353. WMDpiChanged(*M);
  9354. break;
  9355. case WM_SETTINGCHANGE:
  9356. WMSettingChange(*M);
  9357. break;
  9358. case CM_DIALOGKEY:
  9359. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9360. break;
  9361. case WM_PASTE_FILES:
  9362. PasteFiles();
  9363. break;
  9364. case WM_IS_HIDDEN:
  9365. // To treat master password prompt as a main window while showing it when workspace is loading while
  9366. // the exporer is showing up (Visible is true already)
  9367. M->Result = !FShowing;
  9368. break;
  9369. case WM_SHOWWINDOW:
  9370. if (M->WParam)
  9371. {
  9372. AddStartupSequence(L"J");
  9373. }
  9374. TForm::Dispatch(Message);
  9375. break;
  9376. case WM_QUEUE_CALLBACK:
  9377. WMQueueCallback(*M);
  9378. break;
  9379. default:
  9380. TForm::Dispatch(Message);
  9381. break;
  9382. }
  9383. }
  9384. //---------------------------------------------------------------------------
  9385. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9386. {
  9387. // noop
  9388. }
  9389. //---------------------------------------------------------------------------
  9390. void TCustomScpExplorerForm::RegenerateSessionColorsImageList()
  9391. {
  9392. FSessionColors->Clear();
  9393. AddFixedSessionImages();
  9394. ::RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9395. UpdateImages();
  9396. }
  9397. //---------------------------------------------------------------------------
  9398. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9399. {
  9400. TForm::Dispatch(&Message);
  9401. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9402. UpdatePixelsPerInchMainWindowCounter();
  9403. }
  9404. //---------------------------------------------------------------------------
  9405. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9406. {
  9407. AppLog(L"Main window WM_CLOSE");
  9408. // Cannot close window while we are busy.
  9409. // We cannot test this in FormCloseQuery as that is called also from
  9410. // Close(), which is called by CloseApplicationAction. So we can be busy
  9411. // there already even, when it is legitimate to close the application.
  9412. // Possibly a better place to handle this would be WMSysCommand.
  9413. if (NonVisualDataModule->Busy)
  9414. {
  9415. Message.Result = 1;
  9416. }
  9417. else
  9418. {
  9419. TForm::Dispatch(&Message);
  9420. }
  9421. }
  9422. //---------------------------------------------------------------------------
  9423. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9424. {
  9425. if (!FShowingChanged)
  9426. {
  9427. AddStartupSequence(L"D");
  9428. FShowingChanged = true;
  9429. }
  9430. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9431. bool NoSession = (ManagedSession == NULL);
  9432. // This calls TCustomScpExplorerForm::DoShow
  9433. TForm::Dispatch(&Message);
  9434. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9435. if (Showing && !FStarted)
  9436. {
  9437. FStarted = true;
  9438. InterfaceStarted();
  9439. }
  9440. if (Showing && NoSession)
  9441. {
  9442. // When we are starting minimized (i.e. from an installer),
  9443. // postpone showing Login dialog until we get restored.
  9444. // Otherwise the Login dialog (and Authentication window) show restored
  9445. // over invisible (minimized) main window.
  9446. if (WindowState == wsMinimized)
  9447. {
  9448. FNeedSession = true;
  9449. }
  9450. else
  9451. {
  9452. // This happens before application ever goes idle, so the toolbars would
  9453. // stay enabled (initial state) until the Login dialog is dismissed.
  9454. UpdateActions();
  9455. NonVisualDataModule->StartBusy();
  9456. try
  9457. {
  9458. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9459. // otherwise the dialog does not receive focus.
  9460. // With Commander interface the ProcessMessages is called already
  9461. // by TDriveView, but with Explorer interface, we need to call it explicily
  9462. Application->ProcessMessages();
  9463. // do not reload sessions, they have been loaded just now (optimization)
  9464. NeedSession(true);
  9465. }
  9466. __finally
  9467. {
  9468. NonVisualDataModule->EndBusy();
  9469. }
  9470. }
  9471. }
  9472. }
  9473. //---------------------------------------------------------------------------
  9474. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9475. {
  9476. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9477. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9478. }
  9479. //---------------------------------------------------------------------------
  9480. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9481. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9482. int & MaxHeight)
  9483. {
  9484. // workaround for bug in TWinControl.CalcConstraints
  9485. // Check for empty rect (restore from iconic state) is done there only after
  9486. // call to AdjustClientRect, which enlarges the rect (for forms).
  9487. TRect R = GetClientRect();
  9488. // when restoring from iconic state, place no restrictions
  9489. if (IsRectEmpty(R))
  9490. {
  9491. MinWidth = 0;
  9492. MinHeight = 0;
  9493. MaxWidth = 32000;
  9494. MaxHeight = 32000;
  9495. }
  9496. }
  9497. //---------------------------------------------------------------------------
  9498. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9499. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9500. {
  9501. // terminal can be already closed (e.g. dropped connection)
  9502. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9503. {
  9504. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9505. try
  9506. {
  9507. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9508. }
  9509. catch(...)
  9510. {
  9511. if (!Terminal->Active)
  9512. {
  9513. Close = true;
  9514. }
  9515. throw;
  9516. }
  9517. }
  9518. }
  9519. //---------------------------------------------------------------------------
  9520. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9521. {
  9522. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9523. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9524. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9525. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9526. {
  9527. OnGetSpaceAvailable = GetSpaceAvailable;
  9528. }
  9529. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9530. OnGetSpaceAvailable);
  9531. }
  9532. //---------------------------------------------------------------------------
  9533. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9534. {
  9535. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9536. Terminal->FillSessionDataForCode(Data.get());
  9537. return Data.release();
  9538. }
  9539. //---------------------------------------------------------------------------
  9540. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9541. {
  9542. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9543. DoGenerateUrlDialog(Data.get(), Paths);
  9544. }
  9545. //---------------------------------------------------------------------------
  9546. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9547. {
  9548. GenerateUrl(NULL);
  9549. }
  9550. //---------------------------------------------------------------------------
  9551. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9552. {
  9553. std::unique_ptr<TStrings> Paths(new TStringList());
  9554. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9555. GenerateUrl(Paths.get());
  9556. }
  9557. //---------------------------------------------------------------------------
  9558. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9559. {
  9560. FSessionColor = value;
  9561. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9562. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9563. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9564. DebugAssert(ColorItem != NULL);
  9565. ColorItem->Color = C;
  9566. NonVisualDataModule->ColorMenuItem->Color = C;
  9567. UpdateControls();
  9568. }
  9569. //---------------------------------------------------------------------------
  9570. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9571. {
  9572. if (value != FSessionColor)
  9573. {
  9574. UpdateSessionColor(value);
  9575. // Is null when called from LastTerminalClosed
  9576. if (Terminal != NULL)
  9577. {
  9578. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9579. }
  9580. }
  9581. }
  9582. //---------------------------------------------------------------------------
  9583. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9584. {
  9585. bool Result = FNoteTimer->Enabled;
  9586. if (Result)
  9587. {
  9588. // cannot cancel note too early
  9589. bool NotEarly =
  9590. (Now() - FNoteShown >
  9591. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9592. if (Force || NotEarly)
  9593. {
  9594. FNoteTimer->Enabled = false;
  9595. FNote = L"";
  9596. SAFE_DESTROY(FNoteData);
  9597. FOnNoteClick = NULL;
  9598. FNoteHints = FNotes->Text;
  9599. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9600. UpdateStatusBar();
  9601. }
  9602. }
  9603. return Result;
  9604. }
  9605. //---------------------------------------------------------------------------
  9606. void TCustomScpExplorerForm::CancelNote(const UnicodeString & Note)
  9607. {
  9608. if (FNote == Note)
  9609. {
  9610. CancelNote(true);
  9611. }
  9612. }
  9613. //---------------------------------------------------------------------------
  9614. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9615. {
  9616. DebugAssert(FNoteTimer->Enabled);
  9617. CancelNote(true);
  9618. }
  9619. //---------------------------------------------------------------------------
  9620. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9621. {
  9622. FNoteHints = FNotes->Text.TrimRight();
  9623. }
  9624. //---------------------------------------------------------------------------
  9625. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9626. {
  9627. int P = Note.Pos(L"\n");
  9628. if (P > 0)
  9629. {
  9630. Note.SetLength(P - 1);
  9631. }
  9632. FNotes->Add(FORMAT(L"[%s] %s",
  9633. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9634. while (FNotes->Count > 10)
  9635. {
  9636. FNotes->Delete(0);
  9637. }
  9638. if (UpdateNow)
  9639. {
  9640. UpdateNoteHints();
  9641. UpdateStatusBar();
  9642. }
  9643. }
  9644. //---------------------------------------------------------------------------
  9645. void TCustomScpExplorerForm::PostNote(
  9646. const UnicodeString & ANote, unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9647. {
  9648. UnicodeString Note = ANote;
  9649. int P = Note.Pos(L"\n");
  9650. if (P > 0)
  9651. {
  9652. Note.SetLength(P - 1);
  9653. }
  9654. UpdateNoteHints();
  9655. FNote = Note;
  9656. SAFE_DESTROY(FNoteData);
  9657. FNoteData = NoteData;
  9658. FOnNoteClick = OnNoteClick;
  9659. AddNote(Note, false);
  9660. UpdateStatusBar();
  9661. FNoteShown = Now();
  9662. FNoteTimer->Enabled = false;
  9663. if (Seconds == 0)
  9664. {
  9665. Seconds = WinConfiguration->NotificationsTimeout;
  9666. }
  9667. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9668. FNoteTimer->Enabled = true;
  9669. }
  9670. //---------------------------------------------------------------------------
  9671. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9672. {
  9673. PostNote(LoadStr(DIRECTORY_READING_CANCELLED));
  9674. }
  9675. //---------------------------------------------------------------------------
  9676. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9677. {
  9678. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9679. {
  9680. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9681. }
  9682. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9683. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9684. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))));
  9685. }
  9686. //---------------------------------------------------------------------------
  9687. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9688. {
  9689. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9690. UnicodeString Note =
  9691. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9692. PostNote(Note);
  9693. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9694. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9695. }
  9696. //---------------------------------------------------------------------------
  9697. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9698. {
  9699. WinConfiguration->FormatSizeBytes = Style;
  9700. }
  9701. //---------------------------------------------------------------------------
  9702. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9703. {
  9704. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9705. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9706. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9707. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))));
  9708. }
  9709. //---------------------------------------------------------------------------
  9710. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9711. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9712. {
  9713. if (Panel->Index == 0)
  9714. {
  9715. if (FOnNoteClick != NULL)
  9716. {
  9717. // prevent the user data from being freed by possible call
  9718. // to CancelNote or PostNote during call to OnNoteClick
  9719. std::unique_ptr<TObject> NoteData(FNoteData);
  9720. TNotifyEvent OnNoteClick = FOnNoteClick;
  9721. FNoteData = NULL;
  9722. // need to cancel the note as we are going to delete its user data
  9723. CancelNote(true);
  9724. OnNoteClick(NoteData.get());
  9725. }
  9726. }
  9727. if (HasAvailableTerminal() &&
  9728. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9729. {
  9730. FileSystemInfo();
  9731. }
  9732. }
  9733. //---------------------------------------------------------------------------
  9734. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9735. {
  9736. // workaround:
  9737. // 1) for unknown reason, disabling window, while minimized,
  9738. // prevents it from restoring, even if it was enabled again meanwhile
  9739. // 2) when disabling the main window, while another has focus
  9740. // minimize is no longer possible
  9741. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9742. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9743. // Shouldn't we use IsApplicationMinimized() here?
  9744. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9745. {
  9746. Enabled = false;
  9747. }
  9748. FLockLevel++;
  9749. }
  9750. //---------------------------------------------------------------------------
  9751. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9752. {
  9753. DebugAssert(FLockLevel > 0);
  9754. FLockLevel--;
  9755. if (FLockLevel == 0)
  9756. {
  9757. DebugAssert(FLockSuspendLevel == 0);
  9758. Enabled = true;
  9759. // VCL_COPY (TCustomForm.SetWindowFocus)
  9760. if (Active && (ActiveControl != NULL))
  9761. {
  9762. ::SetFocus(ActiveControl->Handle);
  9763. if (GetFocus() == ActiveControl->Handle)
  9764. {
  9765. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9766. }
  9767. }
  9768. }
  9769. }
  9770. //---------------------------------------------------------------------------
  9771. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9772. {
  9773. // We need to make sure that window is enabled when the last modal window closes
  9774. // otherwise focus is not restored correctly.
  9775. // So we re-enable the window when modal window opens and
  9776. // disable it back after is closes
  9777. if (FLockLevel > 0)
  9778. {
  9779. // while we have nesting counter, we know that we never be called
  9780. // recursivelly as Application->OnModalBegin is called only
  9781. // for the top-level modal window
  9782. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9783. {
  9784. // won't be disabled when conditions in LockWindow() were not satisfied
  9785. FDisabledOnLockSuspend = !Enabled;
  9786. // When minimized to tray (or actually when set to SW_HIDE),
  9787. // setting Enabled makes the window focusable even when there's
  9788. // modal window over it
  9789. if (!FTrayIcon->Visible)
  9790. {
  9791. Enabled = true;
  9792. }
  9793. }
  9794. FLockSuspendLevel++;
  9795. }
  9796. }
  9797. //---------------------------------------------------------------------------
  9798. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9799. {
  9800. if (FLockSuspendLevel > 0)
  9801. {
  9802. DebugAssert(FLockLevel > 0);
  9803. FLockSuspendLevel--;
  9804. // see comment in SuspendWindowLock
  9805. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9806. {
  9807. // Note that window can be enabled here, when we were minized to tray when
  9808. // was SuspendWindowLock() called.
  9809. // We should possibly do the same check as in LockWindow(),
  9810. // if it is ever possible that the consitions change between
  9811. // SuspendWindowLock() and ResumeWindowLock()
  9812. Enabled = !FDisabledOnLockSuspend;
  9813. }
  9814. }
  9815. }
  9816. //---------------------------------------------------------------------------
  9817. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9818. {
  9819. TTBXComboBoxItem * RemotePathComboBox =
  9820. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9821. if (!TextOnly)
  9822. {
  9823. TStrings * Items = RemotePathComboBox->Strings;
  9824. Items->BeginUpdate();
  9825. try
  9826. {
  9827. Items->Clear();
  9828. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9829. {
  9830. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9831. while (!IsUnixRootPath(APath))
  9832. {
  9833. int P = APath.LastDelimiter(L'/');
  9834. DebugAssert(P >= 0);
  9835. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9836. APath.SetLength(P - 1);
  9837. }
  9838. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9839. }
  9840. }
  9841. __finally
  9842. {
  9843. Items->EndUpdate();
  9844. }
  9845. }
  9846. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9847. // Setting ItemIndex to -1 does not reset its text
  9848. if (RemotePathComboBox->Strings->Count == 0)
  9849. {
  9850. RemotePathComboBox->Text = L"";
  9851. }
  9852. }
  9853. //---------------------------------------------------------------------------
  9854. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9855. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9856. {
  9857. if (AIndex < 0)
  9858. {
  9859. AIndex = Sender->ItemIndex;
  9860. }
  9861. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9862. }
  9863. //---------------------------------------------------------------------------
  9864. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9865. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9866. int & ImageIndex)
  9867. {
  9868. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9869. }
  9870. //---------------------------------------------------------------------------
  9871. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9872. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9873. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9874. {
  9875. if (!IsLocalBrowserMode())
  9876. {
  9877. ARect.Left += (10 * AIndex);
  9878. }
  9879. }
  9880. //---------------------------------------------------------------------------
  9881. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9882. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9883. {
  9884. AWidth += (10 * AIndex);
  9885. }
  9886. //---------------------------------------------------------------------------
  9887. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9888. {
  9889. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9890. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9891. int Index = RemotePathComboBox->ItemIndex;
  9892. while (Index < RemotePathComboBox->Strings->Count - 1)
  9893. {
  9894. APath = UnixExtractFileDir(APath);
  9895. Index++;
  9896. }
  9897. // VanDyke style paths
  9898. if (APath.IsEmpty())
  9899. {
  9900. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9901. APath = ROOTDIRECTORY;
  9902. }
  9903. if (RemoteDirView->Path != APath)
  9904. {
  9905. RemoteDirView->Path = APath;
  9906. }
  9907. }
  9908. //---------------------------------------------------------------------------
  9909. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9910. {
  9911. DoRemotePathComboBoxItemClick(Sender);
  9912. }
  9913. //---------------------------------------------------------------------------
  9914. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9915. {
  9916. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9917. DebugUsedParam(Sender);
  9918. UpdateRemotePathComboBox(true);
  9919. }
  9920. //---------------------------------------------------------------------------
  9921. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9922. {
  9923. DoRemotePathComboBoxCancel(Sender);
  9924. }
  9925. //---------------------------------------------------------------------------
  9926. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9927. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9928. {
  9929. ResetIncrementalSearch();
  9930. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9931. DebugAssert(DirView != NULL);
  9932. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9933. {
  9934. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9935. // OnEditing is called also from TCustomListView::CanEdit
  9936. if (Edit != NULL)
  9937. {
  9938. EditSelectBaseName(Edit);
  9939. }
  9940. }
  9941. }
  9942. //---------------------------------------------------------------------------
  9943. //---------------------------------------------------------------------------
  9944. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9945. {
  9946. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9947. Result->AutoDetectDnD = false;
  9948. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9949. Result->RenderDataOn = rdoEnterAndDropSync;
  9950. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9951. return Result;
  9952. }
  9953. //---------------------------------------------------------------------------
  9954. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9955. {
  9956. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9957. UseDarkMode(this);
  9958. }
  9959. //---------------------------------------------------------------------------
  9960. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9961. {
  9962. TForm::CreateWnd();
  9963. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9964. UpdateDarkMode();
  9965. if (FSessionsDragDropFilesEx == NULL)
  9966. {
  9967. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9968. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9969. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9970. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9971. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9972. }
  9973. if (FQueueDragDropFilesEx == NULL)
  9974. {
  9975. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9976. // No need to set OnDragOver as we do not have any restrictions
  9977. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9978. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9979. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9980. }
  9981. }
  9982. //---------------------------------------------------------------------------
  9983. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9984. {
  9985. TForm::DestroyWnd();
  9986. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9987. FQueueDragDropFilesEx->DragDropControl = NULL;
  9988. }
  9989. //---------------------------------------------------------------------------
  9990. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9991. {
  9992. SideEnter(FCurrentSide);
  9993. FEverShown = true;
  9994. }
  9995. //---------------------------------------------------------------------------
  9996. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9997. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9998. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9999. {
  10000. if (!NonVisualDataModule->Busy)
  10001. {
  10002. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  10003. Configuration->Usage->Inc(L"FileFinds");
  10004. LockWindow(true);
  10005. NonVisualDataModule->StartBusy();
  10006. WinConfiguration->LockedInterface = true;
  10007. try
  10008. {
  10009. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  10010. }
  10011. __finally
  10012. {
  10013. WinConfiguration->LockedInterface = false;
  10014. NonVisualDataModule->EndBusy();
  10015. UnlockWindow();
  10016. }
  10017. }
  10018. }
  10019. //---------------------------------------------------------------------------
  10020. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  10021. {
  10022. if (!NonVisualDataModule->Busy)
  10023. {
  10024. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  10025. SetFocus();
  10026. RemoteDirView->Path = UnixExtractFilePath(Path);
  10027. UnicodeString FileName = UnixExtractFileName(Path);
  10028. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  10029. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  10030. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  10031. if (Item == NULL)
  10032. {
  10033. ReloadDirectory(osRemote);
  10034. Item = RemoteDirView->FindFileItem(FileName);
  10035. }
  10036. if (Item != NULL)
  10037. {
  10038. RemoteDirView->ItemFocused = Item;
  10039. RemoteDirView->ItemFocused->MakeVisible(false);
  10040. RemoteDirView->SetFocus();
  10041. }
  10042. }
  10043. }
  10044. //---------------------------------------------------------------------------
  10045. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  10046. {
  10047. bool Result = !NonVisualDataModule->Busy;
  10048. if (Result)
  10049. {
  10050. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  10051. }
  10052. return Result;
  10053. }
  10054. //---------------------------------------------------------------------------
  10055. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  10056. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10057. {
  10058. if (CanOperateOnFoundFiles(ATerminal))
  10059. {
  10060. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished, OnFileOperationFinished);
  10061. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  10062. }
  10063. }
  10064. //---------------------------------------------------------------------------
  10065. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  10066. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10067. {
  10068. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  10069. }
  10070. //---------------------------------------------------------------------------
  10071. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  10072. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10073. {
  10074. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  10075. }
  10076. //---------------------------------------------------------------------------
  10077. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  10078. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10079. {
  10080. if (CanOperateOnFoundFiles(ATerminal))
  10081. {
  10082. for (int Index = 0; Index < FileList->Count; Index++)
  10083. {
  10084. UnicodeString FileName = FileList->Strings[Index];
  10085. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  10086. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  10087. OnFileOperationFinished(osRemote, FileName, true, true);
  10088. }
  10089. }
  10090. }
  10091. //---------------------------------------------------------------------------
  10092. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  10093. {
  10094. FFileFindTerminal = Terminal;
  10095. ShowFileFindDialog(
  10096. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  10097. DoDownloadFoundFiles, DoEditFoundFiles);
  10098. }
  10099. //---------------------------------------------------------------------------
  10100. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  10101. {
  10102. FTaskbarList = TaskbarList;
  10103. }
  10104. //---------------------------------------------------------------------------
  10105. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  10106. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  10107. {
  10108. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10109. if (Index >= 0)
  10110. {
  10111. if (Button == mbLeft)
  10112. {
  10113. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  10114. // If switching tab (switching session) takes long enough for user
  10115. // to actually release the button, "mouse down" is still raised,
  10116. // but we do not get "mouse up" event, so dragging is not cancelled,
  10117. // prevent that by not beginning dragging in the first place.
  10118. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  10119. if (IsKeyPressed(Key))
  10120. {
  10121. // when user clicks the "+", we get mouse down only after the session
  10122. // is closed, when new session tab is already on X:Y, so dragging
  10123. // starts, prevent that
  10124. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  10125. {
  10126. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10127. if (Terminal != NULL)
  10128. {
  10129. SessionsPageControl->BeginDrag(false);
  10130. }
  10131. }
  10132. }
  10133. }
  10134. else if (Button == mbMiddle)
  10135. {
  10136. // ignore middle-click for "New session tab" and the last local-local tab
  10137. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10138. if ((Session != NULL) && CanCloseSession(Session))
  10139. {
  10140. CloseSessionTab(Index);
  10141. }
  10142. }
  10143. }
  10144. }
  10145. //---------------------------------------------------------------------------
  10146. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10147. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10148. {
  10149. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10150. // do not allow dropping on the "+" tab
  10151. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10152. if ((TargetTerminal != NULL) &&
  10153. (SessionsPageControl->ActivePage->PageIndex != Index))
  10154. {
  10155. Configuration->Usage->Inc(L"SessionTabMoves");
  10156. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10157. // but we want to actually prevent that to avoid flicker
  10158. SessionsPageControl->ActivePage->PageIndex = Index;
  10159. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10160. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10161. }
  10162. }
  10163. //---------------------------------------------------------------------------
  10164. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10165. TObject * Sender, TObject * Source, int X, int Y,
  10166. TDragState /*State*/, bool & Accept)
  10167. {
  10168. Accept = (Sender == Source);
  10169. if (Accept)
  10170. {
  10171. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10172. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10173. // do not allow dragging to the "+" tab
  10174. Accept = (Terminal != NULL);
  10175. }
  10176. }
  10177. //---------------------------------------------------------------------------
  10178. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10179. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10180. {
  10181. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10182. if (Index < 0)
  10183. {
  10184. Effect = DROPEFFECT_NONE;
  10185. }
  10186. else
  10187. {
  10188. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10189. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10190. if (!IsAvailableTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10191. {
  10192. Effect = DROPEFFECT_NONE;
  10193. }
  10194. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10195. {
  10196. Effect = DROPEFFECT_COPY;
  10197. }
  10198. }
  10199. }
  10200. //---------------------------------------------------------------------------
  10201. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10202. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10203. {
  10204. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10205. // do not allow dropping on local-local, disconnected and the "+" tab
  10206. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10207. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10208. if (DebugAlwaysTrue(IsAvailableTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10209. {
  10210. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10211. if (!IsFileControl(DropSourceControl, osRemote))
  10212. {
  10213. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10214. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10215. // Why don't we use Terminal->CurrentDirectory directly?
  10216. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10217. // do not force queue, drag drop
  10218. false, true);
  10219. }
  10220. }
  10221. }
  10222. //---------------------------------------------------------------------------
  10223. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10224. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10225. {
  10226. // Downloads are handled in RemoteFileControlDDEnd
  10227. if (!IsFileControl(DropSourceControl, osRemote))
  10228. {
  10229. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10230. Terminal->CurrentDirectory,
  10231. // force queue, drag drop
  10232. true, true);
  10233. }
  10234. }
  10235. //---------------------------------------------------------------------------
  10236. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10237. {
  10238. FShowing = false;
  10239. // Do not save empty workspace
  10240. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10241. {
  10242. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10243. UnicodeString Name = WorkspaceName();
  10244. DoSaveWorkspace(
  10245. Name, DataList.get(),
  10246. !Configuration->DisablePasswordStoring &&
  10247. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10248. WinConfiguration->LastStoredSession = Name;
  10249. }
  10250. AppLog(L"Closing main window");
  10251. }
  10252. //---------------------------------------------------------------------------
  10253. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10254. {
  10255. TManagedTerminal * ManagedTerminal =
  10256. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10257. if (ManagedTerminal != NULL)
  10258. {
  10259. ManagedTerminal->DirectoryLoaded = Now();
  10260. }
  10261. }
  10262. //---------------------------------------------------------------------------
  10263. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10264. TListItem * /*Item*/, bool /*Selected*/)
  10265. {
  10266. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10267. switch (DirView->LastSelectMethod)
  10268. {
  10269. case smKeyboard:
  10270. Configuration->Usage->Inc(L"KeyboardSelections");
  10271. break;
  10272. case smMouse:
  10273. Configuration->Usage->Inc(L"MouseSelections");
  10274. break;
  10275. }
  10276. }
  10277. //---------------------------------------------------------------------------
  10278. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10279. {
  10280. if (Color != 0)
  10281. {
  10282. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10283. }
  10284. else
  10285. {
  10286. return FSessionTabImageIndex;
  10287. }
  10288. }
  10289. //---------------------------------------------------------------------------
  10290. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10291. {
  10292. TPngImageCollectionItem * Item =
  10293. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10294. FSessionColors->AddPng(Item->PngImage);
  10295. return FSessionColors->Count - 1;
  10296. }
  10297. //---------------------------------------------------------------------------
  10298. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10299. {
  10300. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10301. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10302. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10303. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10304. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10305. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10306. }
  10307. //---------------------------------------------------------------------------
  10308. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10309. {
  10310. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10311. }
  10312. //---------------------------------------------------------------------------
  10313. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10314. {
  10315. switch (Side)
  10316. {
  10317. case osLocal:
  10318. return FNewLocalTabTabImageIndex;
  10319. case osRemote:
  10320. case osCurrent:
  10321. return FNewRemoteTabTabImageIndex;
  10322. default:
  10323. DebugFail();
  10324. return -1;
  10325. }
  10326. }
  10327. //---------------------------------------------------------------------------
  10328. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10329. {
  10330. for (int Index = 0; Index < Control->ControlCount; Index++)
  10331. {
  10332. TControl * AControl = Control->Controls[Index];
  10333. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10334. if (WinControl != NULL)
  10335. {
  10336. CollectItemsWithTextDisplayMode(WinControl);
  10337. }
  10338. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10339. if (Toolbar != NULL)
  10340. {
  10341. // we care for top-level items only
  10342. TTBCustomItem * Items = Toolbar->Items;
  10343. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10344. {
  10345. TTBCustomItem * Item = Items->Items[ItemIndex];
  10346. if (((Item->DisplayMode == nbdmImageAndText) ||
  10347. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10348. EligibleForImageDisplayMode(Item))
  10349. {
  10350. FItemsWithTextDisplayMode.insert(Item);
  10351. }
  10352. }
  10353. }
  10354. }
  10355. }
  10356. //---------------------------------------------------------------------------
  10357. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10358. {
  10359. return true;
  10360. }
  10361. //---------------------------------------------------------------------------
  10362. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10363. {
  10364. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10365. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10366. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10367. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10368. bool Result = true;
  10369. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10370. {
  10371. TTBCustomItem * Item = *i;
  10372. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10373. if (Label != NULL)
  10374. {
  10375. // optimization
  10376. if (Label->Visible == SelectiveToolbarText)
  10377. {
  10378. Result = false;
  10379. }
  10380. else
  10381. {
  10382. Label->Visible = SelectiveToolbarText;
  10383. }
  10384. }
  10385. else
  10386. {
  10387. // optimization
  10388. if (Item->DisplayMode == DisplayMode)
  10389. {
  10390. Result = false;
  10391. }
  10392. else
  10393. {
  10394. Item->DisplayMode = DisplayMode;
  10395. }
  10396. }
  10397. ++i;
  10398. }
  10399. UpdateNewTabTab();
  10400. return Result;
  10401. }
  10402. //---------------------------------------------------------------------------
  10403. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10404. {
  10405. DebugFail();
  10406. }
  10407. //---------------------------------------------------------------------------
  10408. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10409. {
  10410. // Among other, a lock level is non zero, while directory is being loaded,
  10411. // even when it happens as a result of dirview navigation,
  10412. // i.e. when TNonVisualDataModule is NOT FBusy.
  10413. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10414. // Among other this prevents a panel auto update to occur while
  10415. // directory is changing.
  10416. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10417. }
  10418. //---------------------------------------------------------------------------
  10419. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10420. {
  10421. // While the window is disabled, we still seem to process menu shortcuts at least,
  10422. // so stop it at least here.
  10423. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10424. bool Result;
  10425. if (Allowed == aaUpdate)
  10426. {
  10427. Result = true;
  10428. }
  10429. else
  10430. {
  10431. Result = !NonVisualDataModule->Busy;
  10432. if (Result && (Allowed == aaShortCut))
  10433. {
  10434. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10435. Action->Update();
  10436. Result = Action->Enabled;
  10437. }
  10438. }
  10439. return Result;
  10440. }
  10441. //---------------------------------------------------------------------------
  10442. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10443. {
  10444. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10445. }
  10446. //---------------------------------------------------------------------------
  10447. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10448. {
  10449. // This is somewhat redundant to LockWindow() call from
  10450. // TTerminalManager::TerminalReadDirectoryProgress.
  10451. // But disabling window is known not to block keyboard shorcuts
  10452. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10453. if (Busy > 0)
  10454. {
  10455. if (NonVisualDataModule->Busy)
  10456. {
  10457. State = false;
  10458. }
  10459. else
  10460. {
  10461. NonVisualDataModule->StartBusy();
  10462. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10463. LockWindow();
  10464. }
  10465. }
  10466. else if (Busy < 0)
  10467. {
  10468. UnlockWindow();
  10469. NonVisualDataModule->EndBusy();
  10470. }
  10471. else
  10472. {
  10473. State = NonVisualDataModule->Busy;
  10474. }
  10475. }
  10476. //---------------------------------------------------------------------------
  10477. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10478. {
  10479. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10480. if (Index >= 0)
  10481. {
  10482. TPopupMenu * PopupMenu = NULL;
  10483. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10484. if (Session != NULL)
  10485. {
  10486. SessionsPageControl->ActivePageIndex = Index;
  10487. if (DebugAlwaysTrue(SessionTabSwitched()))
  10488. {
  10489. // copied from TControl.WMContextMenu
  10490. SendCancelMode(SessionsPageControl);
  10491. // explicit popup instead of using PopupMenu property
  10492. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10493. // while connecting yet not-connected session and hence
  10494. // allowing an access to commands over not-completely connected session
  10495. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10496. }
  10497. }
  10498. else
  10499. {
  10500. if (SupportsLocalBrowser())
  10501. {
  10502. PopupMenu = NonVisualDataModule->NewTabPopup;
  10503. }
  10504. }
  10505. if (PopupMenu != NULL)
  10506. {
  10507. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10508. PopupMenu->PopupComponent = SessionsPageControl;
  10509. PopupMenu->Popup(Point.x, Point.y);
  10510. }
  10511. }
  10512. Handled = true;
  10513. }
  10514. //---------------------------------------------------------------------------
  10515. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10516. {
  10517. return HasAvailableTerminal() && Terminal->IsCapable[fcChangePassword];
  10518. }
  10519. //---------------------------------------------------------------------------
  10520. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10521. {
  10522. Configuration->Usage->Inc(L"PasswordChanges");
  10523. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10524. ChangePasswordData->DisableAuthentationsExceptPassword();
  10525. ChangePasswordData->ChangePassword = true;
  10526. std::unique_ptr<TTerminal> ChangePasswordSession(
  10527. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10528. ChangePasswordSession->AutoReadDirectory = false;
  10529. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10530. {
  10531. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10532. }
  10533. else
  10534. {
  10535. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10536. }
  10537. }
  10538. //---------------------------------------------------------------------------
  10539. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10540. {
  10541. // No nice way to assert SSH2
  10542. return HasAvailableTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10543. }
  10544. //---------------------------------------------------------------------------
  10545. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10546. {
  10547. TOperationVisualizer OperationVisualizer;
  10548. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10549. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10550. }
  10551. //---------------------------------------------------------------------------
  10552. void __fastcall TCustomScpExplorerForm::FormAfterMonitorDpiChanged(TObject *, int OldDPI, int NewDPI)
  10553. {
  10554. DebugUsedParam(OldDPI);
  10555. DebugAssert(NewDPI == GetControlPixelsPerInch(this));
  10556. GlyphsModule->PixelsPerInch = NewDPI;
  10557. // Can be called too early when primary monitor has non-system dpi
  10558. if (FSessionColors != NULL)
  10559. {
  10560. RegenerateSessionColorsImageList();
  10561. }
  10562. UpdateTabsSize();
  10563. UpdateSessionsPageControlHeight();
  10564. QueueFileListColumnAutoSize();
  10565. }
  10566. //---------------------------------------------------------------------------
  10567. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10568. {
  10569. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10570. }
  10571. //---------------------------------------------------------------------
  10572. class TPublicControl : public TControl
  10573. {
  10574. friend class TCustomScpExplorerForm;
  10575. };
  10576. //---------------------------------------------------------------------------
  10577. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10578. {
  10579. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10580. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10581. }
  10582. //---------------------------------------------------------------------------
  10583. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10584. {
  10585. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10586. OpenBookmark(Side, Bookmark);
  10587. }
  10588. //---------------------------------------------------------------------------
  10589. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10590. {
  10591. DoBookmarkClick(osLocal, Sender);
  10592. }
  10593. //---------------------------------------------------------------------------
  10594. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10595. {
  10596. DoBookmarkClick(osRemote, Sender);
  10597. }
  10598. //---------------------------------------------------------------------------
  10599. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10600. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10601. {
  10602. if (BookmarkList != NULL)
  10603. {
  10604. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10605. if (IsLocalBrowserMode())
  10606. {
  10607. Side = osLocal;
  10608. }
  10609. if (!WinConfiguration->UseLocationProfiles)
  10610. {
  10611. std::unique_ptr<TStringList> Directories(new TStringList());
  10612. Directories->CaseSensitive = (Side == osRemote);
  10613. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10614. {
  10615. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10616. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10617. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10618. {
  10619. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10620. Item->Caption = EscapeHotkey(Directory);
  10621. Item->ShortCut = Bookmark->ShortCut;
  10622. Item->OnClick = OnBookmarkClick;
  10623. Item->Tag = reinterpret_cast<int>(Bookmark);
  10624. Directories->Add(Directory);
  10625. Menu->Add(Item.release());
  10626. }
  10627. }
  10628. }
  10629. else
  10630. {
  10631. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10632. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10633. {
  10634. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10635. if (!Bookmark->Node.IsEmpty())
  10636. {
  10637. Folders->Add(Bookmark->Node);
  10638. }
  10639. }
  10640. for (int Index = 0; Index < Folders->Count; Index++)
  10641. {
  10642. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10643. Item->Caption = Folders->Strings[Index];
  10644. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10645. Folders->Objects[Index] = Item.get();
  10646. Menu->Add(Item.release());
  10647. }
  10648. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10649. {
  10650. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10651. TTBCustomItem * Parent;
  10652. if (!Bookmark->Node.IsEmpty())
  10653. {
  10654. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10655. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10656. }
  10657. else
  10658. {
  10659. Parent = Menu;
  10660. }
  10661. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10662. Item->Caption = Bookmark->Name;
  10663. Item->ShortCut = Bookmark->ShortCut;
  10664. Item->OnClick = OnBookmarkClick;
  10665. Item->Tag = reinterpret_cast<int>(Bookmark);
  10666. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10667. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10668. {
  10669. // No hint for location profiles that are actually mere "bookmarks"
  10670. }
  10671. else
  10672. {
  10673. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10674. UnicodeString LongHint;
  10675. if (!Bookmark->Local.IsEmpty())
  10676. {
  10677. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10678. }
  10679. if (!Bookmark->Remote.IsEmpty())
  10680. {
  10681. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10682. }
  10683. AddToList(Hint, LongHint, L"|");
  10684. Item->Hint = Hint;
  10685. }
  10686. Parent->Add(Item.release());
  10687. }
  10688. }
  10689. AddMenuSeparator(Menu);
  10690. }
  10691. }
  10692. //---------------------------------------------------------------------------
  10693. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10694. {
  10695. Menu->Clear();
  10696. std::unique_ptr<TTBCustomItem> Item;
  10697. Item.reset(new TTBXItem(Owner));
  10698. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10699. Item->Options = Item->Options << tboDefault;
  10700. Menu->Add(Item.release());
  10701. AddMenuSeparator(Menu);
  10702. if (Terminal != NULL)
  10703. {
  10704. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10705. }
  10706. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10707. Item.reset(new TTBXItem(Owner));
  10708. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10709. Menu->Add(Item.release());
  10710. }
  10711. //---------------------------------------------------------------------------
  10712. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10713. {
  10714. bool Result = true;
  10715. bool Remote = !IsSideLocalBrowser(Side);
  10716. try
  10717. {
  10718. UnicodeString APath = Path;
  10719. if (Remote)
  10720. {
  10721. Terminal->ExceptionOnFail = true;
  10722. }
  10723. else
  10724. {
  10725. APath = ExpandEnvironmentVariables(Path);
  10726. }
  10727. try
  10728. {
  10729. DirView(Side)->Path = APath;
  10730. }
  10731. __finally
  10732. {
  10733. if (Remote)
  10734. {
  10735. Terminal->ExceptionOnFail = false;
  10736. }
  10737. }
  10738. }
  10739. catch (Exception & E)
  10740. {
  10741. if (!Remote || Terminal->Active)
  10742. {
  10743. ShowExtendedExceptionEx(Terminal, &E);
  10744. Result = false;
  10745. }
  10746. else
  10747. {
  10748. throw;
  10749. }
  10750. }
  10751. return Result;
  10752. }
  10753. //---------------------------------------------------------------------------
  10754. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10755. {
  10756. // Make sure there some feedback even when loading tiny local folders
  10757. TInstantOperationVisualizer Visualizer;
  10758. DirView(Side)->ReloadDirectory();
  10759. }
  10760. //---------------------------------------------------------------------------
  10761. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10762. {
  10763. if (Index == SessionsPageControl->TabIndex)
  10764. {
  10765. CloseTab();
  10766. }
  10767. else
  10768. {
  10769. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10770. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10771. TTerminalManager * Manager = TTerminalManager::Instance();
  10772. if (!Terminal->Active)
  10773. {
  10774. Manager->FreeTerminal(Terminal);
  10775. }
  10776. else
  10777. {
  10778. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10779. if (CanCloseQueue(Queue))
  10780. {
  10781. Manager->FreeTerminal(Terminal);
  10782. }
  10783. }
  10784. }
  10785. }
  10786. //---------------------------------------------------------------------------
  10787. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10788. {
  10789. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10790. if (Session == NULL)
  10791. {
  10792. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10793. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10794. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10795. //P = SessionsPageControl->ClientToScreen(P);
  10796. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10797. }
  10798. else
  10799. {
  10800. CloseSessionTab(Index);
  10801. }
  10802. }
  10803. //---------------------------------------------------------------------------
  10804. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10805. {
  10806. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10807. {
  10808. TInstantOperationVisualizer Visualizer;
  10809. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10810. // before we create a new data object
  10811. ClipboardClear();
  10812. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10813. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10814. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10815. // Intermediate variable to WORKAROUND a crash in compiler
  10816. TObjectList * ClipboardFakeMonitors =
  10817. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10818. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10819. if (FClipboardDragDropFilesEx.get() == NULL)
  10820. {
  10821. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10822. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10823. }
  10824. FClipboardDragDropFilesEx->FileList->Clear();
  10825. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10826. FClipboardDragDropFilesEx->CopyToClipboard();
  10827. FClipboardTerminal = Terminal;
  10828. // Need full paths, as cwd can be different once files are pasted
  10829. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10830. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10831. {
  10832. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10833. }
  10834. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10835. }
  10836. }
  10837. //---------------------------------------------------------------------------
  10838. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10839. {
  10840. if (OpenClipboard(0))
  10841. {
  10842. AppLog(L"Clearing clipboard");
  10843. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10844. CloseClipboard();
  10845. }
  10846. }
  10847. //---------------------------------------------------------------------------
  10848. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10849. {
  10850. return !FClipboardFakeDirectory.IsEmpty();
  10851. }
  10852. //---------------------------------------------------------------------------
  10853. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10854. {
  10855. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10856. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10857. FClipboardFakeDirectory = UnicodeString();
  10858. FClipboardTerminal = NULL;
  10859. if (FDownloadingFromClipboard)
  10860. {
  10861. // We are called by the monitor, so attempt to release it would deadlock
  10862. FClipboardFakeMonitorsPendingReset = true;
  10863. }
  10864. else
  10865. {
  10866. FClipboardFakeMonitors.reset(NULL);
  10867. }
  10868. }
  10869. //---------------------------------------------------------------------------
  10870. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10871. {
  10872. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10873. {
  10874. ClipboardStop();
  10875. }
  10876. }
  10877. //---------------------------------------------------------------------------
  10878. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10879. {
  10880. TTerminalManager * Manager = TTerminalManager::Instance();
  10881. Manager->ActiveSession = FClipboardTerminal;
  10882. TTransferOperationParam Params;
  10883. Params.TargetDirectory = TargetDirectory;
  10884. Params.DragDrop = DragDrop;
  10885. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10886. }
  10887. //---------------------------------------------------------------------------
  10888. void TCustomScpExplorerForm::PasteFiles()
  10889. {
  10890. // Guard against possible race conditions
  10891. if (!FClipboardPasteTarget.IsEmpty())
  10892. {
  10893. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10894. UnicodeString Target = FClipboardPasteTarget;
  10895. FClipboardPasteTarget = EmptyStr;
  10896. // Can fail as it can be e.g. locked by AV, so we retry that later
  10897. bool Removed = RemoveDir(ApiPath(Target));
  10898. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10899. try
  10900. {
  10901. if (NonVisualDataModule->Busy)
  10902. {
  10903. AppLog(L"Is busy, cannot paste");
  10904. }
  10905. else
  10906. {
  10907. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10908. FClipboardFakeMonitorsPendingReset = false;
  10909. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10910. TAutoFlag Flag(FDownloadingFromClipboard);
  10911. AppLog(L"Downloading to paste target...");
  10912. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10913. AppLog(L"Downloaded to paste target...");
  10914. }
  10915. }
  10916. __finally
  10917. {
  10918. if (!Removed)
  10919. {
  10920. Removed = RemoveDir(ApiPath(Target));
  10921. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10922. }
  10923. }
  10924. }
  10925. }
  10926. //---------------------------------------------------------------------------
  10927. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10928. {
  10929. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10930. // (as it pumps a Windows message queue while being shutted down)
  10931. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10932. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10933. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10934. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10935. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10936. {
  10937. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10938. FClipboardPasteTarget = FileName;
  10939. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10940. // Postponing removing (or actually whole pasting operation) seems to help.
  10941. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10942. }
  10943. }
  10944. //---------------------------------------------------------------------------
  10945. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10946. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10947. {
  10948. TFileMasks::TParams MaskParams;
  10949. MaskParams.Size = Size;
  10950. MaskParams.Modification = Modification;
  10951. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10952. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10953. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10954. if (!Local && Directory)
  10955. {
  10956. FileName = UnixExcludeTrailingBackslash(FileName);
  10957. }
  10958. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10959. {
  10960. bool ImplicitMatch;
  10961. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10962. !ImplicitMatch)
  10963. {
  10964. Color = Iter->Color;
  10965. break;
  10966. }
  10967. }
  10968. }
  10969. //---------------------------------------------------------------------------
  10970. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10971. {
  10972. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10973. if (!DirView->IsEditing())
  10974. {
  10975. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10976. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10977. // while searching
  10978. if (Key == VK_BACK)
  10979. {
  10980. if (FIncrementalSearchState.Searching)
  10981. {
  10982. if (FIncrementalSearchState.Text.Length() <= 1)
  10983. {
  10984. ResetIncrementalSearch();
  10985. }
  10986. else
  10987. {
  10988. UnicodeString NewText = LeftStr(FIncrementalSearchState.Text, FIncrementalSearchState.Text.Length() - 1);
  10989. IncrementalSearch(NewText, false, false);
  10990. }
  10991. Key = 0;
  10992. }
  10993. }
  10994. }
  10995. }
  10996. //---------------------------------------------------------------------------
  10997. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10998. {
  10999. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  11000. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  11001. {
  11002. // Filter control sequences.
  11003. // When not searching yet, prefer use of the space for toggling file selection
  11004. // (so we cannot incrementally search for a string starting with a space).
  11005. if ((Key > VK_SPACE) ||
  11006. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && FIncrementalSearchState.Searching))
  11007. {
  11008. IncrementalSearch(FIncrementalSearchState.Text + Key, false, false);
  11009. Key = 0;
  11010. }
  11011. }
  11012. }
  11013. //---------------------------------------------------------------------------
  11014. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  11015. {
  11016. if (FIncrementalSearchState.Searching)
  11017. {
  11018. FIncrementalSearchState.Reset();
  11019. DirView(osCurrent)->UpdateStatusBar();
  11020. }
  11021. }
  11022. //---------------------------------------------------------------------------
  11023. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  11024. {
  11025. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  11026. if (Item == NULL)
  11027. {
  11028. MessageBeep(MB_ICONHAND);
  11029. }
  11030. else
  11031. {
  11032. TCustomDirView * ADirView = DirView(osCurrent);
  11033. {
  11034. TAutoNestingCounter Guard(FIncrementalSearching);
  11035. ADirView->FocusItem(Item);
  11036. if (ADirView->NortonLike == nlOff)
  11037. {
  11038. if ((ADirView->Selected != Item) ||
  11039. (ADirView->SelCount > 1))
  11040. {
  11041. ADirView->ClearSelection();
  11042. ADirView->Selected = Item;
  11043. }
  11044. }
  11045. }
  11046. FIncrementalSearchState.Searching = true;
  11047. FIncrementalSearchState.Text = Text;
  11048. Item->MakeVisible(false);
  11049. TListItem * NextItem = SearchFile(Text, true, Reverse);
  11050. FIncrementalSearchState.HaveNext = (NextItem != NULL) && (NextItem != Item);
  11051. ADirView->UpdateStatusBar();
  11052. }
  11053. }
  11054. //---------------------------------------------------------------------------
  11055. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  11056. {
  11057. int Index = Item->Index;
  11058. if (!Reverse)
  11059. {
  11060. Index++;
  11061. if (Index >= Item->Owner->Count)
  11062. {
  11063. Index = 0;
  11064. }
  11065. }
  11066. else
  11067. {
  11068. Index--;
  11069. if (Index < 0)
  11070. {
  11071. Index = Item->Owner->Count - 1;
  11072. }
  11073. }
  11074. return Item->Owner->Item[Index];
  11075. }
  11076. //---------------------------------------------------------------------------
  11077. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  11078. {
  11079. TCustomDirView * ADirView = DirView(osCurrent);
  11080. if (ADirView->Items->Count == 0)
  11081. {
  11082. return NULL;
  11083. }
  11084. else
  11085. {
  11086. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  11087. TListItem * Item = CurrentItem;
  11088. if (SkipCurrent)
  11089. {
  11090. Item = DebugNotNull(GetNextFile(Item, Reverse));
  11091. }
  11092. while (true)
  11093. {
  11094. bool Matches = false;
  11095. switch (WinConfiguration->PanelSearch)
  11096. {
  11097. case isNameStartOnly:
  11098. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  11099. break;
  11100. case isName:
  11101. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  11102. break;
  11103. case isAll:
  11104. int ColCount = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Count : 1;
  11105. int Index = 0;
  11106. while ((Index < ColCount) && !Matches)
  11107. {
  11108. bool Visible = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Visible[Index] : true;
  11109. if (Visible)
  11110. {
  11111. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  11112. }
  11113. Index++;
  11114. }
  11115. break;
  11116. }
  11117. if (Matches)
  11118. {
  11119. return Item;
  11120. }
  11121. Item = GetNextFile(Item, Reverse);
  11122. if (Item == CurrentItem)
  11123. {
  11124. return NULL;
  11125. }
  11126. }
  11127. }
  11128. }
  11129. //---------------------------------------------------------------------------
  11130. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  11131. {
  11132. ResetIncrementalSearch();
  11133. }
  11134. //---------------------------------------------------------------------------
  11135. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  11136. {
  11137. if (Message.CharCode == VK_TAB)
  11138. {
  11139. if (!FIncrementalSearchState.Text.IsEmpty())
  11140. {
  11141. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11142. bool Reverse = Shift.Contains(ssShift);
  11143. IncrementalSearch(FIncrementalSearchState.Text, true, Reverse);
  11144. Message.Result = 1;
  11145. return;
  11146. }
  11147. }
  11148. else if (Message.CharCode == VK_ESCAPE)
  11149. {
  11150. if (FIncrementalSearchState.Searching)
  11151. {
  11152. ResetIncrementalSearch();
  11153. Message.Result = 1;
  11154. return;
  11155. }
  11156. }
  11157. TForm::Dispatch(&Message);
  11158. }
  11159. //---------------------------------------------------------------------------
  11160. void __fastcall TCustomScpExplorerForm::Deactivate()
  11161. {
  11162. TForm::Deactivate();
  11163. // E.g. when switching to an internal editor window
  11164. ResetIncrementalSearch();
  11165. }
  11166. //---------------------------------------------------------------------------
  11167. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11168. {
  11169. // When switching to another application
  11170. ResetIncrementalSearch();
  11171. }
  11172. //---------------------------------------------------------------------------
  11173. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11174. {
  11175. ResetIncrementalSearch();
  11176. }
  11177. //---------------------------------------------------------------------------
  11178. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11179. {
  11180. if (FIncrementalSearching <= 0)
  11181. {
  11182. ResetIncrementalSearch();
  11183. }
  11184. }
  11185. //---------------------------------------------------------------------------
  11186. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11187. {
  11188. CountClicksForWindowPrint(this);
  11189. }
  11190. //---------------------------------------------------------------------------
  11191. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11192. {
  11193. CenterReconnectToolbar();
  11194. }
  11195. //---------------------------------------------------------------------------
  11196. void TCustomScpExplorerForm::DoExploreFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11197. {
  11198. if (!FileName.IsEmpty())
  11199. {
  11200. DirView->FocusByName(FileName);
  11201. if (DirView->ItemFocused != NULL)
  11202. {
  11203. DirView->ItemFocused->Selected = true;
  11204. }
  11205. }
  11206. }
  11207. //---------------------------------------------------------------------------
  11208. void __fastcall TCustomScpExplorerForm::ExploreFile(const UnicodeString & FileName)
  11209. {
  11210. DoExploreFile(RemoteDirView, FileName);
  11211. }
  11212. //---------------------------------------------------------------------------
  11213. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11214. {
  11215. if (!FQueueStatusUpdating)
  11216. {
  11217. bool Refresh;
  11218. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11219. {
  11220. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11221. }
  11222. else
  11223. {
  11224. if (FQueueFileList->GetCount() > 0)
  11225. {
  11226. FQueueFileList->Clear();
  11227. Refresh = true;
  11228. }
  11229. }
  11230. int Count = FQueueFileList->GetCount();
  11231. if (QueueFileList->Items->Count != Count)
  11232. {
  11233. DebugAssert(Refresh);
  11234. QueueFileList->Items->Count = Count;
  11235. }
  11236. if (Refresh)
  11237. {
  11238. QueueFileList->Invalidate();
  11239. }
  11240. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11241. }
  11242. }
  11243. //---------------------------------------------------------------------------
  11244. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11245. {
  11246. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11247. }
  11248. //---------------------------------------------------------------------------
  11249. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11250. {
  11251. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11252. // See TSynchronizeChecklistDialog::UpdateTimer
  11253. if (QueueFileList->Items->Count > 0)
  11254. {
  11255. QueueFileList->Items->Item[0]->MakeVisible(false);
  11256. }
  11257. UpdateQueueFileList();
  11258. }
  11259. //---------------------------------------------------------------------------
  11260. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11261. {
  11262. Active = QueueView3->Focused() || QueueFileList->Focused();
  11263. }
  11264. //---------------------------------------------------------------------------
  11265. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11266. {
  11267. QueueLabelUpdateStatus();
  11268. }
  11269. //---------------------------------------------------------------------------
  11270. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11271. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11272. {
  11273. int State = FQueueFileList->GetState(Item->Index);
  11274. if (State == qfsProcessed)
  11275. {
  11276. Sender->Canvas->Font->Color = clGrayText;
  11277. }
  11278. }
  11279. //---------------------------------------------------------------------------
  11280. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11281. {
  11282. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11283. QueueFileList->Column[0]->Width =
  11284. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11285. }
  11286. //---------------------------------------------------------------------------
  11287. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11288. {
  11289. QueueFileListColumnAutoSize();
  11290. }
  11291. //---------------------------------------------------------------------------
  11292. void __fastcall TCustomScpExplorerForm::CloseApp()
  11293. {
  11294. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11295. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11296. // So we clear the flag here.
  11297. DebugAssert(NonVisualDataModule->Busy);
  11298. NonVisualDataModule->EndBusy();
  11299. try
  11300. {
  11301. Close();
  11302. }
  11303. __finally
  11304. {
  11305. NonVisualDataModule->StartBusy();
  11306. }
  11307. }
  11308. //---------------------------------------------------------------------------
  11309. bool TCustomScpExplorerForm::IsAvailableTerminal(TTerminal * Terminal)
  11310. {
  11311. return TTerminalManager::Instance()->IsAvailableTerminal(Terminal);
  11312. }
  11313. //---------------------------------------------------------------------------
  11314. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  11315. {
  11316. return (ManagedSession != NULL);
  11317. }
  11318. //---------------------------------------------------------------------------
  11319. bool TCustomScpExplorerForm::HasAvailableTerminal()
  11320. {
  11321. return IsAvailableTerminal(Terminal);
  11322. }
  11323. //---------------------------------------------------------------------------
  11324. void TCustomScpExplorerForm::LocalLocalCopy(
  11325. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11326. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11327. {
  11328. DebugFail();
  11329. }
  11330. //---------------------------------------------------------------------------
  11331. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11332. {
  11333. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11334. }
  11335. //---------------------------------------------------------------------------
  11336. void TCustomScpExplorerForm::UpdateTabsSize()
  11337. {
  11338. // 1) Changing tab list triggers the OnResize.
  11339. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11340. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11341. {
  11342. // UpdateTabsCaptionTruncation should be enough
  11343. SessionListChanged(true);
  11344. }
  11345. }
  11346. //---------------------------------------------------------------------------
  11347. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11348. {
  11349. UpdateTabsSize();
  11350. }
  11351. //---------------------------------------------------------------------------
  11352. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11353. {
  11354. if (ASession == ManagedSession)
  11355. {
  11356. UpdateSession(ASession);
  11357. }
  11358. TSessionData * Data = ASession->StateData;
  11359. UnicodeString Result;
  11360. if (Side == osLocal)
  11361. {
  11362. Result = Data->LocalDirectory;
  11363. }
  11364. else if (DebugAlwaysTrue(Side == osOther))
  11365. {
  11366. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11367. }
  11368. return Result;
  11369. }
  11370. //---------------------------------------------------------------------------
  11371. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11372. {
  11373. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11374. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11375. if (Title == Result)
  11376. {
  11377. Result = EmptyStr;
  11378. }
  11379. else
  11380. {
  11381. Result += L"\n";
  11382. }
  11383. return Result;
  11384. }
  11385. //---------------------------------------------------------------------------
  11386. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11387. {
  11388. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11389. if (!ASession->Active)
  11390. {
  11391. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11392. }
  11393. else
  11394. {
  11395. Result += GetSessionPath(ASession, osRemote);
  11396. }
  11397. return Result;
  11398. }
  11399. //---------------------------------------------------------------------------
  11400. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11401. {
  11402. return LoadStr(NEW_REMOTE_TAB_HINT);
  11403. }
  11404. //---------------------------------------------------------------------------
  11405. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11406. {
  11407. if (Index >= 0)
  11408. {
  11409. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11410. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11411. if (TabSession == NULL)
  11412. {
  11413. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11414. if (NewTabTabCaption != TabSheet->Caption)
  11415. {
  11416. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11417. }
  11418. }
  11419. else
  11420. {
  11421. TTerminalManager * Manager = TTerminalManager::Instance();
  11422. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11423. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11424. }
  11425. }
  11426. }
  11427. //---------------------------------------------------------------------------
  11428. typedef std::vector<TListItem *> TListItemsVector;
  11429. struct TCalculateSizeOperation
  11430. {
  11431. TCalculateSizeStats Stats;
  11432. TListItemsVector ListItems;
  11433. size_t Index;
  11434. };
  11435. //---------------------------------------------------------------------------
  11436. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11437. {
  11438. TCalculateSizeOperation CalculateSizeOperation;
  11439. Side = GetSide(Side);
  11440. TCustomDirView * ADirView = DirView(Side);
  11441. bool LocalSide = IsSideLocalBrowser(Side);
  11442. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11443. std::unique_ptr<TStrings> FileList(new TStringList());
  11444. for (int Index = 0; Index < AllFileList->Count; Index++)
  11445. {
  11446. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11447. if (ADirView->ItemIsDirectory(Item))
  11448. {
  11449. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11450. CalculateSizeOperation.ListItems.push_back(Item);
  11451. }
  11452. }
  11453. CalculateSizeOperation.Index = 0;
  11454. __int64 Size = 0;
  11455. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation, &CalculateSizeOperation);
  11456. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11457. FOnFileOperationFinished = DirectorySizeCalculated;
  11458. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation, foCalculateSize);
  11459. TCalculatedSizes CalculatedSizes;
  11460. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11461. if (LocalSide)
  11462. {
  11463. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, Side);
  11464. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11465. }
  11466. else
  11467. {
  11468. TCalculateSizeParams Params;
  11469. Params.Stats = &CalculateSizeOperation.Stats;
  11470. Params.UseCache = true;
  11471. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11472. }
  11473. }
  11474. //---------------------------------------------------------------------------
  11475. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(
  11476. TOperationSide Side, const UnicodeString & FileName, bool Success, bool NotCancelled)
  11477. {
  11478. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11479. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11480. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11481. // optimization
  11482. bool GotExpectedItem =
  11483. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11484. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11485. int Index = -1;
  11486. if (DebugAlwaysTrue(GotExpectedItem))
  11487. {
  11488. Index = FCalculateSizeOperation->Index;
  11489. FCalculateSizeOperation->Index++;
  11490. }
  11491. else
  11492. {
  11493. TListItemsVector::iterator I =
  11494. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11495. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11496. {
  11497. Index = I - FCalculateSizeOperation->ListItems.begin();
  11498. }
  11499. }
  11500. if (DebugAlwaysTrue(Index >= 0) && Success && NotCancelled)
  11501. {
  11502. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11503. ADirView->SetItemCalculatedSize(Item, Size);
  11504. }
  11505. }
  11506. //---------------------------------------------------------------------------
  11507. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11508. {
  11509. Accept = false;
  11510. }
  11511. //---------------------------------------------------------------------------
  11512. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11513. {
  11514. // Send Ctrl+Gray+ to the list view
  11515. TKeyboardState KeyState;
  11516. GetKeyboardState(KeyState);
  11517. TKeyboardState NewKeyState;
  11518. memset(NewKeyState, 0, sizeof(NewKeyState));
  11519. NewKeyState[VK_CONTROL] = 0x81;
  11520. SetKeyboardState(NewKeyState);
  11521. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11522. SetKeyboardState(KeyState);
  11523. }
  11524. //---------------------------------------------------------------------------
  11525. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11526. {
  11527. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11528. }
  11529. //---------------------------------------------------------------------------
  11530. void * TCustomScpExplorerForm::SaveFocus()
  11531. {
  11532. return NULL;
  11533. }
  11534. //---------------------------------------------------------------------------
  11535. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11536. {
  11537. DebugUsedParam(Focus);
  11538. DebugAssert(Focus == NULL);
  11539. }
  11540. //---------------------------------------------------------------------------
  11541. void TCustomScpExplorerForm::IncrementalSearchStart()
  11542. {
  11543. TCustomDirView * ADirView = DirView(osCurrent);
  11544. ADirView->SetFocus();
  11545. if (!FIncrementalSearchState.Searching)
  11546. {
  11547. FIncrementalSearchState.Searching = true;
  11548. FIncrementalSearchState.HaveNext = false;
  11549. DebugAssert(FIncrementalSearchState.Text.IsEmpty());
  11550. ADirView->UpdateStatusBar();
  11551. }
  11552. }
  11553. //---------------------------------------------------------------------------
  11554. void __fastcall TCustomScpExplorerForm::RemoteDirViewThumbnailNeeded(
  11555. TUnixDirView *, TListItem * Item, TRemoteFile * File, const TSize & Size, TBitmap *& Bitmap)
  11556. {
  11557. // though when downloading to temporary folder, encryption should not be a problem
  11558. if (Terminal->IsCapable[fcBackgroundTransfers] &&
  11559. !File->IsDirectory)
  11560. {
  11561. UnicodeString FileName = File->FullFileName;
  11562. TFileMasks::TParams MaskParams;
  11563. MaskParams.Size = File->Size;
  11564. MaskParams.Modification = File->Modification;
  11565. if ((File->Size <= static_cast<__int64>(WinConfiguration->RemoteThumbnailSizeLimit) * 1024) &&
  11566. FRemoteThumbnailMask.Matches(FileName, false, File->IsDirectory, &MaskParams))
  11567. {
  11568. Bitmap = TTerminalManager::Instance()->ThumbnailNeeded(Terminal, Item->Index, File, Size);
  11569. }
  11570. }
  11571. }
  11572. //---------------------------------------------------------------------------
  11573. TThumbnailDownloadQueueItem * TCustomScpExplorerForm::AddThumbnailDownloadQueueItem(TManagedTerminal * ATerminal)
  11574. {
  11575. DebugAssert(ATerminal == Terminal);
  11576. TCopyParamType CopyParam = TemporaryFileCopyParam();
  11577. CopyParam.TransferMode = tmBinary;
  11578. UnicodeString SourceDir = ATerminal->CurrentDirectory;
  11579. UnicodeString TempDir, RootTempDir;
  11580. TemporaryDirectoryForRemoteFiles(SourceDir, CopyParam, true, TempDir, RootTempDir);
  11581. TTerminalQueue * AQueue = TTerminalManager::Instance()->FindQueueForTerminal(ATerminal);
  11582. DebugAssert((Queue == NULL) || (AQueue == Queue)); // we might get here before queue is set
  11583. TThumbnailDownloadQueueItem * QueueItem =
  11584. new TThumbnailDownloadQueueItem(this, Terminal, SourceDir, TempDir, &CopyParam);
  11585. AddQueueItem(AQueue, QueueItem, ATerminal);
  11586. return QueueItem;
  11587. }
  11588. //---------------------------------------------------------------------------
  11589. enum { qccRemoteItemVisible, qccRemoteItemRedraw };
  11590. typedef std::pair<int, UnicodeString> TRemoteItemVisibleData;
  11591. //---------------------------------------------------------------------------
  11592. void TCustomScpExplorerForm::PostThumbnailVisibleQueueQuery(int Index, const UnicodeString & FileName)
  11593. {
  11594. // The queue might be destroyed before the WM_QUEUE_CALLBACK is processed
  11595. TRemoteItemVisibleData * Data = new TRemoteItemVisibleData();
  11596. Data->first = Index;
  11597. Data->second = FileName;
  11598. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemVisible, reinterpret_cast<WPARAM>(Data));
  11599. }
  11600. //---------------------------------------------------------------------------
  11601. void TCustomScpExplorerForm::PostThumbnailDrawRequest(int Index)
  11602. {
  11603. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemRedraw, Index);
  11604. }
  11605. //---------------------------------------------------------------------------
  11606. void TCustomScpExplorerForm::WMQueueCallback(TMessage & Message)
  11607. {
  11608. int Command = Message.WParam;
  11609. if (Command == qccRemoteItemVisible)
  11610. {
  11611. TRemoteItemVisibleData * Data = reinterpret_cast<TRemoteItemVisibleData *>(Message.LParam);
  11612. int Index = Data->first;
  11613. UnicodeString FileName = Data->second;
  11614. delete Data;
  11615. TGuard Guard(Terminal->ThumbnailsSection.get());
  11616. bool Visible = False;
  11617. if (Terminal->ThumbnailsEnabled &&
  11618. // though we should better also disable thumbnails once we switch to different view style
  11619. (RemoteDirView->DirViewStyle == dvsThumbnail))
  11620. {
  11621. // The message might be processed, while we are already loading a different directory
  11622. if ((Index >= 0) &&
  11623. (Index < RemoteDirView->Items->Count))
  11624. {
  11625. TListItem * Item = RemoteDirView->Items->Item[Index];
  11626. Visible =
  11627. (RemoteDirView->ItemFullFileName(Item) == FileName) &&
  11628. ListView_IsItemVisible(RemoteDirView->Handle, Index);
  11629. }
  11630. }
  11631. Terminal->ThumbnailVisible(Index, FileName, Visible);
  11632. }
  11633. else if (Command == qccRemoteItemRedraw)
  11634. {
  11635. int Index = Message.LParam;
  11636. if ((Index >= 0) &&
  11637. (Index < RemoteDirView->Items->Count))
  11638. {
  11639. RemoteDirView->InvalidateItem(RemoteDirView->Items->Item[Index]);
  11640. }
  11641. }
  11642. }
  11643. //---------------------------------------------------------------------------
  11644. void TCustomScpExplorerForm::InitializeRemoteThumbnailMask()
  11645. {
  11646. UnicodeString DefaultRemoteThumbnailMask = L"*.jpg;*.jpeg;*.gif;*.png;*.svg;*.bmp;*.raw;*.ico;*.heic;*.webp";
  11647. UnicodeString RemoteThumbnailMask = WinConfiguration->RemoteThumbnailMask;
  11648. if (RemoteThumbnailMask.IsEmpty() ||
  11649. StartsStr(L"+", RemoteThumbnailMask) || StartsStr(L"-", RemoteThumbnailMask) || StartsStr(L"*", RemoteThumbnailMask))
  11650. {
  11651. std::unique_ptr<TStrings> RemoteThumbnailMasks(new TStringList());
  11652. while (!DefaultRemoteThumbnailMask.IsEmpty())
  11653. {
  11654. RemoteThumbnailMasks->Add(CutToChar(DefaultRemoteThumbnailMask, L';', true));
  11655. }
  11656. RemoteThumbnailMasks.reset(ProcessFeatures(RemoteThumbnailMasks.get(), RemoteThumbnailMask));
  11657. RemoteThumbnailMask = EmptyStr;
  11658. for (int Index = 0; Index < RemoteThumbnailMasks->Count; Index++)
  11659. {
  11660. AddToList(RemoteThumbnailMask, RemoteThumbnailMasks->Strings[Index], L";");
  11661. }
  11662. }
  11663. FRemoteThumbnailMask.Masks = RemoteThumbnailMask;
  11664. }
  11665. //---------------------------------------------------------------------------
  11666. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartLoading(TObject *)
  11667. {
  11668. Terminal->StartLoadingDirectory();
  11669. }
  11670. //---------------------------------------------------------------------------
  11671. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartReading(TObject *)
  11672. {
  11673. Terminal->DisableThumbnails();
  11674. }
  11675. //---------------------------------------------------------------------------
  11676. void TCustomScpExplorerForm::ChangeDirViewStyle(TOperationSide Side, TDirViewStyle DirViewStyle)
  11677. {
  11678. TCustomDirView * ADirView = DirView(Side);
  11679. if (ADirView->DirViewStyle != DirViewStyle)
  11680. {
  11681. if (DirViewStyle == dvsThumbnail)
  11682. {
  11683. if (dynamic_cast<TUnixDirView *>(ADirView) != NULL)
  11684. {
  11685. Configuration->Usage->Inc(L"ThumbnailsRemote");
  11686. }
  11687. else
  11688. {
  11689. Configuration->Usage->Inc(L"ThumbnailsLocal");
  11690. }
  11691. }
  11692. ADirView->DirViewStyle = DirViewStyle;
  11693. UpdateControls();
  11694. }
  11695. }