CustomScpExplorer.cpp 420 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475
  1. //---------------------------------------------------------------------------
  2. #include <WinPCH.h>
  3. #pragma hdrstop
  4. #include "CustomScpExplorer.h"
  5. #include <Bookmarks.h>
  6. #include <FileSystems.h>
  7. #include <Progress.h>
  8. #include <SynchronizeProgress.h>
  9. #include <DragExt.h>
  10. #include <WinApi.h>
  11. #include "NonVisual.h"
  12. #include "Glyphs.h"
  13. #include "TerminalManager.h"
  14. #include "EditorManager.h"
  15. #include "ProgParams.h"
  16. #include "Setup.h"
  17. #include <TB2Common.hpp>
  18. #include <DirectoryMonitor.hpp>
  19. #include <mmsystem.h>
  20. //---------------------------------------------------------------------------
  21. #pragma link "CustomDirView"
  22. #pragma link "CustomUnixDirView"
  23. #pragma link "IEListView"
  24. #pragma link "NortonLikeListView"
  25. #pragma link "UnixDirView"
  26. #pragma link "CustomDriveView"
  27. #pragma link "UnixDriveView"
  28. #pragma link "CustomDriveView"
  29. #pragma link "TB2Dock"
  30. #pragma link "TBXStatusBars"
  31. #pragma link "TB2Item"
  32. #pragma link "TB2Toolbar"
  33. #pragma link "ThemePageControl"
  34. #pragma link "PathLabel"
  35. #pragma resource "*.dfm"
  36. //---------------------------------------------------------------------------
  37. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  38. #define WM_PASTE_FILES (WM_WINSCP_USER + 14)
  39. static const int SessionPanelCount = 3;
  40. //---------------------------------------------------------------------------
  41. class TMutexGuard
  42. {
  43. public:
  44. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  45. int Timeout = 5000)
  46. {
  47. FMutex = NULL;
  48. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  49. if (WaitResult == WAIT_TIMEOUT)
  50. {
  51. throw Exception(LoadStr(Message));
  52. }
  53. else
  54. {
  55. FMutex = AMutex;
  56. }
  57. }
  58. ~TMutexGuard()
  59. {
  60. if (FMutex != NULL)
  61. {
  62. ReleaseMutex(FMutex);
  63. }
  64. }
  65. private:
  66. HANDLE FMutex;
  67. };
  68. //---------------------------------------------------------------------------
  69. class TWindowLock
  70. {
  71. public:
  72. TWindowLock(TCustomScpExplorerForm * Form) :
  73. FForm(Form)
  74. {
  75. FForm->LockWindow();
  76. }
  77. ~TWindowLock()
  78. {
  79. FForm->UnlockWindow();
  80. }
  81. private:
  82. TCustomScpExplorerForm * FForm;
  83. };
  84. //---------------------------------------------------------------------------
  85. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  86. FForm(Form)
  87. {
  88. FForm->BatchStart(FBatchStorage);
  89. }
  90. //---------------------------------------------------------------------------
  91. TAutoBatch::~TAutoBatch()
  92. {
  93. FForm->BatchEnd(FBatchStorage);
  94. }
  95. //---------------------------------------------------------------------------
  96. struct TTransferOperationParam
  97. {
  98. TTransferOperationParam();
  99. UnicodeString TargetDirectory;
  100. bool Temp;
  101. bool DragDrop;
  102. int Options;
  103. TAutoSwitch Queue;
  104. };
  105. //---------------------------------------------------------------------------
  106. TTransferOperationParam::TTransferOperationParam()
  107. {
  108. Temp = false;
  109. DragDrop = false;
  110. Options = 0;
  111. Queue = asAuto;
  112. }
  113. //---------------------------------------------------------------------------
  114. class TTransferPresetNoteData : public TObject
  115. {
  116. public:
  117. UnicodeString Message;
  118. };
  119. //---------------------------------------------------------------------------
  120. class TTerminalNoteData : public TObject
  121. {
  122. public:
  123. TManagedTerminal * Terminal;
  124. };
  125. //---------------------------------------------------------------------------
  126. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  127. TForm(Owner),
  128. FFormRestored(false)
  129. {
  130. AddStartupSequence(L"F");
  131. FInvalid = false;
  132. FCurrentSide = osRemote;
  133. FEverShown = false;
  134. FDocks = new TList();
  135. InitControls();
  136. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  137. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  138. NonVisualDataModule->ScpExplorer = this;
  139. RestoreParams();
  140. ConfigurationChanged();
  141. RemoteDirView->Invalidate();
  142. FAutoOperation = false;
  143. FOnFileOperationFinished = NULL;
  144. FPrimaryOperation = foNone;
  145. FForceExecution = false;
  146. FIgnoreNextDialogChar = 0;
  147. FErrorList = NULL;
  148. FSynchronizeProgressForm = NULL;
  149. FProgressForm = NULL;
  150. FRefreshLocalDirectory = false;
  151. FRefreshRemoteDirectory = false;
  152. FDDExtMapFile = NULL;
  153. // CreateMutexW keeps failing with ERROR_NOACCESS
  154. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  155. DebugAssert(FDDExtMutex != NULL);
  156. FDDTargetControl = NULL;
  157. FDelayedDeletionTimer = NULL;
  158. FDelayedDeletionList = new TStringList();
  159. FDDFileList = NULL;
  160. FPendingTempSpaceWarn = false;
  161. FCapturedLog = NULL;
  162. FDragDropOperation = false;
  163. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  164. FAllowTransferPresetAutoSelect = true;
  165. FSessionChanging = false;
  166. FCopyParamDefault = L"";
  167. FSynchronizeController = NULL;
  168. FPendingQueueActionItem = NULL;
  169. FLockLevel = 0;
  170. FLockSuspendLevel = 0;
  171. FDisabledOnLockSuspend = false;
  172. FAlternativeDelete = false;
  173. FTrayIcon = new ::TTrayIcon(0);
  174. FTrayIcon->OnClick = TrayIconClick;
  175. FMaxQueueLength = 0;
  176. FLastContextPopupScreenPoint = TPoint(-1, -1);
  177. FTransferResumeList = NULL;
  178. FDeletedFiles = NULL;
  179. FMoveToQueue = false;
  180. StandaloneOperation = false;
  181. FOnFeedSynchronizeError = NULL;
  182. FOnSynchronizeAbort = NULL;
  183. FSynchronizeTerminal = NULL;
  184. FNeedSession = false;
  185. FDoNotIdleCurrentTerminal = 0;
  186. FIncrementalSearching = 0;
  187. FQueueFileList.reset(new TQueueFileList());
  188. FProgressSide = osCurrent;
  189. FCalculateSizeOperation = NULL;
  190. FDownloadingFromClipboard = false;
  191. FClipboardFakeMonitorsPendingReset = false;
  192. FHiContrastTheme = NULL;
  193. InitializeRemoteThumbnailMask();
  194. GlyphsModule->PixelsPerInch = CurrentPPI;
  195. FEditorManager = new TEditorManager();
  196. FEditorManager->OnFileChange = ExecutedFileChanged;
  197. FEditorManager->OnFileReload = ExecutedFileReload;
  198. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  199. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  200. FLocalEditors = new TList();
  201. FQueueStatus = NULL;
  202. FQueueStatusSection = new TCriticalSection();
  203. FQueueStatusInvalidated = false;
  204. FQueueItemInvalidated = false;
  205. FQueueStatusUpdating = false;
  206. FQueueActedItem = NULL;
  207. FQueueController = new TQueueController(QueueView3);
  208. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  209. FUserActionTimer = new TTimer(this);
  210. FUserActionTimer->Enabled = false;
  211. FUserActionTimer->Interval = 10;
  212. FUserActionTimer->OnTimer = UserActionTimer;
  213. FNotes = new TStringList();
  214. FNoteTimer = new TTimer(this);
  215. FNoteTimer->Enabled = false;
  216. FNoteTimer->OnTimer = NoteTimer;
  217. FOnNoteClick = NULL;
  218. FOle32Library = LoadLibrary(L"Ole32.dll");
  219. FDragMoveCursor = FOle32Library != NULL ?
  220. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  221. UseSystemSettings(this);
  222. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  223. static_cast<TObject*>(GetComponent(fcTransferList)));
  224. DebugAssert(TransferList != NULL);
  225. FTransferListHoverIndex = -1;
  226. TransferList->OnChange = TransferListChange;
  227. TransferList->OnDrawItem = TransferListDrawItem;
  228. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  229. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  230. UseDesktopFont(SessionsPageControl);
  231. UseDesktopFont(RemoteDirView);
  232. UseDesktopFont(RemoteDriveView);
  233. UseDesktopFont(QueueView3);
  234. UseDesktopFont(QueueFileList);
  235. UseDesktopFont(QueueLabel);
  236. UseDesktopFont(RemoteStatusBar);
  237. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  238. QueueSplitter->ShowHint = true;
  239. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  240. QueueFileListSplitter->ShowHint = true;
  241. RemotePanelSplitter->ShowHint = true;
  242. UpdateImages();
  243. FCustomCommandMenu = CreateTBXPopupMenu(this);
  244. FCustomCommandLocalFileList = NULL;
  245. FCustomCommandRemoteFileList = NULL;
  246. FSessionColors = new TPngImageList(this);
  247. FSessionColors->ColorDepth = cd32Bit;
  248. AddFixedSessionImages();
  249. SessionsPageControl->Images = FSessionColors;
  250. // Needed for Explorer (Commander calls it implicitly on its own)
  251. UpdateSessionsPageControlHeight();
  252. UpdateQueueLabel();
  253. CheckStoreTransition();
  254. CreateHiddenWindow();
  255. StartUpdates();
  256. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  257. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  258. DriveInfo->NeedData();
  259. UsesCustomColorMode(this);
  260. }
  261. //---------------------------------------------------------------------------
  262. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  263. {
  264. AppLog(L"Destroying main window");
  265. FInvalid = true;
  266. ReleaseHiContrastTheme();
  267. if (FClipboardTerminal != NULL)
  268. {
  269. ClipboardClear(); // implies ClipboardStop
  270. }
  271. // this has to be one of the very first things to do
  272. StopUpdateThread();
  273. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  274. TTerminalManager::Instance()->ScpExplorer = NULL;
  275. delete FCustomCommandLocalFileList;
  276. delete FCustomCommandRemoteFileList;
  277. delete FCustomCommandMenu;
  278. delete FTrayIcon;
  279. FTrayIcon = NULL;
  280. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  281. delete FEditorManager;
  282. ForceCloseLocalEditors();
  283. delete FLocalEditors;
  284. HideFileFindDialog();
  285. if (FDelayedDeletionTimer)
  286. {
  287. DoDelayedDeletion(NULL);
  288. SAFE_DESTROY(FDelayedDeletionTimer);
  289. }
  290. SAFE_DESTROY(FDelayedDeletionList);
  291. // sometimes we do not get DDEnd so the list is not released
  292. SAFE_DESTROY(FDDFileList);
  293. DebugAssert(FSynchronizeController == NULL);
  294. CloseHandle(FDDExtMutex);
  295. FDDExtMutex = NULL;
  296. FreeLibrary(FOle32Library);
  297. FOle32Library = NULL;
  298. FDragMoveCursor = NULL;
  299. DebugAssert(!FErrorList);
  300. if (FEverShown)
  301. {
  302. // when window is never shown (like when running command-line operation),
  303. // particularly window site is not restored correctly (BoundsRect value set
  304. // in RestoreForm gets lost during handle allocation), so we do not want
  305. // it to be stored
  306. AppLog(L"Storing main window configuration");
  307. StoreParams();
  308. }
  309. ManagedSession = NULL;
  310. Queue = NULL;
  311. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  312. NonVisualDataModule->ScpExplorer = NULL;
  313. delete FQueueScrollOnDragOver;
  314. FQueueScrollOnDragOver = NULL;
  315. delete FQueueController;
  316. FQueueController = NULL;
  317. delete FQueueStatusSection;
  318. FQueueStatusSection = NULL;
  319. delete FQueueStatus;
  320. FQueueStatus = NULL;
  321. delete FUserActionTimer;
  322. FUserActionTimer = NULL;
  323. delete FNoteTimer;
  324. delete FNotes;
  325. delete FNoteData;
  326. SAFE_DESTROY(FDocks);
  327. SessionsPageControl->Images = NULL;
  328. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  329. SAFE_DESTROY(FSessionColors);
  330. SAFE_DESTROY(FSessionsDragDropFilesEx);
  331. SAFE_DESTROY(FHistoryMenu[0][0]);
  332. SAFE_DESTROY(FHistoryMenu[0][1]);
  333. SAFE_DESTROY(FHistoryMenu[1][0]);
  334. SAFE_DESTROY(FHistoryMenu[1][1]);
  335. if (FHiddenWindow != NULL)
  336. {
  337. DestroyWindow(FHiddenWindow);
  338. FHiddenWindow = NULL;
  339. }
  340. AppLog(L"Main window destroyed");
  341. }
  342. //---------------------------------------------------------------------------
  343. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  344. {
  345. if (FHiContrastTheme != NULL)
  346. {
  347. ReleaseTBXTheme(FHiContrastTheme);
  348. FHiContrastTheme = NULL;
  349. }
  350. }
  351. //---------------------------------------------------------------------------
  352. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  353. {
  354. std::unique_ptr<TSessionData> Data;
  355. if (!Session.IsEmpty())
  356. {
  357. bool DefaultsOnly;
  358. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  359. }
  360. TTerminalManager * Manager = TTerminalManager::Instance();
  361. for (int Index = 0; Index < Manager->Count; Index++)
  362. {
  363. TTerminal * Terminal = Manager->Sessions[Index];
  364. if (Session.IsEmpty() ||
  365. Manager->IsAvailableTerminalForSite(Terminal, Data.get()))
  366. {
  367. if (Path.IsEmpty())
  368. {
  369. Terminal->ClearCaches();
  370. }
  371. else
  372. {
  373. Terminal->DirectoryModified(Path, true);
  374. }
  375. }
  376. }
  377. // We should flag a pending refresh for the background terminals or busy foreground terminals
  378. if (HasAvailableTerminal() &&
  379. CanCommandLineFromAnotherInstance() &&
  380. (Session.IsEmpty() || Manager->IsAvailableTerminalForSite(Terminal, Data.get())) &&
  381. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  382. {
  383. Terminal->ReloadDirectory();
  384. }
  385. }
  386. //---------------------------------------------------------------------------
  387. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  388. {
  389. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  390. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  391. size_t MessageSize = sizeof(TCopyDataMessage);
  392. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  393. if (Result)
  394. {
  395. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  396. Result = (Message.Version == TCopyDataMessage::Version1);
  397. if (Result)
  398. {
  399. switch (Message.Command)
  400. {
  401. case TCopyDataMessage::CommandCanCommandLine:
  402. Result = CanCommandLineFromAnotherInstance();
  403. if (Result)
  404. {
  405. AppLog(L"Can process command-line from other instance");
  406. }
  407. else
  408. {
  409. AppLog(L"Cannot process command-line from other instance");
  410. }
  411. break;
  412. case TCopyDataMessage::CommandCommandLine:
  413. {
  414. UnicodeString CommandLine(Message.Data.CommandLine);
  415. Result = CommandLineFromAnotherInstance(CommandLine);
  416. }
  417. break;
  418. case TCopyDataMessage::RefreshPanel:
  419. RefreshPanel(Message.Data.Refresh.Session, Message.Data.Refresh.Path);
  420. break;
  421. case TCopyDataMessage::MainWindowCheck:
  422. Result = true;
  423. break;
  424. default:
  425. Result = false;
  426. break;
  427. }
  428. }
  429. }
  430. Message.Result = Result ? 1 : 0;
  431. }
  432. //---------------------------------------------------------------------------
  433. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  434. {
  435. WNDCLASS WindowClass = {};
  436. WindowClass.lpfnWndProc = DefWindowProc;
  437. WindowClass.hInstance = HInstance;
  438. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  439. FHiddenWindow = NULL;
  440. if (RegisterClass(&WindowClass))
  441. {
  442. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  443. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  444. }
  445. }
  446. //---------------------------------------------------------------------------
  447. bool __fastcall TCustomScpExplorerForm::CanConsole()
  448. {
  449. return
  450. HasAvailableTerminal() &&
  451. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  452. }
  453. //---------------------------------------------------------------------------
  454. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  455. {
  456. bool Result = Visible && !NonVisualDataModule->Busy;
  457. return Result;
  458. }
  459. //---------------------------------------------------------------------------
  460. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  461. const UnicodeString & CommandLine)
  462. {
  463. TProgramParams Params(CommandLine);
  464. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  465. if (Result)
  466. {
  467. NonVisualDataModule->StartBusy();
  468. try
  469. {
  470. // this action is initiated from another process,
  471. // so it's likely that our window is not visible,
  472. // and user won't see what is going on
  473. Application->BringToFront();
  474. // reload sessions as we may be asked to open a session
  475. // just stored by another instance
  476. StoredSessions->Reload();
  477. UnicodeString SessionName = Params.Param[1];
  478. std::unique_ptr<TObjectList> DataList(new TObjectList());
  479. try
  480. {
  481. UnicodeString DownloadFile; // unused
  482. int Flags = GetCommandLineParseUrlFlags(&Params);
  483. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  484. }
  485. catch (EAbort &)
  486. {
  487. // Happens when opening session in PuTTY and in other situations,
  488. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  489. // to process the command-line on its own (or to pass it to yet another instance)
  490. }
  491. if (DataList->Count > 0)
  492. {
  493. TTerminalManager * Manager = TTerminalManager::Instance();
  494. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  495. }
  496. }
  497. __finally
  498. {
  499. NonVisualDataModule->EndBusy();
  500. }
  501. }
  502. return Result;
  503. }
  504. //---------------------------------------------------------------------------
  505. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  506. {
  507. TManagedTerminal * Result;
  508. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  509. {
  510. Result = FManagedSession;
  511. }
  512. else
  513. {
  514. Result = NULL;
  515. }
  516. return Result;
  517. }
  518. //---------------------------------------------------------------------------
  519. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  520. {
  521. if (FManagedSession != value)
  522. {
  523. TWindowLock Lock(this);
  524. SessionChanging();
  525. DoSetManagedSession(value, false);
  526. }
  527. }
  528. //---------------------------------------------------------------------------
  529. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  530. {
  531. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  532. FManagedSession = value;
  533. {
  534. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect, false);
  535. TAutoFlag SessionChangingFlag(FSessionChanging);
  536. SessionChanged(Replace);
  537. }
  538. if (Terminal != NULL)
  539. {
  540. TransferPresetAutoSelect();
  541. }
  542. // Update app and tab titles, prevented above by FSessionChanging.
  543. UpdateControls();
  544. }
  545. //---------------------------------------------------------------------------
  546. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  547. {
  548. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  549. DoSetManagedSession(value, true);
  550. }
  551. //---------------------------------------------------------------------------
  552. void __fastcall TCustomScpExplorerForm::SessionChanging()
  553. {
  554. if (ManagedSession != NULL)
  555. {
  556. UpdateSession(ManagedSession);
  557. }
  558. }
  559. //---------------------------------------------------------------------------
  560. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  561. {
  562. if (ManagedSession != NULL)
  563. {
  564. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  565. }
  566. if (!TTerminalManager::Instance()->Updating)
  567. {
  568. SessionListChanged();
  569. }
  570. if (Terminal != NULL)
  571. {
  572. TObject * State = NULL;
  573. if (WinConfiguration->PreservePanelState)
  574. {
  575. State = Terminal->RemoteExplorerState;
  576. DirView(osRemote)->AnnounceState(State);
  577. }
  578. try
  579. {
  580. if (Replaced)
  581. {
  582. RemoteDirView->ReplaceTerminal(Terminal);
  583. }
  584. else
  585. {
  586. RemoteDirView->Terminal = Terminal;
  587. }
  588. if (Terminal->Active)
  589. {
  590. Terminal->RefreshDirectory();
  591. }
  592. if (State != NULL)
  593. {
  594. DirView(osRemote)->RestoreState(State);
  595. }
  596. }
  597. __finally
  598. {
  599. DirView(osRemote)->AnnounceState(NULL);
  600. }
  601. }
  602. else
  603. {
  604. RemoteDirView->Terminal = NULL;
  605. }
  606. InitStatusBar();
  607. UpdateTransferList();
  608. // Update panels Enable state before refreshing the labels
  609. UpdateControls();
  610. }
  611. //---------------------------------------------------------------------------
  612. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  613. {
  614. if (Queue != value)
  615. {
  616. if (FQueue != NULL)
  617. {
  618. FQueue->OnListUpdate = NULL;
  619. FQueue->OnQueueItemUpdate = NULL;
  620. }
  621. FQueue = value;
  622. if (FQueue != NULL)
  623. {
  624. DebugAssert(FQueue->OnListUpdate == NULL);
  625. FQueue->OnListUpdate = QueueListUpdate;
  626. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  627. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  628. }
  629. QueueChanged();
  630. }
  631. }
  632. //---------------------------------------------------------------------------
  633. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  634. TListItem * Item)
  635. {
  636. if (FQueueActedItem == Item)
  637. {
  638. FQueueActedItem = NULL;
  639. if ((QueueView3->PopupMenu != NULL) &&
  640. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  641. {
  642. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  643. ReleaseCapture();
  644. }
  645. }
  646. if (Item->Data == FPendingQueueActionItem)
  647. {
  648. FPendingQueueActionItem = NULL;
  649. }
  650. }
  651. //---------------------------------------------------------------------------
  652. bool TCustomScpExplorerForm::IsAnythingQueued()
  653. {
  654. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  655. }
  656. //---------------------------------------------------------------------------
  657. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  658. {
  659. {
  660. TGuard Guard(FQueueStatusSection);
  661. FQueueStatusInvalidated = false;
  662. if (FQueue != NULL)
  663. {
  664. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  665. }
  666. }
  667. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  668. {
  669. FMaxQueueLength = FQueueStatus->Count;
  670. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  671. }
  672. {
  673. TAutoFlag Flag(FQueueStatusUpdating);
  674. FQueueController->UpdateQueueStatus(FQueueStatus);
  675. }
  676. UpdateQueueFileList();
  677. SetQueueProgress();
  678. UpdateQueueView();
  679. bool IsEmpty = !IsAnythingQueued();
  680. if (IsEmpty && (Terminal != NULL))
  681. {
  682. TOnceDoneOperation OnceDoneOperation =
  683. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  684. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  685. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  686. {
  687. FQueue->Enabled = false;
  688. }
  689. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  690. {
  691. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  692. }
  693. }
  694. }
  695. //---------------------------------------------------------------------------
  696. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  697. {
  698. UnicodeString Result;
  699. if (FQueueStatus != NULL)
  700. {
  701. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  702. {
  703. TFileOperationProgressType * ProgressData =
  704. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  705. if ((ProgressData != NULL) && ProgressData->InProgress)
  706. {
  707. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  708. }
  709. }
  710. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  711. {
  712. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  713. }
  714. }
  715. return Result;
  716. }
  717. //---------------------------------------------------------------------------
  718. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  719. {
  720. ComponentVisible[fcQueueView] =
  721. !IsLocalBrowserMode() &&
  722. ((WinConfiguration->QueueView.Show == qvShow) ||
  723. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  724. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  725. }
  726. //---------------------------------------------------------------------------
  727. void __fastcall TCustomScpExplorerForm::QueueChanged()
  728. {
  729. if (FQueueStatus != NULL)
  730. {
  731. // UpdateFileList implementation relies on the status being recreated when session changes
  732. delete FQueueStatus;
  733. FQueueStatus = NULL;
  734. }
  735. UpdateQueueStatus(true);
  736. }
  737. //---------------------------------------------------------------------------
  738. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  739. {
  740. if (FQueue == Queue)
  741. {
  742. FQueueStatusInvalidated = true;
  743. }
  744. }
  745. //---------------------------------------------------------------------------
  746. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  747. TQueueItem * Item)
  748. {
  749. if (FQueue == Queue)
  750. {
  751. TGuard Guard(FQueueStatusSection);
  752. // this may be running in parallel with QueueChanged
  753. if (FQueueStatus != NULL)
  754. {
  755. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  756. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  757. {
  758. FRefreshLocalDirectory = (QueueItem == NULL) ||
  759. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  760. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  761. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  762. }
  763. if (QueueItem != NULL)
  764. {
  765. QueueItem->UserData = (void*)true;
  766. FQueueItemInvalidated = true;
  767. }
  768. }
  769. }
  770. }
  771. //---------------------------------------------------------------------------
  772. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  773. {
  774. // during standalone editing, we have no way to see/control queue,
  775. // so we have to always popup prompts automatically
  776. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  777. }
  778. //---------------------------------------------------------------------------
  779. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  780. {
  781. if (FQueueStatus != NULL)
  782. {
  783. bool QueueAutoPopup = IsQueueAutoPopup();
  784. bool NeedRefresh = FQueueController->NeedRefresh();
  785. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  786. FQueueItemInvalidated = false;
  787. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  788. bool Updated = false;
  789. TQueueItemProxy * QueueItem;
  790. bool WasUserAction;
  791. for (int Index = 0; Index < Limit; Index++)
  792. {
  793. bool Update = false;
  794. QueueItem = FQueueStatus->Items[Index];
  795. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  796. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  797. (FPendingQueueActionItem == NULL))
  798. {
  799. FPendingQueueActionItem = QueueItem;
  800. FUserActionTimer->Enabled = true;
  801. }
  802. if ((bool)QueueItem->UserData)
  803. {
  804. QueueItem->UserData = (void*)false;
  805. QueueItem->Update();
  806. Updated = true;
  807. Update = true;
  808. }
  809. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  810. {
  811. Update = true;
  812. }
  813. if (Update)
  814. {
  815. FQueueController->RefreshQueueItem(QueueItem);
  816. }
  817. }
  818. if (Updated)
  819. {
  820. NonVisualDataModule->UpdateNonVisibleActions();
  821. SetQueueProgress();
  822. UpdateQueueFileList();
  823. }
  824. }
  825. }
  826. //---------------------------------------------------------------------------
  827. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  828. {
  829. if (FTaskbarList != NULL)
  830. {
  831. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  832. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  833. }
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  837. {
  838. if (Progress >= 0)
  839. {
  840. if (FTaskbarList != NULL)
  841. {
  842. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  843. }
  844. }
  845. else
  846. {
  847. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  848. }
  849. }
  850. //---------------------------------------------------------------------------
  851. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  852. {
  853. int OverallProgress;
  854. // FProgressForm is null when this is called from SetQueueProgress
  855. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  856. {
  857. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  858. }
  859. else if (!ProgressData->IsIndeterminate())
  860. {
  861. OverallProgress = ProgressData->OverallProgress();
  862. }
  863. else
  864. {
  865. OverallProgress = -1;
  866. }
  867. SetTaskbarListProgressValue(OverallProgress);
  868. }
  869. //---------------------------------------------------------------------------
  870. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  871. {
  872. TTerminalManager::Instance()->QueueStatusUpdated();
  873. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  874. {
  875. // Do not animate task bar button, when items are queued, but processing is disabled
  876. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  877. {
  878. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  879. {
  880. TFileOperationProgressType * ProgressData = NULL;
  881. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  882. {
  883. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  884. }
  885. if ((ProgressData != NULL) &&
  886. ProgressData->InProgress)
  887. {
  888. SetTaskbarListProgressValue(ProgressData);
  889. }
  890. else
  891. {
  892. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  893. }
  894. }
  895. else
  896. {
  897. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  898. }
  899. }
  900. else
  901. {
  902. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  903. }
  904. }
  905. UpdateQueueLabel();
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  909. {
  910. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  911. if (FQueueStatus != NULL)
  912. {
  913. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  914. if (ActiveAndPendingPrimaryCount > 0)
  915. {
  916. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  917. }
  918. }
  919. QueueLabel->Caption = Caption;
  920. }
  921. //---------------------------------------------------------------------------
  922. void TCustomScpExplorerForm::CheckStoreTransition()
  923. {
  924. if (WinConfiguration->StoreTransition == stInit)
  925. {
  926. if (IsUWP())
  927. {
  928. WinConfiguration->StoreTransition = stStoreFresh;
  929. AppLog(L"Fresh UWP/store installation");
  930. }
  931. else
  932. {
  933. WinConfiguration->StoreTransition = stStandard;
  934. AppLog(L"Fresh standard installation");
  935. }
  936. }
  937. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  938. {
  939. WinConfiguration->StoreTransition = stStoreMigrated;
  940. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  941. AppLog(L"Standard installation migrated to store installation");
  942. }
  943. if (WinConfiguration->StoreTransition == stStoreMigrated)
  944. {
  945. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  946. Toolbar->Parent = MessageDock;
  947. Toolbar->FullSize = true;
  948. Toolbar->Color = Application->HintColor;
  949. TTBXLabelItem * LabelItem;
  950. LabelItem = new TTBXLabelItem(Toolbar);
  951. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  952. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  953. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  954. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  955. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  956. Toolbar->Items->Add(LabelItem);
  957. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  958. LinkItem->FontSettings->Color = GetLightLinkColor(); // the background is not themed yet
  959. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  960. LinkItem->OnClick = StoreTransitionLinkClick;
  961. Toolbar->Items->Add(LinkItem);
  962. AddMenuSeparator(Toolbar->Items);
  963. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  964. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  965. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  966. CloseItem->OnClick = StoreTransitionCloseClick;
  967. Toolbar->Items->Add(CloseItem);
  968. GiveTBItemPriority(CloseItem);
  969. }
  970. }
  971. //---------------------------------------------------------------------------
  972. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  973. {
  974. ShowHelp(HELP_STORE_TRANSITION);
  975. }
  976. //---------------------------------------------------------------------------
  977. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  978. {
  979. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  980. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  981. delete Toolbar;
  982. WinConfiguration->StoreTransition = stStoreAcknowledged;
  983. UpdateControls();
  984. }
  985. //---------------------------------------------------------------------------
  986. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  987. {
  988. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  989. static_cast<TComponent*>(GetComponent(fcTransferList)));
  990. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  991. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  992. TransferList->Strings->BeginUpdate();
  993. try
  994. {
  995. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  996. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  997. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  998. if (FTransferDropDownHint.IsEmpty())
  999. {
  1000. FTransferDropDownHint = TransferDropDown->Hint;
  1001. }
  1002. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1003. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1004. TransferDropDown->Text = StripHotkey(Name);
  1005. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1006. (FTransferDropDownHint, StripHotkey(Name),
  1007. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1008. FLAGMASK(HasAvailableTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1009. // update the label, otherwise when it is updated only on the first draw
  1010. // of the list, it is drawn "bold" for some reason
  1011. FTransferListHoverIndex = TransferList->ItemIndex;
  1012. UpdateTransferLabel();
  1013. }
  1014. __finally
  1015. {
  1016. TransferList->Strings->EndUpdate();
  1017. }
  1018. }
  1019. //---------------------------------------------------------------------------
  1020. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1021. {
  1022. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1023. DebugAssert(Toolbar != NULL);
  1024. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1025. }
  1026. //---------------------------------------------------------------------------
  1027. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1028. {
  1029. TForm::UpdateActions();
  1030. if (ComponentVisible[fcCustomCommandsBand])
  1031. {
  1032. UpdateCustomCommandsToolbar();
  1033. }
  1034. }
  1035. //---------------------------------------------------------------------------
  1036. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1037. {
  1038. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1042. {
  1043. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1044. {
  1045. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1046. // Without this, the panel turns gray and unused part of header turns black
  1047. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1048. }
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1052. {
  1053. Color = GetBtnFaceColor();
  1054. DebugAssert(Configuration && RemoteDirView);
  1055. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1056. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1057. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1058. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1059. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1060. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1061. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1062. UpdateRowSelect(RemoteDirView);
  1063. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1064. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1065. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1066. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1067. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1068. UpdateSessionsPageControlHeight();
  1069. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1070. UpdateToolbarDisplayMode();
  1071. UpdateTransferList();
  1072. if (Terminal != NULL)
  1073. {
  1074. TransferPresetAutoSelect();
  1075. }
  1076. UpdateQueueView();
  1077. UpdateControls();
  1078. // this can be called even before constuctor finishes.
  1079. if (FEditorManager != NULL)
  1080. {
  1081. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1082. }
  1083. // this can be called even before constuctor finishes.
  1084. if (FLocalEditors != NULL)
  1085. {
  1086. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1087. {
  1088. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1089. }
  1090. }
  1091. if (ComponentVisible[fcCustomCommandsBand])
  1092. {
  1093. UpdateCustomCommandsToolbar();
  1094. }
  1095. // show only when keeping queue items forever,
  1096. // otherwise, it's enough to have it in the context menu
  1097. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1098. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1099. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1100. {
  1101. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1102. FFileColorsCurrent = WinConfiguration->FileColors;
  1103. FileColorsChanged();
  1104. }
  1105. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1106. (FSessionColors != NULL))
  1107. {
  1108. SessionListChanged();
  1109. }
  1110. if (GlyphsModule->LargerToolbar != WinConfiguration->LargerToolbar)
  1111. {
  1112. GlyphsModule->LargerToolbar = WinConfiguration->LargerToolbar;
  1113. if (FSessionColors != NULL)
  1114. {
  1115. RegenerateSessionColorsImageList();
  1116. UpdateSessionsPageControlHeight();
  1117. }
  1118. }
  1119. }
  1120. //---------------------------------------------------------------------------
  1121. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1122. {
  1123. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1124. DirView->Invalidate();
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1128. {
  1129. DoFileColorsChanged(RemoteDirView);
  1130. }
  1131. //---------------------------------------------------------------------------
  1132. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1133. const UnicodeString DebugUsedArg(FileName), TEditedFileData * /*Data*/, TObject * Token,
  1134. void * /*Arg*/)
  1135. {
  1136. if (Token != NULL)
  1137. {
  1138. TForm * Editor = dynamic_cast<TForm*>(Token);
  1139. DebugAssert(Editor != NULL);
  1140. ReconfigureEditorForm(Editor);
  1141. }
  1142. }
  1143. //---------------------------------------------------------------------------
  1144. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1145. {
  1146. WinConfiguration->DDTransferConfirmation = asOn;
  1147. }
  1148. //---------------------------------------------------------------------------
  1149. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1150. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1151. {
  1152. // noop
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1156. {
  1157. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1161. {
  1162. if (DoNotShowAgain)
  1163. {
  1164. if (DragDrop)
  1165. {
  1166. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1167. {
  1168. PopupTrayBalloon(
  1169. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1170. }
  1171. WinConfiguration->DDTransferConfirmation = asOff;
  1172. }
  1173. else
  1174. {
  1175. WinConfiguration->ConfirmTransferring = false;
  1176. }
  1177. }
  1178. else
  1179. {
  1180. // User explicitly unchecked "do not show again",
  1181. // so show him the dialog the next time
  1182. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1183. {
  1184. WinConfiguration->DDTransferConfirmation = asOn;
  1185. }
  1186. }
  1187. }
  1188. //---------------------------------------------------------------------------
  1189. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1190. TTransferDirection Direction, TTransferType Type, bool Temp,
  1191. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1192. bool Confirm, bool DragDrop, int Options)
  1193. {
  1194. bool Result = true;
  1195. DebugAssert(HasAvailableTerminal());
  1196. // these parameters are known in advance
  1197. int Params =
  1198. FLAGMASK(Type == ttMove, cpDelete);
  1199. bool ToTemp = (Temp && (Direction == tdToLocal));
  1200. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1201. {
  1202. bool DisableNewerOnly =
  1203. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1204. ToTemp;
  1205. Options |=
  1206. FLAGMASK(ToTemp, coTemp) |
  1207. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1208. coDoNotShowAgain;
  1209. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1210. int CopyParamAttrs = (Direction == tdToRemote ?
  1211. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1212. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1213. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1214. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1215. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1216. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1217. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1218. if (Result)
  1219. {
  1220. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1221. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1222. }
  1223. }
  1224. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1225. {
  1226. Configuration->Usage->Inc(L"TransfersOnBackground");
  1227. // these parameter are known only after transfer dialog
  1228. Params |=
  1229. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1230. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1231. Result = false;
  1232. ClearTransferSourceSelection(Direction);
  1233. }
  1234. return Result;
  1235. }
  1236. //---------------------------------------------------------------------------
  1237. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1238. {
  1239. if (FOnFileOperationFinished != NULL)
  1240. {
  1241. FOnFileOperationFinished(Side, UnicodeString(), true, true);
  1242. }
  1243. else
  1244. {
  1245. if (HasDirView[Side])
  1246. {
  1247. DirView(Side)->SelectAll(smNone);
  1248. }
  1249. }
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1253. {
  1254. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1255. ClearOperationSelection(Side);
  1256. }
  1257. //---------------------------------------------------------------------------
  1258. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1259. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1260. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1261. int Params)
  1262. {
  1263. DebugAssert(Queue != NULL);
  1264. TQueueItem * QueueItem;
  1265. if (Direction == tdToRemote)
  1266. {
  1267. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1268. QueueItem =
  1269. new TUploadQueueItem(
  1270. Terminal, FileList, TargetDirectory, &CopyParam, Params, CopyParam.QueueParallel);
  1271. }
  1272. else
  1273. {
  1274. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1275. QueueItem =
  1276. new TDownloadQueueItem(
  1277. Terminal, FileList, TargetDirectory, &CopyParam, Params, CopyParam.QueueParallel);
  1278. }
  1279. AddQueueItem(Queue, QueueItem, Terminal);
  1280. }
  1281. //---------------------------------------------------------------------------
  1282. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1283. {
  1284. if (Queue->IsEmpty)
  1285. {
  1286. Terminal->QueueOperationStart = Now();
  1287. }
  1288. Queue->AddItem(QueueItem);
  1289. }
  1290. //---------------------------------------------------------------------------
  1291. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1292. {
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. void __fastcall TCustomScpExplorerForm::InitControls()
  1296. {
  1297. DebugAssert(FDocks != NULL);
  1298. for (int Index = 0; Index < ComponentCount; Index++)
  1299. {
  1300. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1301. if ((Dock != NULL) && (Dock->Tag == 0))
  1302. {
  1303. FDocks->Add(Dock);
  1304. }
  1305. }
  1306. CollectItemsWithTextDisplayMode(this);
  1307. }
  1308. //---------------------------------------------------------------------------
  1309. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1310. {
  1311. ConfigurationChanged();
  1312. QueuePanel->Height =
  1313. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1314. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1315. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1316. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1317. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1318. QueueFileList->Height =
  1319. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1320. if (QueueFileList->Visible)
  1321. {
  1322. AdjustQueueLayout();
  1323. }
  1324. UpdateCustomCommandsToolbar();
  1325. }
  1326. //---------------------------------------------------------------------------
  1327. void __fastcall TCustomScpExplorerForm::StoreParams()
  1328. {
  1329. int APixelsPerInch = GetControlPixelsPerInch(this);
  1330. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1331. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1332. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1333. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1334. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1335. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1336. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1337. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1338. }
  1339. //---------------------------------------------------------------------------
  1340. void __fastcall TCustomScpExplorerForm::Loaded()
  1341. {
  1342. // Loaded is called in more deterministic moment than previously used CreateParams
  1343. if (!FFormRestored)
  1344. {
  1345. FFormRestored = true;
  1346. RestoreFormParams();
  1347. }
  1348. TForm::Loaded();
  1349. }
  1350. //---------------------------------------------------------------------------
  1351. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1352. {
  1353. DebugAssert(FDocks != NULL);
  1354. for (int Index = 0; Index < FDocks->Count; Index++)
  1355. {
  1356. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1357. }
  1358. }
  1359. //---------------------------------------------------------------------------
  1360. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1361. {
  1362. SetDockAllowDrag(true);
  1363. while (!ButtonsStr.IsEmpty())
  1364. {
  1365. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1366. UnicodeString Name = CutToChar(S, L'=', true);
  1367. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1368. {
  1369. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1370. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1371. {
  1372. while (!S.IsEmpty())
  1373. {
  1374. UnicodeString S2 = CutToChar(S, L',', true);
  1375. UnicodeString Name = CutToChar(S2, L':', true);
  1376. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1377. {
  1378. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1379. if (SameText(GetToolbarItemName(Item), Name))
  1380. {
  1381. // forward compatibility
  1382. UnicodeString S3 = CutToChar(S2, L':', true);
  1383. bool Visible = StrToIntDef(S3, 0);
  1384. Item->Visible = Visible;
  1385. }
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1392. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1396. {
  1397. UnicodeString Result;
  1398. SetDockAllowDrag(true);
  1399. Result = ::GetToolbarsLayoutStr(this);
  1400. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1401. return Result;
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1405. {
  1406. UnicodeString Result;
  1407. if (Item->Action != NULL)
  1408. {
  1409. Result = Item->Action->Name;
  1410. Result = RemoveSuffix(Result, L"Action", true);
  1411. }
  1412. else
  1413. {
  1414. Result = Item->Name;
  1415. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1416. Result = RemoveSuffix(Result, L"Item", true);
  1417. }
  1418. return Result;
  1419. }
  1420. //---------------------------------------------------------------------------
  1421. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1422. {
  1423. UnicodeString Result;
  1424. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1425. {
  1426. UnicodeString ToolbarStr;
  1427. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1428. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1429. {
  1430. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1431. {
  1432. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1433. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1434. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1435. // and save the changes here only.
  1436. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1437. {
  1438. UnicodeString Name = GetToolbarItemName(Item);
  1439. DebugAssert(Name.Pos(L"TBX") == 0);
  1440. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1441. }
  1442. }
  1443. }
  1444. if (!ToolbarStr.IsEmpty())
  1445. {
  1446. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1447. }
  1448. }
  1449. return Result;
  1450. }
  1451. //---------------------------------------------------------------------------
  1452. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1453. {
  1454. DebugAssert(FProgressForm == NULL);
  1455. bool AllowSkip = HasAvailableTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1456. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1457. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1458. FProgressForm->DeleteLocalToRecycleBin =
  1459. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1460. FProgressForm->DeleteRemoteToRecycleBin =
  1461. HasAvailableTerminal() &&
  1462. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1463. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1464. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1465. LockWindow();
  1466. // Actually, do not know what hides the progress once the operation finishes
  1467. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1468. SetTaskbarListProgressState(TBPF_NORMAL);
  1469. }
  1470. //---------------------------------------------------------------------------
  1471. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1472. {
  1473. UnlockWindow();
  1474. SAFE_DESTROY(FProgressForm);
  1475. SetQueueProgress();
  1476. }
  1477. //---------------------------------------------------------------------------
  1478. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1479. TFileOperationProgressType & ProgressData)
  1480. {
  1481. // Download to temporary local directory
  1482. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1483. {
  1484. bool Continue = true;
  1485. FPendingTempSpaceWarn = false;
  1486. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1487. if (!Continue)
  1488. {
  1489. Abort();
  1490. }
  1491. }
  1492. // operation is being executed and we still didn't show up progress form
  1493. if (ProgressData.InProgress && !FProgressForm)
  1494. {
  1495. CreateProgressForm(NULL);
  1496. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1497. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1498. }
  1499. // operation is finished (or terminated), so we hide progress form
  1500. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1501. {
  1502. DestroyProgressForm();
  1503. if (ProgressData.Operation == foCalculateSize)
  1504. {
  1505. // When calculating size before transfer, the abort caused by
  1506. // cancel flag set due to "MoveToQueue" below,
  1507. // is not propagated back to us in ExecuteFileOperation,
  1508. // as it is silently swallowed.
  1509. // So we explicitly (re)throw it here.
  1510. if (FMoveToQueue)
  1511. {
  1512. Abort();
  1513. }
  1514. }
  1515. else
  1516. {
  1517. if ((ProgressData.Cancel == csContinue) &&
  1518. !FAutoOperation)
  1519. {
  1520. OperationComplete(ProgressData.StartTime);
  1521. }
  1522. }
  1523. }
  1524. if (FProgressForm &&
  1525. // Can happen only during synchronization, when ending one of the operations
  1526. ProgressData.InProgress)
  1527. {
  1528. FProgressForm->SetProgressData(ProgressData);
  1529. DebugAssert(ProgressData.InProgress);
  1530. SetTaskbarListProgressValue(&ProgressData);
  1531. if (FProgressForm->Cancel > csContinue)
  1532. {
  1533. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1534. if (FProgressForm->Cancel == csCancelFile)
  1535. {
  1536. FProgressForm->ClearCancel();
  1537. }
  1538. // cancel cancels even the move
  1539. FMoveToQueue = false;
  1540. }
  1541. else if (FProgressForm->MoveToQueue)
  1542. {
  1543. FMoveToQueue = true;
  1544. ProgressData.SetCancelAtLeast(csCancel);
  1545. }
  1546. if ((FTransferResumeList != NULL) &&
  1547. ProgressData.InProgress &&
  1548. ProgressData.IsTransfer() &&
  1549. !ProgressData.FullFileName.IsEmpty())
  1550. {
  1551. if ((FTransferResumeList->Count == 0) ||
  1552. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1553. {
  1554. // note that we do not recognize directories from files here
  1555. FTransferResumeList->Add(ProgressData.FullFileName);
  1556. }
  1557. }
  1558. }
  1559. }
  1560. //---------------------------------------------------------------------------
  1561. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1562. const TDateTime & StartTime)
  1563. {
  1564. if (GUIConfiguration->BeepOnFinish &&
  1565. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1566. {
  1567. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1568. DWORD Sound;
  1569. if (!ExtractFileExt(BeepSound).IsEmpty())
  1570. {
  1571. Sound = SND_FILENAME;
  1572. }
  1573. else
  1574. {
  1575. Sound = SND_ALIAS;
  1576. }
  1577. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1578. }
  1579. }
  1580. //---------------------------------------------------------------------------
  1581. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1582. TFileOperationProgressType & ProgressData)
  1583. {
  1584. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1585. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1586. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1587. FileOperationProgress(ProgressData);
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1591. {
  1592. UnicodeString Result;
  1593. if (FProgressForm != NULL)
  1594. {
  1595. Result = FProgressForm->ProgressStr();
  1596. }
  1597. return Result;
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1601. bool DragDrop)
  1602. {
  1603. return (!DragDrop && (DropSourceControl == NULL)) ||
  1604. (DropSourceControl == DirView(osOther));
  1605. }
  1606. //---------------------------------------------------------------------------
  1607. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1608. {
  1609. TCustomDirView * ADirView = DirView(Side);
  1610. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1611. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1612. // this can happen when local drive is unplugged in the middle of the operation
  1613. if (Item != NULL)
  1614. {
  1615. if (Unselect)
  1616. {
  1617. Item->Selected = false;
  1618. }
  1619. ADirView->MakeProgressVisible(Item);
  1620. }
  1621. return Item;
  1622. }
  1623. //---------------------------------------------------------------------------
  1624. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1625. TFileOperation Operation, TOperationSide Side,
  1626. bool /*Temp*/, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1627. TOnceDoneOperation & OnceDoneOperation)
  1628. {
  1629. if (!FAutoOperation)
  1630. {
  1631. // no selection on "/upload", form serves only as event handler
  1632. // (it is not displayed)
  1633. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1634. ((Operation == FPrimaryOperation) ||
  1635. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1636. {
  1637. TOperationSide DViewSide;
  1638. if ((FProgressSide != osCurrent) &&
  1639. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1640. {
  1641. // assume the operation is over the focused panel
  1642. DViewSide = FProgressSide;
  1643. }
  1644. else
  1645. {
  1646. DViewSide = Side;
  1647. }
  1648. if (FOnFileOperationFinished != NULL)
  1649. {
  1650. FOnFileOperationFinished(DViewSide, FileName, Success, NotCancelled);
  1651. }
  1652. else
  1653. {
  1654. VisualiseOperationFinished(DViewSide, FileName, Success && NotCancelled);
  1655. }
  1656. }
  1657. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1658. {
  1659. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1660. {
  1661. if (Side == osLocal)
  1662. {
  1663. Configuration->Usage->Inc(L"UploadedFiles");
  1664. }
  1665. else
  1666. {
  1667. Configuration->Usage->Inc(L"DownloadedFiles");
  1668. }
  1669. }
  1670. }
  1671. }
  1672. if (Success && (FSynchronizeController != NULL))
  1673. {
  1674. DebugAssert(!IsSideLocalBrowser(osRemote));
  1675. if (Operation == foCopy)
  1676. {
  1677. DebugAssert(Side == osLocal);
  1678. FSynchronizeController->LogOperation(soUpload, FileName);
  1679. }
  1680. else if (Operation == foDelete)
  1681. {
  1682. DebugAssert(Side == osRemote);
  1683. FSynchronizeController->LogOperation(soDelete, FileName);
  1684. }
  1685. }
  1686. if (FProgressForm)
  1687. {
  1688. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1689. }
  1690. }
  1691. //---------------------------------------------------------------------------
  1692. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1693. TFileOperation Operation, TOperationSide Side,
  1694. bool Temp, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1695. TOnceDoneOperation & OnceDoneOperation)
  1696. {
  1697. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1698. DoOperationFinished(Operation, Side, Temp, FileName, Success, NotCancelled, OnceDoneOperation);
  1699. }
  1700. //---------------------------------------------------------------------------
  1701. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1702. {
  1703. return false;
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1707. {
  1708. return false;
  1709. }
  1710. //---------------------------------------------------------------------------
  1711. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1712. {
  1713. return false;
  1714. }
  1715. //---------------------------------------------------------------------------
  1716. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1717. {
  1718. return NULL;
  1719. }
  1720. //---------------------------------------------------------------------------
  1721. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1722. {
  1723. DebugAssert(GetSide(Side) == osRemote);
  1724. DebugUsedParam(Side);
  1725. return RemoteDirView;
  1726. }
  1727. //---------------------------------------------------------------------------
  1728. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1729. {
  1730. DebugAssert(GetSide(Side) == osRemote);
  1731. DebugUsedParam(Side);
  1732. return RemoteDriveView;
  1733. }
  1734. //---------------------------------------------------------------------------
  1735. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1736. {
  1737. DebugAssert(GetSide(Side) == osRemote);
  1738. DebugUsedParam(Side);
  1739. return HasAvailableTerminal();
  1740. }
  1741. //---------------------------------------------------------------------------
  1742. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1743. TOperationSide Side, int FilesOnly)
  1744. {
  1745. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1746. }
  1747. //---------------------------------------------------------------------------
  1748. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1749. TOperationSide Side, int FilesOnly)
  1750. {
  1751. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1752. }
  1753. //---------------------------------------------------------------------------
  1754. struct THistoryItemData
  1755. {
  1756. short int Side;
  1757. short int Index;
  1758. };
  1759. //---------------------------------------------------------------------------
  1760. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1761. {
  1762. DirView(Side)->HistoryGo(Index);
  1763. }
  1764. //---------------------------------------------------------------------------
  1765. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1766. {
  1767. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1768. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1769. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1770. }
  1771. //---------------------------------------------------------------------------
  1772. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1773. bool Back)
  1774. {
  1775. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1776. {
  1777. TCustomDirView * DView = DirView(Side);
  1778. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1779. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1780. if (ICount > 10)
  1781. {
  1782. ICount = 10;
  1783. }
  1784. Menu->Items->Clear();
  1785. THistoryItemData Data;
  1786. Data.Side = Side;
  1787. for (short int i = 1; i <= ICount; i++)
  1788. {
  1789. TTBCustomItem * Item = new TTBXItem(Menu);
  1790. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1791. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1792. Item->Hint = DView->HistoryPath[Data.Index];
  1793. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1794. Item->Tag = *reinterpret_cast<int*>(&Data);
  1795. Item->OnClick = HistoryItemClick;
  1796. Menu->Items->Add(Item);
  1797. }
  1798. }
  1799. }
  1800. //---------------------------------------------------------------------------
  1801. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1802. TOperationSide Side, bool Back)
  1803. {
  1804. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1805. {
  1806. // workaround
  1807. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1808. // operator new allocates memory in Pascal code, but calls inline
  1809. // constructor in C++, leading in problems, the function does
  1810. // both in Pascal code
  1811. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1812. UpdateHistoryMenu(Side, Back);
  1813. }
  1814. return FHistoryMenu[Side == osLocal][Back];
  1815. }
  1816. //---------------------------------------------------------------------------
  1817. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1818. TCustomDirView *Sender)
  1819. {
  1820. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1821. UpdateHistoryMenu(Side, true);
  1822. UpdateHistoryMenu(Side, false);
  1823. }
  1824. //---------------------------------------------------------------------------
  1825. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1826. {
  1827. // remote custom commands can be executed only if the server supports shell commands
  1828. // or have secondary shell
  1829. return HasAvailableTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1830. }
  1831. //---------------------------------------------------------------------------
  1832. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1833. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1834. {
  1835. // -1 = hidden, 0 = disabled, 1 = enabled
  1836. int Result;
  1837. TFileCustomCommand RemoteCustomCommand;
  1838. TLocalCustomCommand LocalCustomCommand;
  1839. TFileCustomCommand * NonInteractiveCustomCommand =
  1840. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1841. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1842. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1843. if (FLAGCLEAR(Command.Params, ccLocal))
  1844. {
  1845. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1846. // custom command that does not operate with files can be executed anytime ...
  1847. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1848. {
  1849. // ... but do not show such command in remote file menu
  1850. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1851. {
  1852. Result = AllowedState;
  1853. }
  1854. else
  1855. {
  1856. Result = -1;
  1857. }
  1858. }
  1859. else
  1860. {
  1861. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1862. {
  1863. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1864. }
  1865. else
  1866. {
  1867. Result = -1;
  1868. }
  1869. }
  1870. }
  1871. else
  1872. {
  1873. // custom command that does not operate with files can be executed anytime
  1874. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1875. {
  1876. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1877. }
  1878. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1879. {
  1880. if ((ListType == ccltAll) || (ListType == ccltFile))
  1881. {
  1882. // special case is "diff"-style command that can be executed over any side,
  1883. // if we have both sides
  1884. Result =
  1885. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1886. // directly (instead of EnableSelectedOperation) to pass
  1887. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1888. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1889. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1890. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1891. }
  1892. else if (ListType == ccltBoth)
  1893. {
  1894. DebugAssert(!IsLocalBrowserMode());
  1895. Result = 1;
  1896. }
  1897. else
  1898. {
  1899. Result = -1;
  1900. }
  1901. }
  1902. else
  1903. {
  1904. if ((ListType == ccltAll) ||
  1905. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1906. {
  1907. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1908. }
  1909. else
  1910. {
  1911. Result = -1;
  1912. }
  1913. }
  1914. if ((Result > 0) &&
  1915. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1916. !HasAvailableTerminal())
  1917. {
  1918. Result = 0;
  1919. }
  1920. }
  1921. return Result;
  1922. }
  1923. //---------------------------------------------------------------------------
  1924. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1925. TStrings * FileList, const TCustomCommandType & ACommand,
  1926. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1927. {
  1928. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1929. {
  1930. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1931. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1932. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1933. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1934. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1935. bool Capture =
  1936. FLAGSET(ACommand.Params, ccShowResults) ||
  1937. FLAGSET(ACommand.Params, ccCopyResults) ||
  1938. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1939. TCaptureOutputEvent OutputEvent = NULL;
  1940. DebugAssert(FCapturedLog == NULL);
  1941. TObjectReleaser<TStrings> CapturedLogReleaser(FCapturedLog);
  1942. if (Capture)
  1943. {
  1944. CapturedLogReleaser.Set(new TStringList());
  1945. OutputEvent = TerminalCaptureLog;
  1946. }
  1947. if (!RemoteCustomCommand.IsFileCommand(Command))
  1948. {
  1949. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1950. OutputEvent);
  1951. }
  1952. else
  1953. {
  1954. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1955. }
  1956. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1957. {
  1958. if (FLAGSET(ACommand.Params, ccCopyResults))
  1959. {
  1960. CopyToClipboard(FCapturedLog);
  1961. }
  1962. if (FLAGSET(ACommand.Params, ccShowResults))
  1963. {
  1964. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1965. }
  1966. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1967. {
  1968. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. //---------------------------------------------------------------------------
  1974. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1975. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1976. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1977. {
  1978. DebugAssert(!IsLocalBrowserMode());
  1979. TStrings * LocalFileList = NULL;
  1980. TStrings * RemoteFileList = NULL;
  1981. TStrings * RemoteFileListFull = NULL;
  1982. try
  1983. {
  1984. if (LocalFileCommand)
  1985. {
  1986. if (ALocalFileList == NULL)
  1987. {
  1988. DebugAssert(HasDirView[osLocal]);
  1989. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1990. // directly (instead of EnableSelectedOperation) to pass
  1991. // false to FocusedFileOnlyWhenFocused
  1992. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1993. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1994. }
  1995. else
  1996. {
  1997. LocalFileList = ALocalFileList;
  1998. }
  1999. if (FileListCommand)
  2000. {
  2001. if (LocalFileList->Count != 1)
  2002. {
  2003. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2004. }
  2005. }
  2006. else
  2007. {
  2008. if ((LocalFileList->Count != 1) &&
  2009. (FileList->Count != 1) &&
  2010. (LocalFileList->Count != FileList->Count))
  2011. {
  2012. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2013. }
  2014. }
  2015. }
  2016. UnicodeString RootTempDir;
  2017. UnicodeString TempDir;
  2018. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2019. if (!RemoteFiles)
  2020. {
  2021. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, true, true);
  2022. DebugAssert(RootTempDir == TempDir);
  2023. }
  2024. try
  2025. {
  2026. TDateTimes RemoteFileTimes;
  2027. if (RemoteFiles)
  2028. {
  2029. RemoteFileList = FileList;
  2030. }
  2031. else
  2032. {
  2033. RemoteFileList = new TStringList();
  2034. TMakeLocalFileListParams MakeFileListParam;
  2035. MakeFileListParam.FileList = RemoteFileList;
  2036. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2037. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2038. MakeFileListParam.Recursive =
  2039. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2040. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2041. if (!MakeFileListParam.Recursive)
  2042. {
  2043. RemoteFileTimes.clear();
  2044. RemoteFileListFull = new TStringList();
  2045. MakeFileListParam.FileList = RemoteFileListFull;
  2046. MakeFileListParam.Recursive = true;
  2047. MakeFileListParam.IncludeDirs = false;
  2048. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2049. }
  2050. else
  2051. {
  2052. RemoteFileListFull = RemoteFileList;
  2053. }
  2054. }
  2055. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2056. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2057. if (!NonBlocking)
  2058. {
  2059. int Count;
  2060. if (FileListCommand)
  2061. {
  2062. Count = 1;
  2063. }
  2064. else if (LocalFileCommand)
  2065. {
  2066. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2067. }
  2068. else
  2069. {
  2070. Count = RemoteFileList->Count;
  2071. }
  2072. Progress.Start(foCustomCommand, osRemote, Count);
  2073. DebugAssert(FProgressForm != NULL);
  2074. FProgressForm->ReadOnly = true;
  2075. }
  2076. try
  2077. {
  2078. if (FileListCommand)
  2079. {
  2080. UnicodeString LocalFile;
  2081. // MakeFileList does not delimit filenames
  2082. UnicodeString FileList = MakeFileList(RemoteFileList);
  2083. if (LocalFileCommand)
  2084. {
  2085. DebugAssert(LocalFileList->Count == 1);
  2086. LocalFile = LocalFileList->Strings[0];
  2087. }
  2088. TLocalCustomCommand CustomCommand(Data,
  2089. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2090. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2091. if (NonBlocking)
  2092. {
  2093. DebugAssert(!POutput);
  2094. ExecuteShellChecked(ShellCommand);
  2095. }
  2096. else
  2097. {
  2098. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2099. }
  2100. }
  2101. else if (LocalFileCommand)
  2102. {
  2103. if (LocalFileList->Count == 1)
  2104. {
  2105. UnicodeString LocalFile = LocalFileList->Strings[0];
  2106. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2107. {
  2108. UnicodeString FileName = RemoteFileList->Strings[Index];
  2109. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2110. Progress.SetFile(FileNameForProgress);
  2111. TLocalCustomCommand CustomCommand(Data,
  2112. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2113. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2114. TOnceDoneOperation OnceDoneOperation;
  2115. // Do not unselect anything, as it won't work with two panels anyway
  2116. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2117. }
  2118. }
  2119. else if (RemoteFileList->Count == 1)
  2120. {
  2121. UnicodeString FileName = RemoteFileList->Strings[0];
  2122. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2123. {
  2124. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2125. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2126. Progress.SetFile(LocalFileNameOnly);
  2127. TLocalCustomCommand CustomCommand(
  2128. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2129. FileName, LocalFileName, L"");
  2130. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2131. TOnceDoneOperation OnceDoneOperation;
  2132. // Do not unselect anything, as it won't work with two panels anyway
  2133. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2134. }
  2135. }
  2136. else
  2137. {
  2138. if (LocalFileList->Count != RemoteFileList->Count)
  2139. {
  2140. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2141. }
  2142. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2143. {
  2144. UnicodeString FileName = RemoteFileList->Strings[Index];
  2145. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2146. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2147. Progress.SetFile(LocalFileNameOnly); // sic
  2148. TLocalCustomCommand CustomCommand(
  2149. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2150. FileName, LocalFileName, L"");
  2151. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2152. TOnceDoneOperation OnceDoneOperation;
  2153. // Do not unselect anything, as it won't work with two panels anyway
  2154. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2155. }
  2156. }
  2157. }
  2158. else
  2159. {
  2160. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2161. {
  2162. UnicodeString FileName = RemoteFileList->Strings[Index];
  2163. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2164. Progress.SetFile(FileNameForProgress);
  2165. TLocalCustomCommand CustomCommand(Data,
  2166. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2167. FileName, L"", L"");
  2168. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2169. TOnceDoneOperation OnceDoneOperation;
  2170. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2171. }
  2172. }
  2173. }
  2174. __finally
  2175. {
  2176. if (!NonBlocking)
  2177. {
  2178. Progress.Stop();
  2179. }
  2180. }
  2181. DebugAssert(!FAutoOperation);
  2182. if (!RemoteFiles)
  2183. {
  2184. TempDir = IncludeTrailingBackslash(TempDir);
  2185. typedef std::map<UnicodeString, UnicodeString> TTempNameMap;
  2186. TTempNameMap TempNameMap;
  2187. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2188. {
  2189. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2190. TSearchRecSmart SearchRec;
  2191. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2192. FileSearchRec(FileName, SearchRec) &&
  2193. // Skip directories, process only nested files.
  2194. !SearchRec.IsDirectory() &&
  2195. (SearchRec.GetLastWriteTime() != RemoteFileTimes[Index]))
  2196. {
  2197. if (TempNameMap.empty()) // optimization (create map only once it is really needed)
  2198. {
  2199. TCopyParamType CopyParam = TemporaryFileCopyParam();
  2200. for (int Index2 = 0; Index2 < FileList->Count; Index2++)
  2201. {
  2202. UnicodeString RemotePath = FileList->Strings[Index2];
  2203. UnicodeString TempName = GetTempLocalName(RemotePath, CopyParam);
  2204. TempNameMap.insert(std::make_pair(TempName.UpperCase(), RemotePath));
  2205. }
  2206. }
  2207. UnicodeString RelPath = MidStr(FileName, TempDir.Length() + 1);
  2208. UnicodeString TempName = CutToChar(RelPath, L'\\', false).UpperCase();
  2209. TTempNameMap::const_iterator TempNameI = TempNameMap.find(TempName);
  2210. if (DebugAlwaysTrue(TempNameI != TempNameMap.end()))
  2211. {
  2212. TCopyParamType CopyParam = TemporaryFileCopyParam();
  2213. CopyParam.FileMask = L"";
  2214. FAutoOperation = true;
  2215. FMoveToQueue = false;
  2216. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2217. TemporaryFilesList->Add(FileName);
  2218. UnicodeString RemoteDir = UnixExtractFileDir(UnixCombinePathsSmart(TempNameI->second, ToUnixPath(RelPath)));
  2219. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2220. }
  2221. }
  2222. }
  2223. }
  2224. }
  2225. __finally
  2226. {
  2227. FAutoOperation = false;
  2228. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2229. {
  2230. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2231. }
  2232. }
  2233. }
  2234. __finally
  2235. {
  2236. if (RemoteFileList != FileList)
  2237. {
  2238. delete RemoteFileList;
  2239. }
  2240. if (LocalFileList != ALocalFileList)
  2241. {
  2242. delete LocalFileList;
  2243. }
  2244. if (RemoteFileListFull != RemoteFileList)
  2245. {
  2246. delete RemoteFileListFull;
  2247. }
  2248. }
  2249. }
  2250. //---------------------------------------------------------------------------
  2251. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2252. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2253. bool FileListCommand, UnicodeString * POutput)
  2254. {
  2255. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2256. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2257. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2258. {
  2259. UnicodeString FileName = SelectedFileList->Strings[Index];
  2260. if (DirectoryExists(FileName))
  2261. {
  2262. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2263. {
  2264. LocalFileList->Add(FileName);
  2265. }
  2266. if (FLAGSET(ACommand.Params, ccRecursive))
  2267. {
  2268. TMakeLocalFileListParams MakeFileListParam;
  2269. MakeFileListParam.FileList = LocalFileList.get();
  2270. MakeFileListParam.FileTimes = NULL;
  2271. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2272. MakeFileListParam.Recursive = true;
  2273. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2274. }
  2275. }
  2276. else
  2277. {
  2278. LocalFileList->Add(FileName);
  2279. }
  2280. }
  2281. UnicodeString RemotePath;
  2282. if (Terminal != NULL)
  2283. {
  2284. RemotePath = Terminal->CurrentDirectory;
  2285. }
  2286. if (FileListCommand)
  2287. {
  2288. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2289. TLocalCustomCommand CustomCommand(
  2290. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2291. L"", L"", FileList);
  2292. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2293. }
  2294. else
  2295. {
  2296. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2297. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2298. DebugAssert(FProgressForm != NULL);
  2299. FProgressForm->ReadOnly = true;
  2300. try
  2301. {
  2302. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2303. {
  2304. UnicodeString FileName = LocalFileList->Strings[Index];
  2305. Progress.SetFile(FileName);
  2306. TLocalCustomCommand CustomCommand(
  2307. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2308. FileName, L"", L"");
  2309. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2310. TOnceDoneOperation OnceDoneOperation;
  2311. Progress.Finish(FileName, true, OnceDoneOperation);
  2312. }
  2313. }
  2314. __finally
  2315. {
  2316. Progress.Stop();
  2317. }
  2318. }
  2319. }
  2320. //---------------------------------------------------------------------------
  2321. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2322. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2323. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2324. {
  2325. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2326. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2327. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2328. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2329. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2330. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2331. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2332. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2333. std::unique_ptr<UnicodeString> POutput;
  2334. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2335. FLAGSET(ACommand.Params, ccCopyResults))
  2336. {
  2337. POutput.reset(new UnicodeString());
  2338. }
  2339. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  2340. if (!LocalCustomCommand.IsFileCommand(Command))
  2341. {
  2342. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2343. }
  2344. // remote files?
  2345. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2346. {
  2347. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2348. }
  2349. // local files
  2350. else
  2351. {
  2352. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2353. }
  2354. if (POutput.get() != NULL)
  2355. {
  2356. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2357. int P = POutput->Pos(sLineBreak);
  2358. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2359. {
  2360. POutput->SetLength(P - 1);
  2361. }
  2362. // Copy even empty output to clipboard
  2363. if (FLAGSET(ACommand.Params, ccCopyResults))
  2364. {
  2365. CopyToClipboard(*POutput);
  2366. }
  2367. // But do not show an empty message box.
  2368. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2369. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2370. !POutput->IsEmpty())
  2371. {
  2372. TClipboardHandler ClipboardHandler;
  2373. ClipboardHandler.Text = *POutput;
  2374. TMessageParams Params;
  2375. TQueryButtonAlias Aliases[1];
  2376. Aliases[0].Button = qaRetry;
  2377. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2378. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2379. Params.Aliases = Aliases;
  2380. Params.AliasesCount = LENOF(Aliases);
  2381. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2382. }
  2383. }
  2384. }
  2385. //---------------------------------------------------------------------------
  2386. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2387. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2388. {
  2389. TCustomCommandData Data;
  2390. UnicodeString Site;
  2391. UnicodeString RemotePath;
  2392. if (HasAvailableTerminal())
  2393. {
  2394. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2395. Data = TCustomCommandData(SessionData.get());
  2396. Site = Terminal->SessionData->SessionKey;
  2397. RemotePath = Terminal->CurrentDirectory;
  2398. }
  2399. UnicodeString HelpKeyword = ACommand.HomePage;
  2400. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2401. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2402. {
  2403. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2404. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2405. {
  2406. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2407. }
  2408. else
  2409. {
  2410. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2411. }
  2412. if (!DoCustomCommandOptionsDialog(
  2413. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2414. {
  2415. Abort();
  2416. }
  2417. }
  2418. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2419. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2420. {
  2421. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2422. }
  2423. else
  2424. {
  2425. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2426. }
  2427. }
  2428. //---------------------------------------------------------------------------
  2429. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2430. const TCustomCommandType & Command)
  2431. {
  2432. DebugAssert(FCustomCommandLocalFileList != NULL);
  2433. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2434. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2435. TStrings * LocalFileList = new TStringList();
  2436. TStrings * RemoteFileList = new TStringList();
  2437. try
  2438. {
  2439. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2440. {
  2441. LocalFileList->Clear();
  2442. LocalFileList->AddObject(
  2443. FCustomCommandLocalFileList->Strings[Index],
  2444. FCustomCommandLocalFileList->Objects[Index]);
  2445. RemoteFileList->Clear();
  2446. RemoteFileList->AddObject(
  2447. FCustomCommandRemoteFileList->Strings[Index],
  2448. FCustomCommandRemoteFileList->Objects[Index]);
  2449. CustomCommand(RemoteFileList, Command, LocalFileList);
  2450. }
  2451. }
  2452. __finally
  2453. {
  2454. delete LocalFileList;
  2455. delete RemoteFileList;
  2456. }
  2457. }
  2458. //---------------------------------------------------------------------------
  2459. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2460. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2461. {
  2462. delete FCustomCommandLocalFileList;
  2463. delete FCustomCommandRemoteFileList;
  2464. // takeover ownership,
  2465. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2466. FCustomCommandLocalFileList = LocalFileList;
  2467. FCustomCommandRemoteFileList = RemoteFileList;
  2468. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2469. if (Button != NULL)
  2470. {
  2471. FCustomCommandMenu->Items->Clear();
  2472. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2473. MenuPopup(FCustomCommandMenu, Button);
  2474. }
  2475. else
  2476. {
  2477. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2478. }
  2479. }
  2480. //---------------------------------------------------------------------------
  2481. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2482. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2483. {
  2484. DebugAssert(FCapturedLog != NULL);
  2485. if ((OutputType == cotOutput) || (OutputType == cotError))
  2486. {
  2487. FCapturedLog->Add(AddedLine);
  2488. }
  2489. }
  2490. //---------------------------------------------------------------------------
  2491. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2492. TOperationSide Side)
  2493. {
  2494. return
  2495. (Side == osOther) &&
  2496. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2497. }
  2498. //---------------------------------------------------------------------------
  2499. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2500. TOperationSide Side, TTBXCustomItem * Item,
  2501. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2502. {
  2503. TCustomDirView * DView = DirView(Side);
  2504. bool IsDefault = false;
  2505. if (DView->ItemFocused != NULL)
  2506. {
  2507. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2508. TResolvedDoubleClickAction DefaultAction =
  2509. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2510. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2511. }
  2512. TTBItemOptions O = Item->Options;
  2513. if (IsDefault)
  2514. {
  2515. Item->Options = O << tboDefault;
  2516. }
  2517. else
  2518. {
  2519. Item->Options = O >> tboDefault;
  2520. }
  2521. }
  2522. //---------------------------------------------------------------------------
  2523. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2524. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2525. {
  2526. TCustomDirView * DView = DirView(Side);
  2527. TListItem * Item = DView->ItemFocused;
  2528. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2529. EnableFocusedOperation[Side])
  2530. {
  2531. TPoint ClientPoint;
  2532. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2533. TPoint(0, 0) : MousePos;
  2534. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2535. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2536. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2537. }
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2541. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2542. {
  2543. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2544. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2545. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2546. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2547. Handled = true;
  2548. }
  2549. //---------------------------------------------------------------------------
  2550. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString DebugUsedArg(Directory))
  2551. {
  2552. }
  2553. //---------------------------------------------------------------------------
  2554. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2555. {
  2556. DebugAssert(FErrorList == NULL);
  2557. if (WinConfiguration->ContinueOnError)
  2558. {
  2559. FErrorList = new TStringList();
  2560. Configuration->Usage->Inc(L"ContinuationsOnError");
  2561. }
  2562. NonVisualDataModule->StartBusy();
  2563. }
  2564. //---------------------------------------------------------------------------
  2565. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2566. {
  2567. NonVisualDataModule->EndBusy();
  2568. if (FErrorList)
  2569. {
  2570. HandleErrorList(FErrorList);
  2571. }
  2572. }
  2573. //---------------------------------------------------------------------------
  2574. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2575. const TCopyParamType & CopyParam)
  2576. {
  2577. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2578. {
  2579. Configuration->Usage->Inc(L"FileMaskUses");
  2580. }
  2581. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2582. {
  2583. Configuration->Usage->Inc(L"OperationMaskUses");
  2584. }
  2585. }
  2586. //---------------------------------------------------------------------------
  2587. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2588. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2589. {
  2590. DebugAssert(!IsLocalBrowserMode());
  2591. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2592. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2593. TTransferOperationParam DefaultParam;
  2594. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2595. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2596. switch (Param.Queue)
  2597. {
  2598. case asOn:
  2599. CopyParam.Queue = true;
  2600. break;
  2601. case asOff:
  2602. CopyParam.Queue = false;
  2603. break;
  2604. case asAuto:
  2605. default:
  2606. // keep default
  2607. break;
  2608. }
  2609. bool Result =
  2610. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2611. if (Result)
  2612. {
  2613. DebugAssert(Terminal);
  2614. bool SelectionRestored = false;
  2615. TCustomDirView * DView = NULL;
  2616. if (HasDirView[Side])
  2617. {
  2618. DView = DirView(Side);
  2619. DView->SaveSelection();
  2620. DView->SaveSelectedNames();
  2621. }
  2622. UpdateCopyParamCounters(CopyParam);
  2623. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2624. DebugAssert(FTransferResumeList == NULL);
  2625. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2626. FMoveToQueue = false;
  2627. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2628. try
  2629. {
  2630. TStrings * PermanentFileList;
  2631. std::unique_ptr<TStrings> PermanentFileListOwner;
  2632. try
  2633. {
  2634. if (Side == osLocal)
  2635. {
  2636. PermanentFileList = FileList;
  2637. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2638. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2639. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2640. if (Operation == foMove)
  2641. {
  2642. ReloadLocalDirectory();
  2643. if (DView != NULL)
  2644. {
  2645. DView->RestoreSelection();
  2646. }
  2647. SelectionRestored = true;
  2648. }
  2649. }
  2650. else
  2651. {
  2652. // Clone the file list as it may refer to current directory files,
  2653. // which get destroyed, when the source directory is reloaded after foMove operation.
  2654. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2655. // But for a hotfix, we are not going to do such a big change.
  2656. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2657. PermanentFileList = PermanentFileListOwner.get();
  2658. try
  2659. {
  2660. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2661. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2662. }
  2663. __finally
  2664. {
  2665. if (Operation == foMove)
  2666. {
  2667. if (DView != NULL)
  2668. {
  2669. DView->RestoreSelection();
  2670. }
  2671. SelectionRestored = true;
  2672. }
  2673. ReloadLocalDirectory(Param.TargetDirectory);
  2674. }
  2675. }
  2676. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2677. if (FMoveToQueue)
  2678. {
  2679. Abort();
  2680. }
  2681. }
  2682. catch (EAbort &)
  2683. {
  2684. if (FMoveToQueue)
  2685. {
  2686. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2687. DebugAssert(CopyParam.TransferSkipList == NULL);
  2688. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2689. if (TransferResumeList->Count > 0)
  2690. {
  2691. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2692. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2693. }
  2694. CopyParam.TransferSkipList = TransferResumeList.release();
  2695. // not really needed, just to keep it consistent with TransferResumeList
  2696. FTransferResumeList = NULL;
  2697. FMoveToQueue = false;
  2698. Configuration->Usage->Inc("MovesToBackground");
  2699. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2700. ClearTransferSourceSelection(Direction);
  2701. }
  2702. throw;
  2703. }
  2704. }
  2705. __finally
  2706. {
  2707. if (!SelectionRestored && (DView != NULL))
  2708. {
  2709. DView->DiscardSavedSelection();
  2710. }
  2711. FTransferResumeList = NULL;
  2712. }
  2713. }
  2714. return Result;
  2715. }
  2716. //---------------------------------------------------------------------------
  2717. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2718. TOperationSide Side, TStrings * FileList, void * Param)
  2719. {
  2720. DebugAssert(FileList->Count);
  2721. // We deliberately do not toggle alternative flag (Param), but use OR,
  2722. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2723. // shortcut of CurrentDeleteAlternativeAction
  2724. bool Alternative =
  2725. bool(Param) || UseAlternativeFunction();
  2726. bool Recycle;
  2727. if (IsSideLocalBrowser(Side))
  2728. {
  2729. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2730. }
  2731. else
  2732. {
  2733. Recycle =
  2734. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2735. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2736. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2737. }
  2738. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2739. if (!Result)
  2740. {
  2741. UnicodeString Query;
  2742. if (FileList->Count == 1)
  2743. {
  2744. if (IsSideLocalBrowser(Side))
  2745. {
  2746. Query = ExtractFileName(FileList->Strings[0]);
  2747. }
  2748. else
  2749. {
  2750. Query = UnixExtractFileName(FileList->Strings[0]);
  2751. }
  2752. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2753. }
  2754. else
  2755. {
  2756. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2757. }
  2758. TMessageParams Params(mpNeverAskAgainCheck);
  2759. Params.ImageName = L"Delete file";
  2760. unsigned int Answer =
  2761. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2762. if (Answer == qaNeverAskAgain)
  2763. {
  2764. Result = true;
  2765. if (Recycle)
  2766. {
  2767. WinConfiguration->ConfirmRecycling = false;
  2768. }
  2769. else
  2770. {
  2771. WinConfiguration->ConfirmDeleting = false;
  2772. }
  2773. }
  2774. else
  2775. {
  2776. Result = (Answer == qaOK);
  2777. }
  2778. }
  2779. if (Result)
  2780. {
  2781. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2782. }
  2783. return Result;
  2784. }
  2785. //---------------------------------------------------------------------------
  2786. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2787. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2788. {
  2789. TAutoBatch AutoBatch(this);
  2790. bool Result;
  2791. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2792. {
  2793. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2794. }
  2795. else if (Operation == foRename)
  2796. {
  2797. DebugAssert(DirView(Side)->ItemFocused);
  2798. DirView(Side)->ItemFocused->EditCaption();
  2799. Result = true;
  2800. }
  2801. else if (Operation == foDelete)
  2802. {
  2803. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2804. }
  2805. else if (Operation == foSetProperties)
  2806. {
  2807. DirView(osRemote)->SaveSelectedNames();
  2808. Result = SetProperties(Side, FileList);
  2809. }
  2810. else if (Operation == foCustomCommand)
  2811. {
  2812. DebugAssert(Param);
  2813. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2814. DirView(osRemote)->SaveSelectedNames();
  2815. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2816. CustomCommand(FileList, *Command, NULL);
  2817. Result = true;
  2818. }
  2819. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2820. {
  2821. DebugAssert(!IsSideLocalBrowser(Side));
  2822. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2823. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2824. }
  2825. else if (Operation == foLock)
  2826. {
  2827. DebugAssert(!IsSideLocalBrowser(Side));
  2828. LockFiles(FileList, true);
  2829. Result = true;
  2830. }
  2831. else if (Operation == foUnlock)
  2832. {
  2833. DebugAssert(!IsSideLocalBrowser(Side));
  2834. LockFiles(FileList, false);
  2835. Result = true;
  2836. }
  2837. else
  2838. {
  2839. DebugFail();
  2840. Result = false; // shut up
  2841. }
  2842. return Result;
  2843. }
  2844. //---------------------------------------------------------------------------
  2845. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2846. {
  2847. if (Side == osCurrent)
  2848. {
  2849. Side = FCurrentSide;
  2850. }
  2851. return Side;
  2852. }
  2853. //---------------------------------------------------------------------------
  2854. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2855. {
  2856. TOperationSide Result;
  2857. switch (GetSide(Side))
  2858. {
  2859. case osLocal:
  2860. Result = osOther;
  2861. break;
  2862. case osOther:
  2863. Result = osLocal;
  2864. break;
  2865. default:
  2866. Result = osCurrent; // shut up
  2867. DebugFail();
  2868. Abort();
  2869. }
  2870. return Result;
  2871. }
  2872. //---------------------------------------------------------------------------
  2873. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2874. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2875. {
  2876. Side = GetSide(Side);
  2877. bool FullPath = IsSideLocalBrowser(Side);
  2878. TCustomDirView * ADirView = DirView(Side);
  2879. std::unique_ptr<TStringList> FileList(new TStringList());
  2880. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2881. bool ReloadProperties =
  2882. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2883. DebugAlwaysTrue(HasAvailableTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2884. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2885. if (Result && ReloadProperties)
  2886. {
  2887. std::unique_ptr<TStringList> FileList2(new TStringList());
  2888. FileList->CaseSensitive = true;
  2889. FileList->Sort();
  2890. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2891. {
  2892. TListItem * Item = ADirView->Items->Item[Index];
  2893. UnicodeString FileName = ADirView->ItemFileName(Item);
  2894. int Index2;
  2895. if (FileList->Find(FileName, Index2))
  2896. {
  2897. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2898. }
  2899. }
  2900. LoadFilesProperties(FileList2.get());
  2901. }
  2902. return Result;
  2903. }
  2904. //---------------------------------------------------------------------------
  2905. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2906. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2907. bool NoConfirmation, void * Param)
  2908. {
  2909. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2910. {
  2911. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2912. {
  2913. DebugAssert(!IsLocalBrowserMode());
  2914. if (GetSide(Side) == osLocal)
  2915. {
  2916. Configuration->Usage->Inc(L"UploadsCommand");
  2917. }
  2918. else
  2919. {
  2920. Configuration->Usage->Inc(L"DownloadsCommand");
  2921. }
  2922. }
  2923. }
  2924. }
  2925. //---------------------------------------------------------------------------
  2926. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2927. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2928. {
  2929. TTransferOperationParam Param;
  2930. if ((WinConfiguration->Interface != ifCommander) ||
  2931. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2932. {
  2933. Flags &= ~cocShortCutHint;
  2934. }
  2935. TCustomDirView * DView = DirView(Side);
  2936. Param.Options =
  2937. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2938. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2939. if (FLAGSET(Flags, cocQueue))
  2940. {
  2941. Param.Queue = asOn;
  2942. }
  2943. else if (FLAGSET(Flags, cocNonQueue))
  2944. {
  2945. Param.Queue = asOff;
  2946. }
  2947. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2948. }
  2949. //---------------------------------------------------------------------------
  2950. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2951. {
  2952. int Count = ErrorList->Count;
  2953. try
  2954. {
  2955. if (ErrorList->Count)
  2956. {
  2957. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2958. if (MessageDialog(Message, qtError,
  2959. qaOK | qaCancel, HELP_NONE) == qaOK)
  2960. {
  2961. unsigned int Answer;
  2962. int Index = 0;
  2963. do
  2964. {
  2965. DebugAssert(Index >= 0 && Index < Count);
  2966. TQueryButtonAlias Aliases[2];
  2967. Aliases[0].Button = qaYes;
  2968. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2969. Aliases[1].Button = qaNo;
  2970. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2971. TMessageParams Params;
  2972. Params.Aliases = Aliases;
  2973. Params.AliasesCount = LENOF(Aliases);
  2974. int No = Index + 1;
  2975. UnicodeString Message = ErrorList->Strings[Index];
  2976. UnicodeString AMainInstructions;
  2977. UnicodeString Details;
  2978. if (ExtractMainInstructions(Message, AMainInstructions))
  2979. {
  2980. Details = Message;
  2981. Message = AMainInstructions;
  2982. }
  2983. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2984. Answer = MoreMessageDialog(
  2985. Message,
  2986. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2987. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2988. qaOK, HELP_NONE, &Params);
  2989. if (Answer == qaNo)
  2990. {
  2991. Index++;
  2992. }
  2993. if (Answer == qaYes)
  2994. {
  2995. Index--;
  2996. }
  2997. }
  2998. while (Answer != qaOK);
  2999. }
  3000. }
  3001. }
  3002. __finally
  3003. {
  3004. TStrings * List = ErrorList;
  3005. ErrorList = NULL;
  3006. for (int i = 0; i < Count; i++)
  3007. {
  3008. delete List->Objects[i];
  3009. }
  3010. delete List;
  3011. }
  3012. }
  3013. //---------------------------------------------------------------------------
  3014. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3015. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3016. {
  3017. // needed for checking filemasks, as there's no directory object
  3018. // associated with the file object
  3019. File->FullFileName = FullFileName;
  3020. TFileMasks::TParams MaskParams;
  3021. MaskParams.Size = File->Size;
  3022. MaskParams.Modification = File->Modification;
  3023. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3024. }
  3025. //---------------------------------------------------------------------------
  3026. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3027. {
  3028. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3029. Side = GetSide(Side);
  3030. TCustomDirView * DView = DirView(Side);
  3031. TListItem * FocusedItem = DView->ItemFocused;
  3032. UnicodeString Name;
  3033. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3034. {
  3035. Name = DView->ItemFileName(FocusedItem);
  3036. }
  3037. else
  3038. {
  3039. Name = LoadStr(NEW_FILE);
  3040. }
  3041. UnicodeString Names = Name;
  3042. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3043. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3044. HELP_EDIT_NEW, History.get(), true, NULL, true, 444))
  3045. {
  3046. while (!Names.IsEmpty())
  3047. {
  3048. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3049. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3050. UnicodeString TargetFileName;
  3051. UnicodeString LocalFileName;
  3052. UnicodeString RootTempDir;
  3053. UnicodeString TempDir;
  3054. UnicodeString RemoteDirectory;
  3055. bool ExistingFile = false;
  3056. if (!IsSideLocalBrowser(Side))
  3057. {
  3058. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3059. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3060. if ((File.get() != NULL) &&
  3061. !File->IsDirectory)
  3062. {
  3063. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3064. ExistingFile = true;
  3065. }
  3066. File.reset(NULL);
  3067. if (!ExistingFile)
  3068. {
  3069. RemoteDirectory = UnixExtractFilePath(Name);
  3070. TemporaryDirectoryForRemoteFiles(
  3071. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3072. TargetFileName = UnixExtractFileName(Name);
  3073. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3074. LocalFileName = TempDir +
  3075. // We probably do not want to trim the VMS version here
  3076. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3077. }
  3078. }
  3079. else
  3080. {
  3081. if (ExtractFilePath(Name).IsEmpty())
  3082. {
  3083. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3084. }
  3085. else
  3086. {
  3087. LocalFileName = ExpandFileName(Name);
  3088. }
  3089. TargetFileName = ExtractFileName(Name);
  3090. }
  3091. if (!ExistingFile)
  3092. {
  3093. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3094. if (NewFile)
  3095. {
  3096. int File = FileCreate(ApiPath(LocalFileName));
  3097. if (File < 0)
  3098. {
  3099. if (!RootTempDir.IsEmpty())
  3100. {
  3101. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3102. }
  3103. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3104. }
  3105. else
  3106. {
  3107. FileClose(File);
  3108. }
  3109. }
  3110. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3111. const TEditorData * ExternalEditor = NULL;
  3112. TFileMasks::TParams MaskParams; // size not known
  3113. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3114. false, MaskParams);
  3115. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3116. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3117. }
  3118. }
  3119. }
  3120. }
  3121. //---------------------------------------------------------------------------
  3122. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3123. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3124. {
  3125. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3126. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3127. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3128. return
  3129. ((ExecuteFileBy == efInternalEditor)) ||
  3130. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3131. }
  3132. //---------------------------------------------------------------------------
  3133. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3134. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3135. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3136. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3137. {
  3138. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3139. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3140. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3141. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3142. Side = GetSide(Side);
  3143. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3144. if (!IsSideLocalBrowser(Side))
  3145. {
  3146. Data->Terminal = Terminal;
  3147. Data->SessionData = CloneCurrentSessionData();
  3148. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3149. Data->RemoteDirectory = RemoteDirectory;
  3150. Data->SessionName = Terminal->SessionData->SessionName;
  3151. Data->LocalRootDirectory = LocalRootDirectory;
  3152. Data->OriginalFileName = OriginalFileName;
  3153. Data->Command = L""; // will be changed later for external editor
  3154. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3155. if (WinConfiguration->EditorCheckNotModified)
  3156. {
  3157. Data->SourceTimestamp = SourceTimestamp;
  3158. }
  3159. }
  3160. if (ExecuteFileBy == efInternalEditor)
  3161. {
  3162. if (!IsSideLocalBrowser(Side))
  3163. {
  3164. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3165. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3166. TForm * Editor;
  3167. try
  3168. {
  3169. Editor =
  3170. ShowEditorForm(
  3171. FileName, this,
  3172. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3173. SaveAllInternalEditors, AnyInternalEditorModified,
  3174. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3175. }
  3176. catch(...)
  3177. {
  3178. if (!LocalRootDirectory.IsEmpty())
  3179. {
  3180. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3181. }
  3182. throw;
  3183. }
  3184. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3185. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3186. }
  3187. else
  3188. {
  3189. DebugAssert(!StandaloneOperation);
  3190. TForm * Editor =
  3191. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3192. SaveAllInternalEditors, AnyInternalEditorModified,
  3193. L"", false, SessionColor, -1, NewFile);
  3194. FLocalEditors->Add(Editor);
  3195. }
  3196. }
  3197. else
  3198. {
  3199. HANDLE Process;
  3200. if (ExecuteFileBy == efExternalEditor)
  3201. {
  3202. UnicodeString Program, Params, Dir;
  3203. Data->Command = ExternalEditor->ExternalEditor;
  3204. ReformatFileNameCommand(Data->Command);
  3205. SplitCommand(Data->Command, Program, Params, Dir);
  3206. Params = ExpandFileNameCommand(Params, FileName);
  3207. Program = ExpandEnvironmentVariables(Program);
  3208. if (!ExecuteShell(Program, Params, Process))
  3209. {
  3210. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3211. }
  3212. }
  3213. else
  3214. {
  3215. DebugAssert(!IsSideLocalBrowser(Side));
  3216. if (!ExecuteShell(FileName, L"", Process))
  3217. {
  3218. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3219. }
  3220. }
  3221. if (IsSideLocalBrowser(Side) ||
  3222. ((ExecuteFileBy == efShell) &&
  3223. !WinConfiguration->Editor.SDIShellEditor) ||
  3224. ((ExecuteFileBy == efExternalEditor) &&
  3225. !ExternalEditor->SDIExternalEditor))
  3226. {
  3227. // no need for handle
  3228. if (Process != NULL)
  3229. {
  3230. DebugCheck(CloseHandle(Process));
  3231. }
  3232. Process = INVALID_HANDLE_VALUE;
  3233. }
  3234. else
  3235. {
  3236. if (Process == NULL)
  3237. {
  3238. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3239. }
  3240. }
  3241. if (!IsSideLocalBrowser(Side))
  3242. {
  3243. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3244. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3245. }
  3246. }
  3247. }
  3248. //---------------------------------------------------------------------------
  3249. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3250. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3251. void * /*Arg*/)
  3252. {
  3253. if (Token != NULL)
  3254. {
  3255. EditorFormFileSave(static_cast<TForm *>(Token));
  3256. }
  3257. }
  3258. //---------------------------------------------------------------------------
  3259. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3260. {
  3261. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3262. {
  3263. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3264. }
  3265. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3266. }
  3267. //---------------------------------------------------------------------------
  3268. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3269. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3270. void * Arg)
  3271. {
  3272. if ((Token != NULL) &&
  3273. IsEditorFormModified(static_cast<TForm *>(Token)))
  3274. {
  3275. *static_cast<bool *>(Arg) = true;
  3276. }
  3277. }
  3278. //---------------------------------------------------------------------------
  3279. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3280. TObject * /*Sender*/, bool & Modified)
  3281. {
  3282. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3283. {
  3284. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3285. {
  3286. Modified = true;
  3287. }
  3288. }
  3289. if (!Modified)
  3290. {
  3291. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3292. }
  3293. }
  3294. //---------------------------------------------------------------------------
  3295. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3296. {
  3297. DebugCheckNotEqual(FLocalEditors->Extract(Sender), NULL);
  3298. }
  3299. //---------------------------------------------------------------------------
  3300. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3301. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3302. UnicodeString & Result, UnicodeString & RootDirectory)
  3303. {
  3304. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3305. {
  3306. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3307. Result = RootDirectory;
  3308. }
  3309. else
  3310. {
  3311. RootDirectory = L"";
  3312. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3313. Result = IncludeTrailingBackslash(Result);
  3314. }
  3315. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3316. {
  3317. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3318. }
  3319. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3320. {
  3321. UnicodeString ARemoteDirectory = RemoteDirectory;
  3322. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3323. {
  3324. ARemoteDirectory.Delete(1, 1);
  3325. }
  3326. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3327. }
  3328. if (!ForceDirectories(ApiPath(Result)))
  3329. {
  3330. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3331. }
  3332. }
  3333. //---------------------------------------------------------------------------
  3334. UnicodeString TCustomScpExplorerForm::GetTempLocalName(const UnicodeString & Path, const TCopyParamType & CopyParam)
  3335. {
  3336. return Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(Path), osRemote, false);
  3337. }
  3338. //---------------------------------------------------------------------------
  3339. void TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3340. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3341. bool AutoOperation, bool SimpleTempDir)
  3342. {
  3343. DebugAssert(!IsLocalBrowserMode());
  3344. TCopyParamType CopyParam = TemporaryFileCopyParam(ForceText);
  3345. if (TempDir.IsEmpty())
  3346. {
  3347. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3348. }
  3349. DebugAssert(!FAutoOperation);
  3350. FAutoOperation = AutoOperation;
  3351. FMoveToQueue = false;
  3352. Terminal->ExceptionOnFail = true;
  3353. try
  3354. {
  3355. try
  3356. {
  3357. // turn off confirmations, as for MDI editors we may possibly download
  3358. // the same file over
  3359. Terminal->CopyToLocal(
  3360. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3361. }
  3362. catch(...)
  3363. {
  3364. if (!RootTempDir.IsEmpty())
  3365. {
  3366. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3367. }
  3368. throw;
  3369. }
  3370. }
  3371. __finally
  3372. {
  3373. FAutoOperation = false;
  3374. Terminal->ExceptionOnFail = false;
  3375. }
  3376. }
  3377. //---------------------------------------------------------------------------
  3378. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3379. {
  3380. // Do not waste time checking for default editor list the next time,
  3381. // or testing if default editor is not notepad.
  3382. bool TryNextTime = false;
  3383. UnicodeString UsageState;
  3384. if (!WinConfiguration->EditorList->IsDefaultList())
  3385. {
  3386. UsageState = "H";
  3387. }
  3388. else
  3389. {
  3390. UnicodeString Executable;
  3391. UnicodeString ExecutableDescription;
  3392. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3393. {
  3394. UnicodeString Message =
  3395. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3396. unsigned int Answer =
  3397. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3398. if (Answer != qaOK)
  3399. {
  3400. UsageState = "R";
  3401. }
  3402. else
  3403. {
  3404. UsageState = "A";
  3405. TEditorData EditorData;
  3406. EditorData.Editor = edExternal;
  3407. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3408. EditorData.ExternalEditorOptionsAutodetect();
  3409. TEditorList EditorList;
  3410. EditorList = *WinConfiguration->EditorList;
  3411. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3412. WinConfiguration->EditorList = &EditorList;
  3413. }
  3414. }
  3415. }
  3416. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3417. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3418. }
  3419. //---------------------------------------------------------------------------
  3420. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3421. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3422. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3423. {
  3424. if (ExecuteFileBy == efDefaultEditor)
  3425. {
  3426. if (!WinConfiguration->OfferedEditorAutoConfig)
  3427. {
  3428. EditorAutoConfig();
  3429. }
  3430. const TEditorPreferences * Editor =
  3431. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3432. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3433. {
  3434. ExecuteFileBy = efInternalEditor;
  3435. ExternalEditor = NULL;
  3436. }
  3437. else if (Editor->Data->Editor == edOpen)
  3438. {
  3439. ExecuteFileBy = efShell;
  3440. ExternalEditor = NULL;
  3441. }
  3442. else
  3443. {
  3444. ExecuteFileBy = efExternalEditor;
  3445. ExternalEditor = Editor->Data;
  3446. }
  3447. }
  3448. }
  3449. //---------------------------------------------------------------------------
  3450. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3451. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3452. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3453. {
  3454. UnicodeString OriginalFileName;
  3455. UnicodeString LocalRootDirectory;
  3456. UnicodeString RemoteDirectory;
  3457. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3458. IsSideLocalBrowser(Side), MaskParams);
  3459. UnicodeString Counter;
  3460. UnicodeString LocalFileName;
  3461. bool Handled = false;
  3462. if (!IsSideLocalBrowser(Side))
  3463. {
  3464. // We need to trim VMS version here, so that we use name without version
  3465. // when uploading back to create a new version of the file
  3466. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3467. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3468. TObject * Token = NULL;
  3469. UnicodeString LocalDirectory;
  3470. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3471. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3472. LocalDirectory))
  3473. {
  3474. if (Token != NULL)
  3475. {
  3476. TForm * Form = dynamic_cast<TForm *>(Token);
  3477. if (Form->WindowState == wsMinimized)
  3478. {
  3479. ShowWindow(Form->Handle, SW_RESTORE);
  3480. }
  3481. else
  3482. {
  3483. Form->SetFocus();
  3484. }
  3485. Handled = true;
  3486. }
  3487. else
  3488. {
  3489. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3490. }
  3491. }
  3492. if (!Handled)
  3493. {
  3494. std::unique_ptr<TStrings> FileList1(new TStringList());
  3495. FileList1->AddObject(FullFileName, Object);
  3496. bool ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3497. TemporarilyDownloadFiles(FileList1.get(), ForceText, LocalRootDirectory, LocalDirectory, true, false);
  3498. LocalFileName = LocalDirectory + GetTempLocalName(FullFileName, TemporaryFileCopyParam(ForceText));
  3499. switch (ExecuteFileBy)
  3500. {
  3501. case efShell:
  3502. Counter = "RemoteFilesExecuted";
  3503. break;
  3504. case efInternalEditor:
  3505. Counter = "RemoteFilesOpenedInInternalEditor";
  3506. break;
  3507. case efExternalEditor:
  3508. Counter = "RemoteFilesOpenedInExternalEditor";
  3509. break;
  3510. default:
  3511. DebugFail();
  3512. }
  3513. }
  3514. }
  3515. else
  3516. {
  3517. LocalFileName = FullFileName;
  3518. OriginalFileName = ExtractFileName(FullFileName);
  3519. switch (ExecuteFileBy)
  3520. {
  3521. case efShell:
  3522. Counter = "LocalFilesExecuted";
  3523. break;
  3524. case efInternalEditor:
  3525. Counter = "LocalFilesOpenedInInternalEditor";
  3526. break;
  3527. case efExternalEditor:
  3528. Counter = "LocalFilesOpenedInExternalEditor";
  3529. break;
  3530. default:
  3531. DebugFail();
  3532. }
  3533. }
  3534. if (!Handled)
  3535. {
  3536. Configuration->Usage->Inc(Counter);
  3537. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3538. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3539. }
  3540. }
  3541. //---------------------------------------------------------------------------
  3542. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3543. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3544. bool AllSelected, bool OnFocused)
  3545. {
  3546. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3547. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3548. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3549. Side = GetSide(Side);
  3550. TCustomDirView * DView = DirView(Side);
  3551. TStrings * FileList =
  3552. AllSelected ?
  3553. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3554. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3555. try
  3556. {
  3557. DebugAssert(AllSelected || (FileList->Count == 1));
  3558. for (int i = 0; i < FileList->Count; i++)
  3559. {
  3560. UnicodeString ListFileName = FileList->Strings[i];
  3561. UnicodeString FileNameOnly =
  3562. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3563. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3564. if (!DView->ItemIsDirectory(Item))
  3565. {
  3566. UnicodeString FullFileName;
  3567. if (!IsSideLocalBrowser(Side))
  3568. {
  3569. FullFileName = DirView(Side)->Path + ListFileName;
  3570. }
  3571. else
  3572. {
  3573. FullFileName = ListFileName;
  3574. }
  3575. TObject * Object = FileList->Objects[i];
  3576. TFileMasks::TParams MaskParams;
  3577. MaskParams.Size = DView->ItemFileSize(Item);
  3578. TDateTimePrecision Precision;
  3579. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3580. std::unique_ptr<TRemoteFile> File;
  3581. if (!IsSideLocalBrowser(Side))
  3582. {
  3583. File.reset(Terminal->TryReadFile(FullFileName));
  3584. if (File.get() != NULL)
  3585. {
  3586. File->FullFileName = FullFileName;
  3587. Object = File.get();
  3588. MaskParams.Size = File->Size;
  3589. MaskParams.Modification = File->Modification;
  3590. }
  3591. }
  3592. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3593. }
  3594. }
  3595. }
  3596. __finally
  3597. {
  3598. delete FileList;
  3599. }
  3600. }
  3601. //---------------------------------------------------------------------------
  3602. TCopyParamType TCustomScpExplorerForm::TemporaryFileCopyParam(bool ForceText)
  3603. {
  3604. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3605. CopyParam.FileNameCase = ncNoChange;
  3606. CopyParam.PreserveRights = false;
  3607. CopyParam.PreserveReadOnly = false;
  3608. CopyParam.ReplaceInvalidChars = true;
  3609. CopyParam.IncludeFileMask = TFileMasks();
  3610. CopyParam.NewerOnly = false;
  3611. CopyParam.FileMask = L"";
  3612. if (ForceText)
  3613. {
  3614. CopyParam.TransferMode = tmAscii;
  3615. }
  3616. return CopyParam;
  3617. }
  3618. //---------------------------------------------------------------------------
  3619. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3620. {
  3621. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3622. }
  3623. //---------------------------------------------------------------------------
  3624. class TEditorUploadQueueItem : public TUploadQueueItem
  3625. {
  3626. public:
  3627. __fastcall TEditorUploadQueueItem(
  3628. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3629. const TCopyParamType * CopyParam, int Params) :
  3630. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, false)
  3631. {
  3632. }
  3633. protected:
  3634. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3635. {
  3636. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3637. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3638. }
  3639. };
  3640. //---------------------------------------------------------------------------
  3641. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3642. {
  3643. if (WinConfiguration->EditorCheckNotModified) // optimization
  3644. {
  3645. UnicodeString RemoteFilePath;
  3646. {
  3647. TGuard Guard(FEditorManager->Section);
  3648. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3649. if (DebugAlwaysTrue(Data != NULL) &&
  3650. EditorCheckNotModified(Data))
  3651. {
  3652. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3653. }
  3654. }
  3655. if (!RemoteFilePath.IsEmpty())
  3656. {
  3657. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3658. if (File.get() != NULL)
  3659. {
  3660. TGuard Guard(FEditorManager->Section);
  3661. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3662. if (DebugAlwaysTrue(Data != NULL))
  3663. {
  3664. Data->SourceTimestamp = File->Modification;
  3665. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3666. }
  3667. }
  3668. }
  3669. }
  3670. }
  3671. //---------------------------------------------------------------------------
  3672. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3673. const UnicodeString & FileName, const TDateTime & Timestamp, TEditedFileData * Data,
  3674. HANDLE UploadCompleteEvent, bool & Retry)
  3675. {
  3676. TTerminalManager * Manager = TTerminalManager::Instance();
  3677. bool IsInavailable = !IsAvailableTerminal(Data->Terminal);
  3678. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3679. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3680. {
  3681. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3682. Retry = true;
  3683. }
  3684. else if (Manager->IsReconnectingTerminal(Data->Terminal))
  3685. {
  3686. AppLog(L"Session is being reconnected, will retry the upload later");
  3687. Retry = true;
  3688. }
  3689. else if (IsInavailable &&
  3690. GUIConfiguration->SessionReopenAutoInactive &&
  3691. (Data->Terminal->NextInactiveReconnect != TDateTime()))
  3692. {
  3693. if (Data->Terminal->LastInactiveSave != Timestamp)
  3694. {
  3695. AppLog(L"Inactive session reconnect is pending, rescheduling it for as soon as possible to retry the upload");
  3696. Data->Terminal->NextInactiveReconnect = Now();
  3697. Data->Terminal->LastInactiveSave = Timestamp;
  3698. }
  3699. else
  3700. {
  3701. AppLog(L"Inactive session reconnect is pending, will retry the upload later");
  3702. }
  3703. Retry = true;
  3704. }
  3705. else if (IsInavailable)
  3706. {
  3707. if (!NonVisualDataModule->Busy)
  3708. {
  3709. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3710. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3711. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3712. if (Data->Terminal == NULL)
  3713. {
  3714. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3715. if (SameSiteTerminal != NULL)
  3716. {
  3717. UnicodeString Message =
  3718. FMTLOAD(EDIT_SESSION_REATTACH,
  3719. (FileNameOnly, Data->SessionName, FileNameOnly));
  3720. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3721. {
  3722. Data->Terminal = SameSiteTerminal;
  3723. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3724. // We might also overwrite session data
  3725. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3726. }
  3727. else
  3728. {
  3729. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3730. Abort();
  3731. }
  3732. }
  3733. }
  3734. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3735. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3736. {
  3737. UnicodeString Message =
  3738. MainInstructions(
  3739. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3740. TMessageParams Params(FLAGMASK(!GUIConfiguration->SessionReopenAutoInactive, mpNeverAskAgainCheck));
  3741. Params.NeverAskAgainTitle = LoadStr(ALWAYS_RECONNECT);
  3742. unsigned int Answer = MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_NONE, &Params);
  3743. if (Answer == qaNeverAskAgain)
  3744. {
  3745. GUIConfiguration->SessionReopenAutoInactive = true;
  3746. Answer = qaOK;
  3747. }
  3748. if (Answer == qaOK)
  3749. {
  3750. if (Terminal->Disconnected)
  3751. {
  3752. Manager->ActiveSession = Terminal;
  3753. ReconnectSession();
  3754. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3755. if (!IsAvailableTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3756. {
  3757. Abort();
  3758. }
  3759. }
  3760. else
  3761. {
  3762. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3763. }
  3764. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3765. }
  3766. else
  3767. {
  3768. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3769. Abort();
  3770. }
  3771. }
  3772. }
  3773. if (!IsAvailableTerminal(Data->Terminal))
  3774. {
  3775. Configuration->Usage->Inc(L"EditInactiveSession");
  3776. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3777. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3778. (ExtractFileName(FileName), Data->SessionName)));
  3779. }
  3780. }
  3781. if (!Retry && EditorCheckNotModified(Data))
  3782. {
  3783. if (NonVisualDataModule->Busy)
  3784. {
  3785. Retry = true;
  3786. }
  3787. else
  3788. {
  3789. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3790. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3791. if (File.get() != NULL)
  3792. {
  3793. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3794. if (File->Modification != Data->SourceTimestamp)
  3795. {
  3796. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3797. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3798. {
  3799. Abort();
  3800. }
  3801. }
  3802. }
  3803. }
  3804. }
  3805. if (!Retry)
  3806. {
  3807. TStrings * FileList = new TStringList();
  3808. try
  3809. {
  3810. FileList->Add(FileName);
  3811. // Consider using the same settings (preset) as when the file was downloaded.
  3812. // More over this does not reflect the actual session that will do the upload.
  3813. TCopyParamType CopyParam = TemporaryFileCopyParam(Data->ForceText);
  3814. // so i do not need to worry if masking algorithm works in all cases
  3815. // ("" means "copy file name", no masking is actually done)
  3816. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3817. {
  3818. CopyParam.FileMask = L"";
  3819. }
  3820. else
  3821. {
  3822. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3823. }
  3824. int Params = cpNoConfirmation | cpTemporary;
  3825. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3826. {
  3827. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3828. TQueueItem * QueueItem =
  3829. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3830. QueueItem->CompleteEvent = UploadCompleteEvent;
  3831. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3832. }
  3833. else
  3834. {
  3835. if (NonVisualDataModule->Busy)
  3836. {
  3837. Retry = true;
  3838. }
  3839. else
  3840. {
  3841. FMoveToQueue = false;
  3842. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3843. SetEvent(UploadCompleteEvent);
  3844. }
  3845. }
  3846. }
  3847. __finally
  3848. {
  3849. delete FileList;
  3850. }
  3851. }
  3852. }
  3853. //---------------------------------------------------------------------------
  3854. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3855. const UnicodeString & FileName, TEditedFileData * Data)
  3856. {
  3857. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3858. DebugAssert(!NonVisualDataModule->Busy);
  3859. if (!IsAvailableTerminal(Data->Terminal))
  3860. {
  3861. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3862. (ExtractFileName(FileName), Data->SessionName)));
  3863. }
  3864. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3865. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3866. NonVisualDataModule->StartBusy();
  3867. try
  3868. {
  3869. std::unique_ptr<TRemoteFile> File;
  3870. UnicodeString RemoteFileName =
  3871. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3872. Terminal->ExceptionOnFail = true;
  3873. try
  3874. {
  3875. File.reset(Terminal->ReadFile(RemoteFileName));
  3876. if (!File->HaveFullFileName)
  3877. {
  3878. File->FullFileName = RemoteFileName;
  3879. }
  3880. }
  3881. __finally
  3882. {
  3883. Terminal->ExceptionOnFail = false;
  3884. }
  3885. std::unique_ptr<TStrings> FileList(new TStringList());
  3886. FileList->AddObject(RemoteFileName, File.get());
  3887. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3888. UnicodeString TempDir = ExtractFilePath(FileName);
  3889. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, false);
  3890. if (EditorCheckNotModified(Data))
  3891. {
  3892. Data->SourceTimestamp = File->Modification;
  3893. }
  3894. }
  3895. __finally
  3896. {
  3897. NonVisualDataModule->EndBusy();
  3898. // it actually may not exist anymore...
  3899. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3900. }
  3901. }
  3902. //---------------------------------------------------------------------------
  3903. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3904. const TEditedFileData * Data, bool & KeepOpen)
  3905. {
  3906. // Command is set for external editors only (not for "shell" open).
  3907. if (!Data->Command.IsEmpty())
  3908. {
  3909. bool AnyFound = false;
  3910. bool AnyMDI = false;
  3911. bool AnyNonMDI = false;
  3912. bool AnyDetect = false;
  3913. TEditorList * EditorList = new TEditorList();
  3914. try
  3915. {
  3916. *EditorList = *WinConfiguration->EditorList;
  3917. for (int i = 0; i < EditorList->Count; i++)
  3918. {
  3919. const TEditorPreferences * Editor = EditorList->Editors[i];
  3920. if ((Editor->Data->Editor == edExternal) &&
  3921. (Editor->Data->ExternalEditor == Data->Command))
  3922. {
  3923. AnyFound = true;
  3924. if (Editor->Data->SDIExternalEditor)
  3925. {
  3926. AnyNonMDI = true;
  3927. if (Editor->Data->DetectMDIExternalEditor)
  3928. {
  3929. AnyDetect = true;
  3930. }
  3931. }
  3932. else
  3933. {
  3934. AnyMDI = true;
  3935. }
  3936. }
  3937. }
  3938. bool EnableMDI = false;
  3939. bool DisableDetect = false;
  3940. if (AnyMDI)
  3941. {
  3942. KeepOpen = true;
  3943. if (AnyNonMDI)
  3944. {
  3945. // there is at least one instance of the editor with MDI support enabled,
  3946. // and one with disabled, enable it for all instances
  3947. EnableMDI = true;
  3948. }
  3949. }
  3950. else if (AnyFound && !AnyDetect)
  3951. {
  3952. // at least once instance found but all have MDI autodetection disabled
  3953. // => close the file (default action)
  3954. }
  3955. else
  3956. {
  3957. // no instance of the editor has MDI support enabled
  3958. TMessageParams Params;
  3959. if (AnyFound)
  3960. {
  3961. // there is at least one instance of the editor
  3962. Params.Params |= mpNeverAskAgainCheck;
  3963. }
  3964. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3965. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3966. switch (Answer)
  3967. {
  3968. case qaNeverAskAgain:
  3969. DisableDetect = true;
  3970. break;
  3971. case qaNo:
  3972. EnableMDI = true;
  3973. KeepOpen = true;
  3974. break;
  3975. }
  3976. }
  3977. if (AnyFound && (EnableMDI || DisableDetect))
  3978. {
  3979. bool Changed = false;
  3980. for (int i = 0; i < EditorList->Count; i++)
  3981. {
  3982. const TEditorPreferences * Editor = EditorList->Editors[i];
  3983. if ((Editor->Data->Editor == edExternal) &&
  3984. (Editor->Data->ExternalEditor == Data->Command) &&
  3985. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3986. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3987. {
  3988. Changed = true;
  3989. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3990. if (EnableMDI)
  3991. {
  3992. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3993. }
  3994. if (DisableDetect)
  3995. {
  3996. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3997. }
  3998. EditorList->Change(i, UpdatedEditor);
  3999. }
  4000. }
  4001. if (Changed)
  4002. {
  4003. WinConfiguration->EditorList = EditorList;
  4004. }
  4005. }
  4006. }
  4007. __finally
  4008. {
  4009. delete EditorList;
  4010. }
  4011. }
  4012. else
  4013. {
  4014. // "open" case
  4015. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4016. qaOK, HELP_APP_EARLY_CLOSED);
  4017. }
  4018. }
  4019. //---------------------------------------------------------------------------
  4020. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4021. {
  4022. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4023. }
  4024. //---------------------------------------------------------------------------
  4025. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4026. {
  4027. SideEnter(osRemote);
  4028. }
  4029. //---------------------------------------------------------------------------
  4030. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4031. {
  4032. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4033. SideEnter(osRemote);
  4034. }
  4035. //---------------------------------------------------------------------------
  4036. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4037. {
  4038. FCurrentSide = Side;
  4039. if (Visible)
  4040. {
  4041. UpdateControls();
  4042. }
  4043. }
  4044. //---------------------------------------------------------------------------
  4045. void __fastcall TCustomScpExplorerForm::FileDeleted(
  4046. TOperationSide Side, const UnicodeString & FileName, bool Success, bool NotCancelled)
  4047. {
  4048. VisualiseOperationFinished(Side, FileName, Success && NotCancelled);
  4049. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4050. {
  4051. FDeletedFiles->Add(FileName);
  4052. }
  4053. }
  4054. //---------------------------------------------------------------------------
  4055. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4056. TStrings * FileList, bool Alternative)
  4057. {
  4058. TCustomDirView * DView = DirView(Side);
  4059. DView->SaveSelection();
  4060. DView->SaveSelectedNames();
  4061. DebugAssert(!FAlternativeDelete);
  4062. FAlternativeDelete = Alternative;
  4063. try
  4064. {
  4065. int Params = FLAGMASK(Alternative, dfAlternative);
  4066. bool Remote = !IsSideLocalBrowser(Side);
  4067. std::unique_ptr<TStringList> DeletedFiles;
  4068. std::unique_ptr<TStrings> PermanentFileList;
  4069. bool AllowMoveToQueue = (Terminal != NULL);
  4070. if (AllowMoveToQueue)
  4071. {
  4072. DeletedFiles.reset(new TStringList());
  4073. DeletedFiles->CaseSensitive = Remote;
  4074. }
  4075. try
  4076. {
  4077. DebugAssert(FDeletedFiles == NULL);
  4078. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles, DeletedFiles.get());
  4079. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4080. if (AllowMoveToQueue)
  4081. {
  4082. FOnFileOperationFinished = FileDeleted;
  4083. }
  4084. FMoveToQueue = false;
  4085. if (Remote)
  4086. {
  4087. DebugAssert(AllowMoveToQueue);
  4088. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4089. PermanentFileList.reset(TRemoteFileList::CloneStrings(FileList));
  4090. DebugAssert(Terminal != NULL);
  4091. Terminal->DeleteFiles(FileList, Params);
  4092. }
  4093. else
  4094. {
  4095. if (AllowMoveToQueue) // optimization)
  4096. {
  4097. PermanentFileList.reset(CloneStrings(FileList));
  4098. }
  4099. if (IsLocalBrowserMode())
  4100. {
  4101. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4102. }
  4103. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  4104. try
  4105. {
  4106. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, Params);
  4107. }
  4108. __finally
  4109. {
  4110. ReloadLocalDirectory();
  4111. }
  4112. }
  4113. // Probably not needed for deleting, just for consistency with transfer code
  4114. if (FMoveToQueue)
  4115. {
  4116. Abort();
  4117. }
  4118. }
  4119. catch (EAbort &)
  4120. {
  4121. if (FMoveToQueue && DebugAlwaysTrue(AllowMoveToQueue) && DebugAlwaysTrue(Terminal != NULL))
  4122. {
  4123. FMoveToQueue = false;
  4124. DeletedFiles->Sorted = true;
  4125. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4126. {
  4127. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4128. {
  4129. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4130. DebugAssert(Index == 0);
  4131. PermanentFileList->Delete(Index);
  4132. Index--;
  4133. }
  4134. }
  4135. if (Remote)
  4136. {
  4137. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4138. TQueueItem * QueueItem = new TRemoteDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4139. AddQueueItem(Queue, QueueItem, Terminal);
  4140. }
  4141. else
  4142. {
  4143. Configuration->Usage->Inc("MovesToBackgroundDeleteLocal");
  4144. TQueueItem * QueueItem = new TLocalDeleteQueueItem(PermanentFileList.get(), Params);
  4145. AddQueueItem(Queue, QueueItem, Terminal);
  4146. }
  4147. ClearOperationSelection(Side);
  4148. }
  4149. }
  4150. FAlternativeDelete = false;
  4151. }
  4152. catch(...)
  4153. {
  4154. FAlternativeDelete = false;
  4155. DView->DiscardSavedSelection();
  4156. throw;
  4157. }
  4158. DView->RestoreSelection();
  4159. }
  4160. //---------------------------------------------------------------------------
  4161. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4162. {
  4163. DebugAssert(Terminal);
  4164. DebugAssert(!IsLocalBrowserMode());
  4165. RemoteDirView->SaveSelection();
  4166. RemoteDirView->SaveSelectedNames();
  4167. try
  4168. {
  4169. if (Lock)
  4170. {
  4171. Terminal->LockFiles(FileList);
  4172. }
  4173. else
  4174. {
  4175. Terminal->UnlockFiles(FileList);
  4176. }
  4177. }
  4178. catch(...)
  4179. {
  4180. RemoteDirView->DiscardSavedSelection();
  4181. throw;
  4182. }
  4183. RemoteDirView->RestoreSelection();
  4184. }
  4185. //---------------------------------------------------------------------------
  4186. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4187. {
  4188. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4189. bool Result =
  4190. IsAvailableTerminal(ATerminal) &&
  4191. ATerminal->DirectoryExists(Directory);
  4192. return Result;
  4193. }
  4194. //---------------------------------------------------------------------------
  4195. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4196. {
  4197. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4198. return
  4199. !Terminal->IsCapable[fcRemoteCopy] ||
  4200. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4201. }
  4202. //---------------------------------------------------------------------------
  4203. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4204. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4205. bool NoConfirmation, bool Move)
  4206. {
  4207. DebugAssert(Terminal != NULL);
  4208. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4209. DebugAssert(!IsLocalBrowserMode());
  4210. if (Session == NULL)
  4211. {
  4212. Session = Terminal;
  4213. }
  4214. bool TargetConfirmed = false;
  4215. if (Session == Terminal)
  4216. {
  4217. if (RemoteDriveView->DropTarget != NULL)
  4218. {
  4219. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4220. TargetConfirmed = true;
  4221. }
  4222. else if (RemoteDirView->DropTarget != NULL)
  4223. {
  4224. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4225. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4226. TargetConfirmed = true;
  4227. }
  4228. else
  4229. {
  4230. Target = RemoteDirView->Path;
  4231. }
  4232. }
  4233. else
  4234. {
  4235. Target = GetSessionPath(Session, osRemote);
  4236. }
  4237. Target = UnixIncludeTrailingBackslash(Target);
  4238. if (FileList->Count == 1)
  4239. {
  4240. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4241. }
  4242. else
  4243. {
  4244. FileMask = AnyMask;
  4245. }
  4246. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4247. bool Result = true;
  4248. if (!NoConfirmation)
  4249. {
  4250. bool Multi = (FileList->Count > 1);
  4251. if (Move)
  4252. {
  4253. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4254. }
  4255. else
  4256. {
  4257. std::unique_ptr<TStrings> Sessions(new TStringList);
  4258. std::unique_ptr<TStrings> Directories(new TStringList);
  4259. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4260. for (int Index = 0; Index < SessionList->Count; Index++)
  4261. {
  4262. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4263. if (IsAvailableTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4264. {
  4265. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4266. Directories->Add(GetSessionPath(ASession, osRemote));
  4267. }
  4268. }
  4269. bool AnyDirectory = false;
  4270. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4271. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4272. {
  4273. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4274. {
  4275. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4276. }
  4277. }
  4278. TDirectRemoteCopy AllowDirectCopy;
  4279. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4280. {
  4281. DebugAssert(DirectCopy);
  4282. AllowDirectCopy = drcAllow;
  4283. }
  4284. else if (Terminal->IsCapable[fcSecondaryShell])
  4285. {
  4286. DebugAssert(DirectCopy);
  4287. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4288. }
  4289. else
  4290. {
  4291. DebugAssert(!DirectCopy);
  4292. AllowDirectCopy = drcDisallow;
  4293. }
  4294. void * ASession = Session;
  4295. Result = DoRemoteCopyDialog(
  4296. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4297. DoDirectoryExists, TargetConfirmed);
  4298. Session = static_cast<TManagedTerminal *>(ASession);
  4299. }
  4300. }
  4301. return Result;
  4302. }
  4303. //---------------------------------------------------------------------------
  4304. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4305. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4306. {
  4307. DebugAssert(!IsLocalBrowserMode());
  4308. bool DirectCopy;
  4309. UnicodeString Target, FileMask;
  4310. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4311. if (Result)
  4312. {
  4313. if (!Move && !DirectCopy)
  4314. {
  4315. Configuration->Usage->Inc("RemoteCopyTemp");
  4316. UnicodeString RootTempDir;
  4317. UnicodeString TempDir;
  4318. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true);
  4319. TStrings * TemporaryFilesList = new TStringList();
  4320. try
  4321. {
  4322. TMakeLocalFileListParams MakeFileListParam;
  4323. MakeFileListParam.FileList = TemporaryFilesList;
  4324. MakeFileListParam.FileTimes = NULL;
  4325. MakeFileListParam.IncludeDirs = true;
  4326. MakeFileListParam.Recursive = false;
  4327. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4328. TTerminalManager::Instance()->ActiveSession = Session;
  4329. if (TemporaryFilesList->Count > 0)
  4330. {
  4331. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4332. CopyParam.FileMask = FileMask;
  4333. DebugAssert(!FAutoOperation);
  4334. FAutoOperation = true;
  4335. FMoveToQueue = false;
  4336. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4337. }
  4338. }
  4339. __finally
  4340. {
  4341. delete TemporaryFilesList;
  4342. FAutoOperation = false;
  4343. if (!RootTempDir.IsEmpty())
  4344. {
  4345. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4346. }
  4347. }
  4348. }
  4349. else
  4350. {
  4351. RemoteDirView->SaveSelection();
  4352. RemoteDirView->SaveSelectedNames();
  4353. try
  4354. {
  4355. if (Move)
  4356. {
  4357. Configuration->Usage->Inc("RemoteMove");
  4358. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4359. }
  4360. else
  4361. {
  4362. Configuration->Usage->Inc("RemoteCopyDirect");
  4363. DebugAssert(DirectCopy);
  4364. DebugAssert(Session == Terminal);
  4365. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4366. Terminal->CommandSessionOpened ||
  4367. CommandSessionFallback())
  4368. {
  4369. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4370. }
  4371. }
  4372. }
  4373. catch(...)
  4374. {
  4375. RemoteDirView->DiscardSavedSelection();
  4376. throw;
  4377. }
  4378. RemoteDirView->RestoreSelection();
  4379. }
  4380. }
  4381. return Result;
  4382. }
  4383. //---------------------------------------------------------------------------
  4384. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4385. const UnicodeString & Path, TRemoteProperties & Properties)
  4386. {
  4387. DebugAssert(!IsLocalBrowserMode());
  4388. Properties.Valid = Properties.Valid << vpEncrypt;
  4389. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4390. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4391. }
  4392. //---------------------------------------------------------------------------
  4393. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4394. {
  4395. Side = GetSide(Side);
  4396. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4397. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4398. UnicodeString Name = LoadStr(NEW_FOLDER);
  4399. int AllowedChanges =
  4400. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4401. bool SaveSettings = false;
  4402. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4403. {
  4404. TWindowLock Lock(this);
  4405. if (!IsSideLocalBrowser(Side))
  4406. {
  4407. if (SaveSettings)
  4408. {
  4409. GUIConfiguration->NewDirectoryProperties = Properties;
  4410. }
  4411. CreateRemoteDirectory(Name, Properties);
  4412. }
  4413. else
  4414. {
  4415. DirView(Side)->CreateDirectory(Name);
  4416. }
  4417. }
  4418. }
  4419. //---------------------------------------------------------------------------
  4420. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4421. {
  4422. TWindowLock Lock(this);
  4423. DirView(Side)->ExecuteHomeDirectory();
  4424. }
  4425. //---------------------------------------------------------------------------
  4426. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4427. {
  4428. DoOpenDirectoryDialog(odBrowse, Side);
  4429. }
  4430. //---------------------------------------------------------------------------
  4431. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4432. {
  4433. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4434. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4435. bool Result = !Path.IsEmpty();
  4436. if (Result)
  4437. {
  4438. TryOpenDirectory(Side, Path);
  4439. }
  4440. return Result;
  4441. }
  4442. //---------------------------------------------------------------------------
  4443. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4444. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4445. bool & Close)
  4446. {
  4447. // terminal can be already closed (e.g. dropped connection)
  4448. if (Terminal != NULL)
  4449. {
  4450. try
  4451. {
  4452. TCalculateSizeParams Params;
  4453. Params.Stats = &Stats;
  4454. Terminal->CalculateFilesSize(FileList, Size, Params);
  4455. }
  4456. catch(...)
  4457. {
  4458. if (!Terminal->Active)
  4459. {
  4460. Close = true;
  4461. }
  4462. throw;
  4463. }
  4464. }
  4465. }
  4466. //---------------------------------------------------------------------------
  4467. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4468. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4469. bool & Close)
  4470. {
  4471. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4472. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4473. {
  4474. Configuration->Usage->Inc(L"ChecksumCalculated");
  4475. try
  4476. {
  4477. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4478. }
  4479. catch(...)
  4480. {
  4481. if (!Terminal->Active)
  4482. {
  4483. Close = true;
  4484. }
  4485. throw;
  4486. }
  4487. }
  4488. }
  4489. //---------------------------------------------------------------------------
  4490. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4491. {
  4492. if (Terminal->LoadFilesProperties(FileList))
  4493. {
  4494. RemoteDirView->Invalidate();
  4495. }
  4496. }
  4497. //---------------------------------------------------------------------------
  4498. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4499. {
  4500. return
  4501. Terminal->IsCapable[fcCalculatingChecksum] ||
  4502. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4503. }
  4504. //---------------------------------------------------------------------------
  4505. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4506. {
  4507. bool Result;
  4508. if (!IsSideLocalBrowser(Side))
  4509. {
  4510. TRemoteTokenList * GroupList = NULL;
  4511. TRemoteTokenList * UserList = NULL;
  4512. try
  4513. {
  4514. TRemoteProperties CurrentProperties;
  4515. LoadFilesProperties(FileList);
  4516. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4517. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4518. if (CapableGroupChanging || CapableOwnerChanging)
  4519. {
  4520. if (CapableGroupChanging)
  4521. {
  4522. GroupList = Terminal->Groups->Duplicate();
  4523. }
  4524. if (CapableOwnerChanging)
  4525. {
  4526. UserList = Terminal->Users->Duplicate();
  4527. }
  4528. TRemoteDirectory * Files = Terminal->Files;
  4529. int Count = Files->Count;
  4530. if (Count > 100)
  4531. {
  4532. Count = 100;
  4533. }
  4534. for (int Index = 0; Index < Count; Index++)
  4535. {
  4536. TRemoteFile * File = Files->Files[Index];
  4537. if (CapableGroupChanging)
  4538. {
  4539. GroupList->AddUnique(File->Group);
  4540. }
  4541. if (CapableOwnerChanging)
  4542. {
  4543. UserList->AddUnique(File->Owner);
  4544. }
  4545. }
  4546. // if we haven't collected tokens for all files in current directory,
  4547. // make sure we collect them at least for all selected files.
  4548. // (note that so far the files in FileList has to be from current direcotry)
  4549. if (Count < Files->Count)
  4550. {
  4551. for (int Index = 0; Index < FileList->Count; Index++)
  4552. {
  4553. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4554. if (CapableGroupChanging)
  4555. {
  4556. GroupList->AddUnique(File->Group);
  4557. }
  4558. if (CapableOwnerChanging)
  4559. {
  4560. UserList->AddUnique(File->Owner);
  4561. }
  4562. }
  4563. }
  4564. }
  4565. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4566. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4567. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4568. {
  4569. CapableAclChanging = false;
  4570. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4571. }
  4572. int Flags = 0;
  4573. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4574. if (CapableAclChanging) Flags |= cpAcl;
  4575. if (CapableOwnerChanging) Flags |= cpOwner;
  4576. if (CapableGroupChanging) Flags |= cpGroup;
  4577. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4578. if (CanCalculateChecksum())
  4579. {
  4580. CalculateChecksumEvent = CalculateChecksum;
  4581. }
  4582. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4583. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4584. int Options =
  4585. FLAGMASK(Terminal->IsCapable[fcGroupOwnerChangingByID], poUserGroupByID) |
  4586. FLAGMASK(Terminal->IsCapable[fcTags], poTags);
  4587. TRemoteProperties NewProperties = CurrentProperties;
  4588. Result =
  4589. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4590. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags, Options,
  4591. CalculateSize, CalculateChecksumEvent);
  4592. if (Result)
  4593. {
  4594. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4595. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4596. }
  4597. }
  4598. __finally
  4599. {
  4600. delete GroupList;
  4601. delete UserList;
  4602. }
  4603. }
  4604. else
  4605. {
  4606. DirView(Side)->DisplayPropertiesMenu();
  4607. Result = true;
  4608. }
  4609. return Result;
  4610. }
  4611. //---------------------------------------------------------------------------
  4612. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4613. {
  4614. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4615. {
  4616. FIgnoreNextDialogChar = Key;
  4617. }
  4618. Key = 0;
  4619. }
  4620. //---------------------------------------------------------------------------
  4621. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4622. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4623. {
  4624. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4625. if (Command != NULL)
  4626. {
  4627. KeyProcessed(Key, Shift);
  4628. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4629. {
  4630. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4631. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4632. false, false, const_cast<TCustomCommandType *>(Command));
  4633. }
  4634. }
  4635. }
  4636. //---------------------------------------------------------------------------
  4637. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4638. {
  4639. if (!NonVisualDataModule->Busy)
  4640. {
  4641. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4642. {
  4643. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4644. }
  4645. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4646. {
  4647. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4648. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4649. {
  4650. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4651. // But so far it's not a problem, as it does what we want.
  4652. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4653. if (((Action->ShortCut == KeyShortCut) ||
  4654. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4655. AllowedAction(Action, aaShortCut))
  4656. {
  4657. // Has to be called before the action as the dialog char is already in queue.
  4658. // So when the action consumes message queue, we already need to have the
  4659. // FIgnoreNextDialogChar set
  4660. KeyProcessed(Key, Shift);
  4661. // Reset reference to previous component (when menu/toolbar was clicked).
  4662. // Needed to detect that action was invoked by keyboard shortcut
  4663. // in TNonVisualDataModule::ExplorerActionsExecute
  4664. Action->ActionComponent = NULL;
  4665. Action->Execute();
  4666. return;
  4667. }
  4668. }
  4669. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4670. {
  4671. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4672. {
  4673. KeyProcessed(Key, Shift);
  4674. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4675. return;
  4676. }
  4677. }
  4678. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4679. {
  4680. KeyProcessed(Key, Shift);
  4681. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4682. }
  4683. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4684. if (IsCustomShortCut(CustomShortCut))
  4685. {
  4686. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4687. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4688. if (WinConfiguration->SharedBookmarks != NULL)
  4689. {
  4690. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4691. if ((Bookmark != NULL) &&
  4692. OpenBookmark(FCurrentSide, Bookmark))
  4693. {
  4694. KeyProcessed(Key, Shift);
  4695. }
  4696. }
  4697. }
  4698. }
  4699. }
  4700. TForm::KeyDown(Key, Shift);
  4701. }
  4702. //---------------------------------------------------------------------------
  4703. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4704. {
  4705. bool OpenedTerminal = false;
  4706. UnicodeString ProtocolName;
  4707. UnicodeString ProtocolNameHint;
  4708. UnicodeString SecurityProtocolName;
  4709. UnicodeString DurationHint;
  4710. // See the comment in TScpCommanderForm::UpdateControls()
  4711. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4712. if (ActiveTerminal != NULL)
  4713. {
  4714. // Active is not enough here
  4715. if (ActiveTerminal->Status == ssOpened)
  4716. {
  4717. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4718. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4719. if (FileSystemInfo.ProtocolName.IsEmpty())
  4720. {
  4721. ProtocolName = SessionInfo.ProtocolName;
  4722. }
  4723. else
  4724. {
  4725. ProtocolName = FileSystemInfo.ProtocolName;
  4726. }
  4727. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4728. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4729. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4730. OpenedTerminal = true;
  4731. }
  4732. else if (ActiveTerminal->Status > ssClosed)
  4733. {
  4734. ProtocolName = LoadStr(STATUS_CONNECTING);
  4735. }
  4736. else
  4737. {
  4738. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4739. }
  4740. }
  4741. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4742. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4743. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4744. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4745. if (ProtocolStatusPanel->Caption != ProtocolName)
  4746. {
  4747. ProtocolStatusPanel->Caption = ProtocolName;
  4748. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4749. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4750. }
  4751. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4752. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4753. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4754. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4755. SecurityStatusPanel->Enabled = SecurityEnabled;
  4756. UnicodeString SecurityProtocolHint;
  4757. if (SecurityEnabled)
  4758. {
  4759. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4760. }
  4761. else
  4762. {
  4763. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4764. }
  4765. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4766. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4767. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4768. DurationStatusPanel->Hint = DurationHint;
  4769. UpdateStatusBar();
  4770. }
  4771. //---------------------------------------------------------------------------
  4772. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4773. {
  4774. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4775. DebugAssert(SessionStatusBar != NULL);
  4776. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4777. if (!FNote.IsEmpty())
  4778. {
  4779. NoteStatusPanel->Caption = FNote;
  4780. }
  4781. else
  4782. {
  4783. UpdateStatusPanelText(NoteStatusPanel);
  4784. }
  4785. NoteStatusPanel->Hint = FNoteHints;
  4786. UnicodeString LoginTime;
  4787. // See the comment in TScpCommanderForm::UpdateControls()
  4788. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4789. // Active is not enough here
  4790. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4791. {
  4792. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4793. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4794. }
  4795. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4796. DurationStatusPanel->Caption = LoginTime;
  4797. }
  4798. //---------------------------------------------------------------------------
  4799. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4800. {
  4801. Panel->Caption = L"";
  4802. }
  4803. //---------------------------------------------------------------------------
  4804. void __fastcall TCustomScpExplorerForm::Idle()
  4805. {
  4806. if (FShowing ||
  4807. // Particularly for
  4808. // - Standalone editing
  4809. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4810. // while "keeping remote directory up to date".
  4811. StandaloneOperation)
  4812. {
  4813. FEditorManager->Check();
  4814. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4815. // that needs to know if queue view is visible (and it may be closed after queue update)
  4816. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4817. }
  4818. if (FShowing)
  4819. {
  4820. if (!NonVisualDataModule->Busy &&
  4821. // Menu is opened or drag&drop is going on
  4822. (Mouse->Capture == NULL))
  4823. {
  4824. if (FRefreshRemoteDirectory)
  4825. {
  4826. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4827. {
  4828. Terminal->RefreshDirectory();
  4829. }
  4830. FRefreshRemoteDirectory = false;
  4831. }
  4832. if (FRefreshLocalDirectory)
  4833. {
  4834. ReloadLocalDirectory();
  4835. FRefreshLocalDirectory = false;
  4836. }
  4837. if (WinConfiguration->RefreshRemotePanel)
  4838. {
  4839. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4840. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4841. {
  4842. RemoteDirView->ReloadDirectory();
  4843. }
  4844. }
  4845. }
  4846. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4847. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4848. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4849. // And the Alt key can be released even when other window or application is active, so handling the key up in explorer window won't do either.
  4850. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4851. MenuToolbar->Idle();
  4852. }
  4853. if (FShowing || StandaloneOperation)
  4854. {
  4855. if (FQueueStatusInvalidated)
  4856. {
  4857. UpdateQueueStatus(false);
  4858. }
  4859. RefreshQueueItems();
  4860. }
  4861. if (FShowing)
  4862. {
  4863. UpdateStatusBar();
  4864. }
  4865. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4866. {
  4867. FClipboardFakeMonitorsPendingReset = false;
  4868. FClipboardFakeMonitors.reset(NULL);
  4869. }
  4870. FIgnoreNextDialogChar = 0;
  4871. }
  4872. //---------------------------------------------------------------------------
  4873. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4874. {
  4875. try
  4876. {
  4877. FUserActionTimer->Enabled = false;
  4878. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4879. {
  4880. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4881. {
  4882. FPendingQueueActionItem->ProcessUserAction();
  4883. }
  4884. }
  4885. }
  4886. __finally
  4887. {
  4888. FPendingQueueActionItem = NULL;
  4889. }
  4890. }
  4891. //---------------------------------------------------------------------------
  4892. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4893. {
  4894. if (WinConfiguration->MinimizeToTray)
  4895. {
  4896. UpdateTrayIcon();
  4897. FTrayIcon->Visible = true;
  4898. if (Visible)
  4899. {
  4900. ShowWindow(Handle, SW_HIDE);
  4901. }
  4902. }
  4903. }
  4904. //---------------------------------------------------------------------------
  4905. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4906. {
  4907. // WORKAROUND
  4908. // When restoring maximized window from minimization,
  4909. // rarely some controls do not align properly.
  4910. // Two instances seen (both for Commander):
  4911. // - When restoring, window is temporarily narrower (not maximized),
  4912. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4913. // Once maximized already, top dock shinks back, but the session PageControl,
  4914. // do not align up, leaving space between TopDock and PageControl.
  4915. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4916. for (int Index = 0; Index < ControlCount; Index++)
  4917. {
  4918. RealignControl(Controls[Index]);
  4919. }
  4920. if (FTrayIcon->Visible)
  4921. {
  4922. FTrayIcon->Visible = false;
  4923. if (Visible)
  4924. {
  4925. ShowWindow(Handle, SW_SHOW);
  4926. }
  4927. }
  4928. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4929. {
  4930. FNeedSession = false;
  4931. NonVisualDataModule->StartBusy();
  4932. try
  4933. {
  4934. NeedSession(true);
  4935. }
  4936. __finally
  4937. {
  4938. NonVisualDataModule->EndBusy();
  4939. }
  4940. }
  4941. }
  4942. //---------------------------------------------------------------------------
  4943. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4944. {
  4945. FTrayIcon->Hint = GetMainForm()->Caption;
  4946. }
  4947. //---------------------------------------------------------------------------
  4948. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4949. {
  4950. UpdateTrayIcon();
  4951. }
  4952. //---------------------------------------------------------------------------
  4953. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4954. {
  4955. // workaround
  4956. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4957. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4958. // But WM_ACTIVATEAPP message can be received even when
  4959. // the main window is minimized to the tray and internal editor window is focused
  4960. // (after another application was previously active)
  4961. if (::IsIconic(Handle))
  4962. {
  4963. if (!IsAppIconic())
  4964. {
  4965. SetAppIconic(true);
  4966. }
  4967. }
  4968. ::ApplicationRestore();
  4969. Application->BringToFront();
  4970. }
  4971. //---------------------------------------------------------------------------
  4972. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4973. {
  4974. RestoreApp();
  4975. }
  4976. //---------------------------------------------------------------------------
  4977. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4978. {
  4979. if (OpenInNewWindow())
  4980. {
  4981. ExecuteNewInstance(SessionUrl);
  4982. }
  4983. else
  4984. {
  4985. TTerminalManager::Instance()->NewSession(SessionUrl);
  4986. }
  4987. }
  4988. //---------------------------------------------------------------------------
  4989. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4990. {
  4991. NewSession();
  4992. }
  4993. //---------------------------------------------------------------------------
  4994. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4995. {
  4996. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4997. StoredSessions->NewSession(SessionName, SessionData);
  4998. // modified only, explicit
  4999. StoredSessions->Save(false, true);
  5000. // encode session name because of slashes in hierarchical sessions
  5001. return EncodeUrlString(SessionName);
  5002. }
  5003. //---------------------------------------------------------------------------
  5004. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  5005. {
  5006. // current working directories become defaults here, what is not right
  5007. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5008. return SaveHiddenDuplicateSession(SessionData.get());
  5009. }
  5010. //---------------------------------------------------------------------------
  5011. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  5012. {
  5013. if (OpenInNewWindow())
  5014. {
  5015. ExecuteNewInstance(CreateHiddenDuplicateSession());
  5016. }
  5017. else
  5018. {
  5019. // current working directories become defaults here, what is not right
  5020. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5021. TTerminalManager * Manager = TTerminalManager::Instance();
  5022. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  5023. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  5024. // We definitely want these
  5025. ASession->Disconnected = ManagedSession->Disconnected;
  5026. // Not sure about these two
  5027. ASession->Permanent = ManagedSession->Permanent;
  5028. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  5029. Manager->ActiveSession = ASession;
  5030. }
  5031. }
  5032. //---------------------------------------------------------------------------
  5033. void __fastcall TCustomScpExplorerForm::RenameTab()
  5034. {
  5035. UnicodeString Name = ManagedSession->SessionData->SessionName;
  5036. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  5037. // When submitting the default name, do not fix it
  5038. (Name != ManagedSession->SessionData->SessionName))
  5039. {
  5040. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5041. TSessionData::ValidateName(Name);
  5042. // This is inconsistent with how color (for example) is handled.
  5043. ManagedSession->SessionData->Name = Name;
  5044. UpdateControls();
  5045. // Add/Remove distinguishing paths from sessions of the same name.
  5046. SessionListChanged();
  5047. }
  5048. }
  5049. //---------------------------------------------------------------------------
  5050. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5051. {
  5052. DebugAssert(Queue != NULL);
  5053. bool Result = Queue->IsEmpty;
  5054. if (!Result)
  5055. {
  5056. SetFocus();
  5057. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5058. }
  5059. return Result;
  5060. }
  5061. //---------------------------------------------------------------------------
  5062. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5063. {
  5064. return CanCloseQueue(FQueue);
  5065. }
  5066. //---------------------------------------------------------------------------
  5067. void __fastcall TCustomScpExplorerForm::CloseTab()
  5068. {
  5069. if (CanCloseQueue())
  5070. {
  5071. TTerminalManager::Instance()->FreeActiveTerminal();
  5072. }
  5073. }
  5074. //---------------------------------------------------------------------------
  5075. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5076. {
  5077. if (CanCloseQueue())
  5078. {
  5079. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5080. }
  5081. }
  5082. //---------------------------------------------------------------------------
  5083. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5084. {
  5085. DetachTerminal(Terminal);
  5086. RemoteDirView->Terminal = Terminal;
  5087. UpdateRemotePathComboBox(false);
  5088. InitStatusBar();
  5089. UpdateControls();
  5090. }
  5091. //---------------------------------------------------------------------------
  5092. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5093. {
  5094. InitStatusBar();
  5095. }
  5096. //---------------------------------------------------------------------------
  5097. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5098. {
  5099. if (DebugAlwaysTrue(!Terminal->Active))
  5100. {
  5101. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5102. }
  5103. }
  5104. //---------------------------------------------------------------------------
  5105. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5106. {
  5107. if (OpenInNewWindow())
  5108. {
  5109. // encode session name because of slashes in hierarchical sessions
  5110. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5111. }
  5112. else
  5113. {
  5114. TTerminalManager * Manager = TTerminalManager::Instance();
  5115. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5116. Manager->ActiveSession = Terminal;
  5117. }
  5118. }
  5119. //---------------------------------------------------------------------------
  5120. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5121. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5122. {
  5123. TTerminalManager * Manager = TTerminalManager::Instance();
  5124. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5125. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5126. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5127. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5128. {
  5129. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5130. // FirstSession can be null, if none of the workspace sites exist anymore
  5131. // or if all workspace sessions are not suported by the interface
  5132. // (when trying to open all local-local workspace in "explorer" interface)
  5133. if (FirstSession != NULL)
  5134. {
  5135. if (!ConnectFirstTerminal)
  5136. {
  5137. FirstSession->Disconnected = true;
  5138. FirstSession->DisconnectedTemporarily = true;
  5139. }
  5140. Manager->ActiveSession = FirstSession;
  5141. }
  5142. }
  5143. }
  5144. //---------------------------------------------------------------------------
  5145. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5146. {
  5147. if (OpenInNewWindow())
  5148. {
  5149. ExecuteNewInstance(Name);
  5150. }
  5151. else
  5152. {
  5153. DoOpenFolderOrWorkspace(Name, true, false);
  5154. }
  5155. }
  5156. //---------------------------------------------------------------------------
  5157. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5158. bool &CanClose)
  5159. {
  5160. AppLog(L"Windows close query");
  5161. // See the comment in CloseApp()
  5162. if (NonVisualDataModule->Busy)
  5163. {
  5164. CanClose = false;
  5165. }
  5166. else
  5167. {
  5168. TTerminalManager * Manager = TTerminalManager::Instance();
  5169. int ActiveSessions = 0;
  5170. for (int Index = 0; Index < Manager->Count; Index++)
  5171. {
  5172. if (Manager->Sessions[Index]->Active)
  5173. {
  5174. ActiveSessions++;
  5175. }
  5176. }
  5177. // Confirm, when there's at least one active remote session or
  5178. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5179. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5180. WinConfiguration->ConfirmClosingSession)
  5181. {
  5182. unsigned int Result;
  5183. TMessageParams Params(mpNeverAskAgainCheck);
  5184. UnicodeString Message;
  5185. int Answers = qaOK | qaCancel;
  5186. // The current session is the only active session
  5187. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5188. {
  5189. if (!WinConfiguration->AutoSaveWorkspace)
  5190. {
  5191. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5192. }
  5193. else
  5194. {
  5195. Message = LoadStr(CLOSE_SESSION);
  5196. }
  5197. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5198. }
  5199. // Multiple active sessions or one active session, but it's not the current one
  5200. else if (ActiveSessions > 0)
  5201. {
  5202. if (!WinConfiguration->AutoSaveWorkspace)
  5203. {
  5204. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5205. }
  5206. else
  5207. {
  5208. Message = LoadStr(CLOSE_SESSIONS);
  5209. }
  5210. }
  5211. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5212. else
  5213. {
  5214. DebugAssert(Manager->Count > 1);
  5215. DebugAssert(!WinConfiguration->AutoSaveWorkspace);
  5216. Message = LoadStr(CLOSE_WORKSPACE);
  5217. }
  5218. UnicodeString Note;
  5219. if (WinConfiguration->AutoSaveWorkspace)
  5220. {
  5221. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5222. }
  5223. else
  5224. {
  5225. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5226. Answers = qaYes | qaNo | qaCancel;
  5227. }
  5228. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5229. SetFocus();
  5230. Result = MessageDialog(Message, qtConfirmation,
  5231. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5232. if (Result == qaNeverAskAgain)
  5233. {
  5234. WinConfiguration->ConfirmClosingSession = false;
  5235. }
  5236. if (Result == qaNo)
  5237. {
  5238. CanClose = SaveWorkspace(true);
  5239. // note that the workspace will be saved redundatly again from FormClose
  5240. }
  5241. else
  5242. {
  5243. CanClose =
  5244. (Result == qaOK) ||
  5245. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5246. (Result == qaNeverAskAgain);
  5247. }
  5248. }
  5249. if (CanClose && HasAvailableTerminal())
  5250. {
  5251. CanClose = CanCloseQueue();
  5252. }
  5253. }
  5254. if (CanClose)
  5255. {
  5256. CanClose =
  5257. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5258. FEditorManager->CloseExternalFilesWithoutProcess();
  5259. if (CanClose)
  5260. {
  5261. while (CanClose && (FLocalEditors->Count > 0))
  5262. {
  5263. int PrevCount = FLocalEditors->Count;
  5264. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5265. CanClose = (FLocalEditors->Count < PrevCount);
  5266. }
  5267. if (CanClose)
  5268. {
  5269. CanClose = FEditorManager->Empty(true);
  5270. if (!CanClose)
  5271. {
  5272. SetFocus();
  5273. CanClose =
  5274. (MessageDialog(
  5275. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5276. }
  5277. }
  5278. }
  5279. }
  5280. }
  5281. //---------------------------------------------------------------------------
  5282. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5283. {
  5284. TForm * Form = dynamic_cast<TForm *>(Sender);
  5285. DebugAssert(Form != NULL);
  5286. Form->Close();
  5287. }
  5288. //---------------------------------------------------------------------------
  5289. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5290. {
  5291. TForm * Form = dynamic_cast<TForm *>(Sender);
  5292. delete Form;
  5293. }
  5294. //---------------------------------------------------------------------------
  5295. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5296. {
  5297. while (FLocalEditors->Count > 0)
  5298. {
  5299. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5300. }
  5301. }
  5302. //---------------------------------------------------------------------------
  5303. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5304. TObject *Sender)
  5305. {
  5306. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5307. try
  5308. {
  5309. SetProperties(osRemote, FileList);
  5310. }
  5311. __finally
  5312. {
  5313. delete FileList;
  5314. }
  5315. }
  5316. //---------------------------------------------------------------------------
  5317. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5318. {
  5319. if (value)
  5320. {
  5321. if (Component == fcCustomCommandsBand)
  5322. {
  5323. UpdateCustomCommandsToolbar();
  5324. }
  5325. if (Component == fcQueueFileList)
  5326. {
  5327. DebugAssert(!QueueFileListSplitter->Visible);
  5328. AdjustQueueLayout();
  5329. UpdateQueueFileList();
  5330. }
  5331. }
  5332. }
  5333. //---------------------------------------------------------------------------
  5334. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5335. {
  5336. int MinHeightLimit =
  5337. GetStaticQueuePanelComponentsHeight() +
  5338. QueueFileListSplitter->Height +
  5339. QueueFileList->Height +
  5340. GetMinQueueViewHeight();
  5341. if (QueuePanel->ClientHeight < MinHeightLimit)
  5342. {
  5343. QueuePanel->ClientHeight = MinHeightLimit;
  5344. }
  5345. }
  5346. //---------------------------------------------------------------------------
  5347. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5348. {
  5349. TControl * Control = GetComponent(Component);
  5350. DebugAssert(Control);
  5351. bool Changed = (Control->Visible != value);
  5352. if (Changed)
  5353. {
  5354. ComponentShowing(Component, value);
  5355. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5356. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5357. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5358. if (value)
  5359. {
  5360. int RemainingHeight = Control->Parent->ClientHeight;
  5361. int RemainingWidth = Control->Parent->ClientWidth;
  5362. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5363. {
  5364. TControl * ChildControl = Control->Parent->Controls[i];
  5365. if (ChildControl->Visible)
  5366. {
  5367. switch (ChildControl->Align)
  5368. {
  5369. case alTop:
  5370. case alBottom:
  5371. RemainingHeight -= ChildControl->Height;
  5372. break;
  5373. case alLeft:
  5374. case alRight:
  5375. RemainingWidth -= ChildControl->Width;
  5376. break;
  5377. }
  5378. }
  5379. }
  5380. int Reserve = ScaleByTextHeight(this, 32);
  5381. // queue in explorer, trees in commander
  5382. if (Control->Height > RemainingHeight - Reserve)
  5383. {
  5384. Control->Height = RemainingHeight / 2;
  5385. }
  5386. if (Control->Width > RemainingWidth - Reserve)
  5387. {
  5388. Control->Width = RemainingWidth / 2;
  5389. }
  5390. }
  5391. Control->Visible = value;
  5392. if (WasFocused && Visible)
  5393. {
  5394. DirView(osCurrent)->SetFocus();
  5395. }
  5396. FixControlsPlacement();
  5397. }
  5398. }
  5399. //---------------------------------------------------------------------------
  5400. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5401. {
  5402. TControl * Control = GetComponent(Component);
  5403. if (Control == NULL)
  5404. {
  5405. return false;
  5406. }
  5407. else
  5408. {
  5409. return Control->Visible;
  5410. }
  5411. }
  5412. //---------------------------------------------------------------------------
  5413. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5414. {
  5415. bool Result;
  5416. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5417. {
  5418. Result = !IsUWP();
  5419. }
  5420. else
  5421. {
  5422. Result = true;
  5423. }
  5424. return Result;
  5425. }
  5426. //---------------------------------------------------------------------------
  5427. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5428. {
  5429. if (DirView->ItemFocused != NULL)
  5430. {
  5431. DirView->ItemFocused->MakeVisible(false);
  5432. }
  5433. }
  5434. //---------------------------------------------------------------------------
  5435. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5436. {
  5437. MakeFocusedItemVisible(RemoteDirView);
  5438. QueueSplitter->Visible = QueuePanel->Visible;
  5439. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5440. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5441. TControl * TopControlsOrder[] =
  5442. { TopDock, MessageDock, SessionsPageControl };
  5443. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5444. TControl * QueueControlsOrder[] =
  5445. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5446. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5447. }
  5448. //---------------------------------------------------------------------------
  5449. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5450. {
  5451. switch (Component) {
  5452. case fcStatusBar: return RemoteStatusBar;
  5453. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5454. case fcQueueView: return QueuePanel;
  5455. case fcQueueToolbar: return QueueDock;
  5456. case fcRemoteTree: return RemoteDrivePanel;
  5457. case fcSessionsTabs: return SessionsPageControl;
  5458. case fcQueueFileList: return QueueFileList;
  5459. default: return NULL;
  5460. }
  5461. }
  5462. //---------------------------------------------------------------------------
  5463. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5464. TObject *Sender, TListColumn *Column, TPoint &Point)
  5465. {
  5466. DebugAssert(NonVisualDataModule && Column && Sender);
  5467. NonVisualDataModule->ListColumn = Column;
  5468. TPopupMenu * DirViewColumnMenu;
  5469. if (Sender == DirView(osOther))
  5470. {
  5471. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5472. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5473. bool SizeColumn = (Column->Index == uvSize);
  5474. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5475. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5476. }
  5477. else
  5478. {
  5479. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5480. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5481. bool SizeColumn = (Column->Index == dvSize);
  5482. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5483. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5484. }
  5485. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5486. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5487. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5488. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5489. }
  5490. //---------------------------------------------------------------------------
  5491. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5492. TObject *Sender, TListItem *Item, bool &AllowExec)
  5493. {
  5494. DoDirViewExecFile(Sender, Item, AllowExec);
  5495. }
  5496. //---------------------------------------------------------------------------
  5497. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5498. TListItem * Item, bool & AllowExec)
  5499. {
  5500. DebugAssert(Sender && Item && Configuration);
  5501. DebugAssert(AllowExec);
  5502. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5503. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5504. bool Remote = !IsSideLocalBrowser(Side);
  5505. DebugAssert(Item == ADirView->ItemFocused);
  5506. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5507. TResolvedDoubleClickAction Action;
  5508. if (FForceExecution)
  5509. {
  5510. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5511. }
  5512. else
  5513. {
  5514. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5515. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5516. }
  5517. if (Action == rdcaCopy)
  5518. {
  5519. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5520. UnlockWindow();
  5521. try
  5522. {
  5523. if (IsLocalBrowserMode())
  5524. {
  5525. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5526. }
  5527. else
  5528. {
  5529. if (HasAvailableTerminal())
  5530. {
  5531. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5532. }
  5533. }
  5534. }
  5535. __finally
  5536. {
  5537. LockWindow();
  5538. }
  5539. AllowExec = false;
  5540. }
  5541. else if (Action == rdcaEdit)
  5542. {
  5543. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5544. {
  5545. ExecuteFile(Side, efDefaultEditor);
  5546. AllowExec = false;
  5547. }
  5548. }
  5549. else if (Action == rdcaOpen)
  5550. {
  5551. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5552. {
  5553. ExecuteFile(osRemote, efShell);
  5554. AllowExec = false;
  5555. }
  5556. }
  5557. }
  5558. //---------------------------------------------------------------------------
  5559. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5560. {
  5561. return ((Side == osRemote) || (Side == osCurrent));
  5562. }
  5563. //---------------------------------------------------------------------------
  5564. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5565. {
  5566. DebugFail();
  5567. }
  5568. //---------------------------------------------------------------------------
  5569. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5570. {
  5571. DebugFail();
  5572. }
  5573. //---------------------------------------------------------------------------
  5574. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5575. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5576. {
  5577. TSynchronizeParamType Params;
  5578. Params.LocalDirectory = LocalDirectory;
  5579. Params.RemoteDirectory = RemoteDirectory;
  5580. int UnusedParams =
  5581. (GUIConfiguration->SynchronizeParams &
  5582. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5583. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5584. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5585. Params.Options = GUIConfiguration->SynchronizeOptions;
  5586. bool SaveSettings = false;
  5587. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5588. &DoSynchronizeTooManyDirectories);
  5589. DebugAssert(FSynchronizeController == NULL);
  5590. FSynchronizeController = &Controller;
  5591. bool Result;
  5592. try
  5593. {
  5594. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5595. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5596. int Options =
  5597. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5598. DebugAssert(FOnFeedSynchronizeError == NULL);
  5599. DebugAssert(FOnSynchronizeAbort == NULL);
  5600. DebugAssert(FSynchronizeTerminal == NULL);
  5601. FSynchronizeTerminal = Terminal;
  5602. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5603. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5604. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5605. if (Result)
  5606. {
  5607. if (SaveSettings)
  5608. {
  5609. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5610. GUIConfiguration->SynchronizeOptions = Params.Options;
  5611. }
  5612. else
  5613. {
  5614. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5615. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5616. FLAGSET(Params.Options, soSynchronize))
  5617. {
  5618. GUIConfiguration->SynchronizeOptions =
  5619. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5620. soSynchronize;
  5621. }
  5622. }
  5623. LocalDirectory = Params.LocalDirectory;
  5624. RemoteDirectory = Params.RemoteDirectory;
  5625. }
  5626. }
  5627. __finally
  5628. {
  5629. FSynchronizeController = NULL;
  5630. DebugAssert(FOnFeedSynchronizeError == NULL);
  5631. FOnFeedSynchronizeError = NULL;
  5632. DebugAssert(FOnSynchronizeAbort == NULL);
  5633. FOnSynchronizeAbort = NULL;
  5634. FSynchronizeTerminal = NULL;
  5635. }
  5636. return Result;
  5637. }
  5638. //---------------------------------------------------------------------------
  5639. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5640. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5641. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5642. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5643. TSynchronizeOptions * Options, bool Full)
  5644. {
  5645. // Keep-up-to-date mode
  5646. if (Terminal->Status == ssOpened)
  5647. {
  5648. try
  5649. {
  5650. int PParams = Params.Params;
  5651. if (!Full)
  5652. {
  5653. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5654. if (FLAGSET(Params.Options, soRecurse))
  5655. {
  5656. PParams |= TTerminal::spSubDirs;
  5657. }
  5658. }
  5659. else
  5660. {
  5661. // if keepuptodate is non-recursive,
  5662. // full sync before has to be non-recursive as well
  5663. if (FLAGCLEAR(Params.Options, soRecurse))
  5664. {
  5665. PParams |= TTerminal::spNoRecurse;
  5666. }
  5667. }
  5668. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5669. PParams, Checklist, Options);
  5670. }
  5671. catch (Exception & E)
  5672. {
  5673. if (!Terminal->Active)
  5674. {
  5675. ShowExtendedExceptionEx(Terminal, &E);
  5676. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5677. if (!Terminal->Active)
  5678. {
  5679. throw;
  5680. }
  5681. }
  5682. else
  5683. {
  5684. if (FLAGSET(Params.Options, soContinueOnError) &&
  5685. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5686. {
  5687. // noop, already logged in MoreMessageDialog
  5688. }
  5689. else
  5690. {
  5691. // We get mostly EAbort here, so this is noop.
  5692. // Exception is an error when listing directories while looking for differences.
  5693. ShowExtendedExceptionEx(Terminal, &E);
  5694. throw;
  5695. }
  5696. }
  5697. }
  5698. }
  5699. }
  5700. //---------------------------------------------------------------------------
  5701. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5702. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5703. const UnicodeString ErrorStr)
  5704. {
  5705. if (!Directory.IsEmpty())
  5706. {
  5707. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5708. }
  5709. else
  5710. {
  5711. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5712. }
  5713. }
  5714. //---------------------------------------------------------------------------
  5715. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5716. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5717. {
  5718. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5719. {
  5720. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5721. }
  5722. else
  5723. {
  5724. TMessageParams Params(mpNeverAskAgainCheck);
  5725. unsigned int Result = MessageDialog(
  5726. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5727. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5728. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5729. {
  5730. MaxDirectories *= 2;
  5731. if (Result == qaNeverAskAgain)
  5732. {
  5733. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5734. }
  5735. }
  5736. else
  5737. {
  5738. Abort();
  5739. }
  5740. }
  5741. }
  5742. //---------------------------------------------------------------------------
  5743. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5744. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5745. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5746. TSynchronizeOptions * Options)
  5747. {
  5748. // Keep-up-to-date mode
  5749. DebugAssert(!FAutoOperation);
  5750. void * BatchStorage;
  5751. BatchStart(BatchStorage);
  5752. FAutoOperation = true;
  5753. bool AnyOperation = false;
  5754. TDateTime StartTime = Now();
  5755. TSynchronizeChecklist * AChecklist = NULL;
  5756. TObjectReleaser<TSynchronizeProgressForm> SynchronizeProgressFormReleaser(
  5757. FSynchronizeProgressForm, new TSynchronizeProgressForm(Application, true, -1, false));
  5758. try
  5759. {
  5760. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5761. {
  5762. FSynchronizeProgressForm->Start();
  5763. }
  5764. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5765. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5766. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5767. Options);
  5768. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5769. SAFE_DESTROY(FSynchronizeProgressForm);
  5770. AnyOperation = (AChecklist->CheckedCount > 0);
  5771. if (AnyOperation)
  5772. {
  5773. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5774. CreateProgressForm(&SynchronizeProgress);
  5775. try
  5776. {
  5777. Terminal->SynchronizeApply(
  5778. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5779. SynchronizeProcessedItem, NULL, NULL, NULL);
  5780. }
  5781. __finally
  5782. {
  5783. DestroyProgressForm();
  5784. }
  5785. }
  5786. }
  5787. __finally
  5788. {
  5789. if (Checklist == NULL)
  5790. {
  5791. delete AChecklist;
  5792. }
  5793. else
  5794. {
  5795. *Checklist = AChecklist;
  5796. }
  5797. FAutoOperation = false;
  5798. SynchronizeProgressFormReleaser.Reset();
  5799. BatchEnd(BatchStorage);
  5800. ReloadLocalDirectory();
  5801. if (AnyOperation)
  5802. {
  5803. OperationComplete(StartTime);
  5804. }
  5805. }
  5806. }
  5807. //---------------------------------------------------------------------------
  5808. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5809. {
  5810. // can be called from command line
  5811. return Visible &&
  5812. ((DirView(osOther)->SelCount > 0) ||
  5813. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5814. }
  5815. //---------------------------------------------------------------------------
  5816. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5817. {
  5818. LogSynchronizeEvent(Terminal, Message);
  5819. }
  5820. //---------------------------------------------------------------------------
  5821. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5822. int Params, TSynchronizeOptions & Options)
  5823. {
  5824. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5825. {
  5826. Options.Filter = new TStringList();
  5827. Options.Filter->CaseSensitive = false;
  5828. Options.Filter->Duplicates = Types::dupAccept;
  5829. if (DirView(osOther)->SelCount > 0)
  5830. {
  5831. DirView(osOther)->CreateFileList(false, false, Options.Filter);
  5832. }
  5833. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5834. {
  5835. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5836. }
  5837. Options.Filter->Sort();
  5838. }
  5839. }
  5840. //---------------------------------------------------------------------------
  5841. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5842. {
  5843. TCopyParamType Defaults;
  5844. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5845. ConfigStorage->AccessMode = smRead;
  5846. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5847. {
  5848. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5849. }
  5850. ConfigStorage.reset(NULL);
  5851. std::unique_ptr<TStringList> Options(new TStringList());
  5852. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5853. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5854. UnicodeString Result;
  5855. if (Options->Count > 0)
  5856. {
  5857. Result =
  5858. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5859. }
  5860. return Result;
  5861. }
  5862. //---------------------------------------------------------------------------
  5863. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5864. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5865. {
  5866. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5867. UnicodeString AdditionalParams =
  5868. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5869. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5870. SerializeCopyParamForCommandLine(CopyParams),
  5871. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5872. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5873. ExecuteNewInstance(SessionName, AdditionalParams);
  5874. }
  5875. //---------------------------------------------------------------------------
  5876. struct TSynchronizeParams
  5877. {
  5878. TSynchronizeMode Mode;
  5879. TSynchronizeChecklist * Checklist;
  5880. int Params;
  5881. TCopyParamType * CopyParam;
  5882. TDateTime CollectElapsed;
  5883. TDateTime * StartTime;
  5884. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5885. };
  5886. //---------------------------------------------------------------------------
  5887. void TCustomScpExplorerForm::SynchronizeApplyLocal(TSynchronizeChecklist * Checklist, TSynchronizeParams & Params)
  5888. {
  5889. DebugAssert(FLAGCLEAR(Params.Params, TTerminal::spTimestamp));
  5890. std::unique_ptr<TSynchronizeChecklistFileOperation> ChecklistFileOperation(
  5891. new TSynchronizeChecklistFileOperation(Checklist, SynchronizeProcessedItem, &Params));
  5892. unsigned int OperationFlags =
  5893. FOF_ALLOWUNDO |
  5894. FOF_NOCONFIRMMKDIR |
  5895. FOFX_RECYCLEONDELETE | // same effect as FOF_ALLOWUNDO?
  5896. FLAGMASK(FLAGSET(Params.Params, TTerminal::spNoConfirmation), FOF_NOCONFIRMATION);
  5897. IFileOperation * FileOperation = ChecklistFileOperation->FileOperation;
  5898. OleCheck(FileOperation->SetOperationFlags(OperationFlags));
  5899. TForm * ActiveForm = Screen->ActiveForm;
  5900. if (ActiveForm == this)
  5901. {
  5902. LockWindow();
  5903. }
  5904. else
  5905. {
  5906. ActiveForm->Enabled = false;
  5907. }
  5908. FileOperation->SetOwnerWindow(ActiveForm->Handle);
  5909. try
  5910. {
  5911. HRESULT Result = FileOperation->PerformOperations();
  5912. AppLogFmt(L"Performed %d", (int(Result)));
  5913. BOOL Aborted;
  5914. OleCheck(FileOperation->GetAnyOperationsAborted(&Aborted));
  5915. if ((Result == HRESULT_FROM_WIN32(ERROR_CANCELLED)) || Aborted)
  5916. {
  5917. AppLog(L"Aborted");
  5918. Abort();
  5919. }
  5920. AppLog(L"Checking");
  5921. OleCheck(Result);
  5922. }
  5923. __finally
  5924. {
  5925. if (ActiveForm == this)
  5926. {
  5927. UnlockWindow();
  5928. }
  5929. else
  5930. {
  5931. ActiveForm->Enabled = true;
  5932. }
  5933. }
  5934. }
  5935. //---------------------------------------------------------------------------
  5936. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5937. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5938. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5939. {
  5940. DebugAssert(!FAutoOperation);
  5941. void * BatchStorage;
  5942. BatchStart(BatchStorage);
  5943. FAutoOperation = true;
  5944. TFileOperationStatistics Statistics;
  5945. TDateTime Start = Now();
  5946. bool LocalLocal = FLAGSET(Params.Params, TTerminal::spLocalLocal);
  5947. try
  5948. {
  5949. Params.OnProcessedItem = OnProcessedItem;
  5950. if (!LocalLocal)
  5951. {
  5952. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5953. CreateProgressForm(&SynchronizeProgress);
  5954. try
  5955. {
  5956. Terminal->SynchronizeApply(
  5957. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5958. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5959. &Statistics);
  5960. }
  5961. __finally
  5962. {
  5963. DestroyProgressForm();
  5964. }
  5965. }
  5966. else
  5967. {
  5968. SynchronizeApplyLocal(Params.Checklist, Params);
  5969. }
  5970. }
  5971. __finally
  5972. {
  5973. Params.OnProcessedItem = NULL;
  5974. FAutoOperation = false;
  5975. BatchEnd(BatchStorage);
  5976. ReloadLocalDirectory();
  5977. }
  5978. if (WinConfiguration->SynchronizeSummary)
  5979. {
  5980. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5981. // The statistics should be 0 anyway in this case
  5982. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp) &&
  5983. !LocalLocal)
  5984. {
  5985. Message += L"\n";
  5986. if (Statistics.FilesUploaded > 0)
  5987. {
  5988. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5989. }
  5990. if (Statistics.FilesDownloaded > 0)
  5991. {
  5992. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5993. }
  5994. if (Statistics.FilesDeletedLocal > 0)
  5995. {
  5996. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5997. }
  5998. if (Statistics.FilesDeletedRemote > 0)
  5999. {
  6000. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  6001. }
  6002. }
  6003. TDateTime Elapsed = (Now() - Start);
  6004. Message +=
  6005. L"\n" +
  6006. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  6007. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  6008. TMessageParams Params(mpNeverAskAgainCheck);
  6009. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  6010. if (Result == qaNeverAskAgain)
  6011. {
  6012. WinConfiguration->SynchronizeSummary = false;
  6013. }
  6014. }
  6015. }
  6016. //---------------------------------------------------------------------------
  6017. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  6018. {
  6019. // There only the external shell's progress form for local-local
  6020. if ((FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  6021. {
  6022. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  6023. }
  6024. // Not set in keep-up-to-date mode - Synchronize() method
  6025. if (Token != NULL)
  6026. {
  6027. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6028. if (Params.OnProcessedItem != NULL)
  6029. {
  6030. Params.OnProcessedItem(NULL, ChecklistItem);
  6031. // in local-local, nothing pumps the message queue, so we have to do it here
  6032. if (FLAGSET(Params.Params, TTerminal::spLocalLocal))
  6033. {
  6034. Application->ProcessMessages();
  6035. }
  6036. }
  6037. }
  6038. }
  6039. //---------------------------------------------------------------------------
  6040. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  6041. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  6042. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  6043. {
  6044. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6045. *Params.StartTime = Now();
  6046. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  6047. }
  6048. //---------------------------------------------------------------------------
  6049. void TCustomScpExplorerForm::DoQueueSynchronize(void * Token)
  6050. {
  6051. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6052. int CopyParams = TTerminal::GetSynchronizeCopyParams(Params.Params);
  6053. TCopyParamType SyncCopyParam = TTerminal::GetSynchronizeCopyParam(Params.CopyParam, Params.Params);
  6054. bool Parallel = GUIConfiguration->CurrentCopyParam.QueueParallel;
  6055. int Index = 0;
  6056. const TSynchronizeChecklist::TItem * ChecklistItem;
  6057. while (Params.Checklist->GetNextChecked(Index, ChecklistItem))
  6058. {
  6059. TQueueItem * QueueItem = Terminal->SynchronizeToQueue(ChecklistItem, &SyncCopyParam, CopyParams, Parallel);
  6060. AddQueueItem(Queue, QueueItem, Terminal);
  6061. }
  6062. }
  6063. //---------------------------------------------------------------------------
  6064. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  6065. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  6066. {
  6067. // terminal can be already closed (e.g. dropped connection)
  6068. if ((ManagedSession != NULL) && (IsLocalBrowserMode() || ManagedSession->Active))
  6069. {
  6070. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6071. ManagedSession->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam, Params.Params);
  6072. }
  6073. }
  6074. //---------------------------------------------------------------------------
  6075. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  6076. TOperationSide Side, TStrings * FileList, const UnicodeString & NewFileName, bool TargetIsDirectory, void * Token)
  6077. {
  6078. TAutoBatch AutoBatch(this);
  6079. TAutoFlag AutoOperationFlag(FAutoOperation);
  6080. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6081. if (!IsSideLocalBrowser(Side))
  6082. {
  6083. UnicodeString Target;
  6084. UnicodeString FileMask;
  6085. if (TargetIsDirectory)
  6086. {
  6087. Target = NewFileName;
  6088. Terminal->CreateTargetDirectory(Target, faDirectory, Params.CopyParam);
  6089. }
  6090. else
  6091. {
  6092. Target = UnixExtractFileDir(NewFileName);
  6093. FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  6094. }
  6095. RemoteDirView->SaveSelection();
  6096. RemoteDirView->SaveSelectedNames();
  6097. try
  6098. {
  6099. Terminal->MoveFiles(FileList, Target, FileMask, false);
  6100. }
  6101. catch(...)
  6102. {
  6103. RemoteDirView->DiscardSavedSelection();
  6104. throw;
  6105. }
  6106. RemoteDirView->RestoreSelection();
  6107. }
  6108. else
  6109. {
  6110. std::unique_ptr<TStrings> Directories(CreateSortedStringList());
  6111. if (TargetIsDirectory)
  6112. {
  6113. if (!ForceDirectories(ApiPath(NewFileName)))
  6114. {
  6115. throw EOSExtException(FMTLOAD(CREATE_DIR_ERROR, (NewFileName)));
  6116. }
  6117. Directories->Add(NewFileName);
  6118. }
  6119. else
  6120. {
  6121. Directories->Add(ExtractFileDir(NewFileName));
  6122. }
  6123. for (int Index = 0; Index < FileList->Count; Index++)
  6124. {
  6125. UnicodeString FileName = FileList->Strings[Index];
  6126. UnicodeString Directory = ExtractFileDir(FileName);
  6127. Directories->Add(Directory);
  6128. UnicodeString NewFilePath = NewFileName;
  6129. if (TargetIsDirectory)
  6130. {
  6131. NewFilePath = TPath::Combine(NewFilePath, ExtractFileName(FileName));
  6132. }
  6133. UnicodeString LogMsg = FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewFilePath));
  6134. if (Terminal != NULL)
  6135. {
  6136. Terminal->LogEvent(LogMsg);
  6137. }
  6138. AppLog(LogMsg);
  6139. if (!MoveFile(ApiPath(FileName).c_str(), ApiPath(NewFilePath).c_str()))
  6140. {
  6141. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFilePath)));
  6142. }
  6143. }
  6144. for (int Index = 0; Index < Directories->Count; Index++)
  6145. {
  6146. ReloadLocalDirectory(Directories->Strings[Index]);
  6147. }
  6148. }
  6149. }
  6150. //---------------------------------------------------------------------------
  6151. void __fastcall TCustomScpExplorerForm::DoSynchronizeExplore(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  6152. {
  6153. UnicodeString Path1 = ExcludeTrailingBackslash(Item->Info1.Directory);
  6154. if ((Side == osLocal) || IsLocalBrowserMode())
  6155. {
  6156. if (((Side == osLocal) && (Action == TSynchronizeChecklist::saDownloadNew)) ||
  6157. ((Side == osRemote) && (Action == TSynchronizeChecklist::saUploadNew)))
  6158. {
  6159. UnicodeString Directory = (Side == osLocal) ? Path1 : ExcludeTrailingBackslash(Item->Info2.Directory);
  6160. OpenFolderInExplorer(Directory);
  6161. }
  6162. else
  6163. {
  6164. UnicodeString Path = (Side == osLocal) ? Item->ForceGetLocalPath() : Item->ForceGetLocalPath2();
  6165. OpenFileInExplorer(Path);
  6166. }
  6167. }
  6168. else if (DebugAlwaysTrue(Side == osRemote))
  6169. {
  6170. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6171. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6172. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Info2.Directory);
  6173. if (!Path1.IsEmpty())
  6174. {
  6175. SessionData->LocalDirectory = Path1;
  6176. }
  6177. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6178. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(EXPLORE_SWITCH), Item->GetFileName())));
  6179. }
  6180. }
  6181. //---------------------------------------------------------------------------
  6182. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6183. TSynchronizeMode Mode, int Params, const UnicodeString & Directory1, const UnicodeString & Directory2,
  6184. const TCopyParamType * CopyParams)
  6185. {
  6186. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6187. UnicodeString AdditionalParams =
  6188. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6189. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6190. SerializeCopyParamForCommandLine(CopyParams),
  6191. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6192. Directory1, Directory2, Mode, Params));
  6193. ExecuteNewInstance(SessionName, AdditionalParams);
  6194. }
  6195. //---------------------------------------------------------------------------
  6196. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6197. UnicodeString & Directory1, UnicodeString & Directory2,
  6198. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6199. {
  6200. int Result;
  6201. bool SaveSettings = false;
  6202. bool LocalLocal = IsLocalBrowserMode();
  6203. int Options =
  6204. FLAGMASK(LocalLocal || !Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6205. FLAGMASK(!LocalLocal && !CanCalculateChecksum(), fsoDisableByChecksum) |
  6206. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly) |
  6207. FLAGMASK(LocalLocal, fsoLocalLocal);
  6208. // For local-local the file mask would still be relevant, and while it's somehat supported by SynchronizeCollect,
  6209. // it is not supported for (externally implemented) recursive transfers when applying folder differences.
  6210. TCopyParamType CopyParam = LocalLocal ? TCopyParamType() : GUIConfiguration->CurrentCopyParam;
  6211. TUsableCopyParamAttrs CopyParamAttrs = LocalLocal ? TUsableCopyParamAttrs() : Terminal->UsableCopyParamAttrs(0);
  6212. bool Continue =
  6213. ((UseDefaults == 0) ||
  6214. DoFullSynchronizeDialog(
  6215. Mode, Params, Directory1, Directory2,
  6216. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6217. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6218. if (Continue)
  6219. {
  6220. Configuration->Usage->Inc(L"Synchronizations");
  6221. if (!LocalLocal)
  6222. {
  6223. CopyParam.IncludeFileMask.SetRoots(Directory1, Directory2);
  6224. UpdateCopyParamCounters(CopyParam);
  6225. }
  6226. TSynchronizeOptions SynchronizeOptions;
  6227. GetSynchronizeOptions(Params, SynchronizeOptions);
  6228. if (SaveSettings)
  6229. {
  6230. GUIConfiguration->SynchronizeParams = Params;
  6231. }
  6232. else
  6233. {
  6234. SaveMode = false;
  6235. }
  6236. Params |= FLAGMASK(LocalLocal, TTerminal::spLocalLocal);
  6237. TDateTime StartTime = Now();
  6238. TSynchronizeChecklist * Checklist = NULL;
  6239. try
  6240. {
  6241. DebugAssert(!FAutoOperation);
  6242. FAutoOperation = true;
  6243. try
  6244. {
  6245. UnicodeString SessionKey = LocalLocal ? EmptyStr : Terminal->SessionData->SessionKey;
  6246. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, Directory2, CopyParam));
  6247. int Files = -1;
  6248. if (DataList->Count >= 1)
  6249. {
  6250. Files = StrToIntDef(DataList->Strings[0], Files);
  6251. }
  6252. else
  6253. {
  6254. DataList->Add(UnicodeString());
  6255. }
  6256. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files, LocalLocal);
  6257. FSynchronizeProgressForm->Start();
  6258. Checklist =
  6259. ManagedSession->SynchronizeCollect(
  6260. Directory1, Directory2,
  6261. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6262. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6263. &SynchronizeOptions);
  6264. if (LocalLocal || Terminal->SessionData->CacheDirectories)
  6265. {
  6266. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6267. Configuration->SaveDirectoryStatisticsCache(SessionKey, Directory2, CopyParam, DataList.get());
  6268. }
  6269. }
  6270. __finally
  6271. {
  6272. FAutoOperation = false;
  6273. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6274. SAFE_DESTROY(FSynchronizeProgressForm);
  6275. }
  6276. TSynchronizeParams SynchronizeParams;
  6277. SynchronizeParams.Mode = Mode;
  6278. SynchronizeParams.CopyParam = &CopyParam;
  6279. SynchronizeParams.Params = Params;
  6280. SynchronizeParams.Checklist = Checklist;
  6281. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6282. SynchronizeParams.StartTime = &StartTime;
  6283. SynchronizeParams.OnProcessedItem = NULL;
  6284. Result = Checklist->Count;
  6285. if (Checklist->Count > 0)
  6286. {
  6287. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6288. {
  6289. bool CanQueue = Visible && FLAGCLEAR(Params, TTerminal::spTimestamp) && !LocalLocal;
  6290. TQueueSynchronizeEvent OnQueueSynchronize = CanQueue ? DoQueueSynchronize : TQueueSynchronizeEvent();
  6291. TCustomCommandMenuEvent OnCustomCommandMenu = !LocalLocal ? CustomCommandMenu : TCustomCommandMenuEvent();
  6292. if (!DoSynchronizeChecklistDialog(
  6293. Checklist, Mode, Params, Directory1, Directory2, OnCustomCommandMenu, DoFullSynchronize,
  6294. OnQueueSynchronize, DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeExplore,
  6295. &SynchronizeParams))
  6296. {
  6297. Result = -1;
  6298. }
  6299. }
  6300. else
  6301. {
  6302. FullSynchronize(SynchronizeParams, NULL, NULL);
  6303. }
  6304. }
  6305. else
  6306. {
  6307. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6308. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6309. }
  6310. }
  6311. __finally
  6312. {
  6313. delete Checklist;
  6314. }
  6315. OperationComplete(StartTime);
  6316. }
  6317. else
  6318. {
  6319. Result = -1;
  6320. }
  6321. return Result;
  6322. }
  6323. //---------------------------------------------------------------------------
  6324. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6325. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6326. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6327. {
  6328. if (Collect)
  6329. {
  6330. DebugAssert(FSynchronizeProgressForm != NULL);
  6331. if (!FSynchronizeProgressForm->Started)
  6332. {
  6333. FSynchronizeProgressForm->Start();
  6334. }
  6335. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6336. SetTaskbarListProgressValue(CompareProgress);
  6337. }
  6338. else
  6339. {
  6340. DebugAssert(FSynchronizeProgressForm == NULL);
  6341. DebugAssert(FProgressForm != NULL);
  6342. }
  6343. }
  6344. //---------------------------------------------------------------------------
  6345. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6346. {
  6347. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6348. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6349. if (File.get() != NULL)
  6350. {
  6351. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6352. Application->ShowMainForm = false;
  6353. Application->Run();
  6354. }
  6355. }
  6356. //---------------------------------------------------------------------------
  6357. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6358. {
  6359. DebugFail();
  6360. }
  6361. //---------------------------------------------------------------------------
  6362. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6363. {
  6364. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6365. SessionData->Assign(ManagedSession->SessionData);
  6366. UpdateSessionData(SessionData.get());
  6367. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6368. if (IsAvailableTerminal(ManagedSession))
  6369. {
  6370. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6371. }
  6372. if (!ManagedSession->SessionData->HasSessionName())
  6373. {
  6374. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6375. // once IsWorkspace is cleared
  6376. SessionData->Name = UnicodeString();
  6377. }
  6378. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6379. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6380. SessionData->IsWorkspace = false;
  6381. return SessionData.release();
  6382. }
  6383. //---------------------------------------------------------------------------
  6384. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6385. {
  6386. TSessionData * SessionData = CloneCurrentSessionData();
  6387. try
  6388. {
  6389. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6390. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6391. }
  6392. __finally
  6393. {
  6394. delete SessionData;
  6395. }
  6396. }
  6397. //---------------------------------------------------------------------------
  6398. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6399. {
  6400. TTerminalManager * Manager = TTerminalManager::Instance();
  6401. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6402. if (DebugAlwaysTrue(ManagedSession != NULL))
  6403. {
  6404. // Update ManagedSession->StateData
  6405. UpdateSession(ManagedSession);
  6406. }
  6407. Manager->SaveWorkspace(DataList.get());
  6408. return DataList.release();
  6409. }
  6410. //---------------------------------------------------------------------------
  6411. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6412. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6413. {
  6414. WinConfiguration->LastWorkspace = Name;
  6415. if (!SavePasswords)
  6416. {
  6417. for (int Index = 0; Index < DataList->Count; Index++)
  6418. {
  6419. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6420. if (SessionData->Link.IsEmpty())
  6421. {
  6422. SessionData->ClearSessionPasswords();
  6423. }
  6424. }
  6425. }
  6426. StoredSessions->NewWorkspace(Name, DataList);
  6427. // modified only
  6428. StoredSessions->Save(false, Explicit);
  6429. }
  6430. //---------------------------------------------------------------------------
  6431. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6432. {
  6433. return
  6434. DefaultStr(WinConfiguration->LastWorkspace,
  6435. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6436. }
  6437. //---------------------------------------------------------------------------
  6438. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6439. {
  6440. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6441. bool AnyNonStoredSessionWithPassword = false;
  6442. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6443. bool AllNonStoredSessionsAnonymous = true;
  6444. TTerminalManager * Manager = TTerminalManager::Instance();
  6445. for (int Index = 0; Index < DataList->Count; Index++)
  6446. {
  6447. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6448. if (SessionData->Link.IsEmpty())
  6449. {
  6450. if (SessionData->HasAnySessionPassword())
  6451. {
  6452. AnyNonStoredSessionWithPassword = true;
  6453. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6454. {
  6455. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6456. }
  6457. }
  6458. if (!SameText(SessionData->UserName, AnonymousUserName))
  6459. {
  6460. AllNonStoredSessionsAnonymous = false;
  6461. }
  6462. }
  6463. }
  6464. bool SavePasswords;
  6465. bool * PSavePasswords;
  6466. bool NotRecommendedSavingPasswords =
  6467. !CustomWinConfiguration->UseMasterPassword &&
  6468. !AllNonStoredSessionsAnonymous;
  6469. if (Configuration->DisablePasswordStoring ||
  6470. !AnyNonStoredSessionWithPassword)
  6471. {
  6472. PSavePasswords = NULL;
  6473. SavePasswords = false;
  6474. }
  6475. else
  6476. {
  6477. PSavePasswords = &SavePasswords;
  6478. SavePasswords =
  6479. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6480. !NotRecommendedSavingPasswords;
  6481. }
  6482. UnicodeString Name = WorkspaceName();
  6483. bool CreateShortcut = false;
  6484. bool Result =
  6485. DoSaveWorkspaceDialog(
  6486. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6487. EnableAutoSave);
  6488. if (Result)
  6489. {
  6490. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6491. if (CreateShortcut)
  6492. {
  6493. TOperationVisualizer Visualizer;
  6494. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6495. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6496. }
  6497. if (EnableAutoSave)
  6498. {
  6499. WinConfiguration->AutoSaveWorkspace = true;
  6500. WinConfiguration->AutoWorkspace = Name;
  6501. if (PSavePasswords != NULL)
  6502. {
  6503. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6504. }
  6505. }
  6506. }
  6507. return Result;
  6508. }
  6509. //---------------------------------------------------------------------------
  6510. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6511. {
  6512. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6513. DebugAssert(Session == ManagedSession);
  6514. if (!IsLocalBrowserMode())
  6515. {
  6516. SAFE_DESTROY(Session->RemoteExplorerState);
  6517. if (WinConfiguration->PreservePanelState)
  6518. {
  6519. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6520. }
  6521. }
  6522. UpdateSessionData(Session->StateData);
  6523. }
  6524. //---------------------------------------------------------------------------
  6525. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6526. {
  6527. // Keep in sync with TSessionData::CopyStateData
  6528. DebugAssert(Data != NULL);
  6529. // This is inconsistent with how color (for example) is handled.
  6530. Data->Name = ManagedSession->SessionData->Name;
  6531. if (!IsLocalBrowserMode())
  6532. {
  6533. // cannot use RemoteDirView->Path, because it is empty if connection
  6534. // was already closed
  6535. // also only peek, we may not be connected at all atm
  6536. // so make sure we do not try retrieving current directory from the server
  6537. // (particularly with FTP)
  6538. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6539. if (!ACurrentDirectory.IsEmpty())
  6540. {
  6541. Data->RemoteDirectory = ACurrentDirectory;
  6542. }
  6543. }
  6544. Data->Color = SessionColor;
  6545. }
  6546. //---------------------------------------------------------------------------
  6547. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6548. {
  6549. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6550. DebugAssert(Toolbar != NULL);
  6551. for (int i = 0; i < Toolbar->Items->Count; i++)
  6552. {
  6553. TTBXCustomDropDownItem * DropDownItem;
  6554. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6555. if (DropDownItem != NULL)
  6556. {
  6557. ToolbarItemResize(DropDownItem,
  6558. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6559. Toolbar->NonClientWidth);
  6560. break;
  6561. }
  6562. }
  6563. }
  6564. //---------------------------------------------------------------------------
  6565. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6566. {
  6567. Item->EditWidth = Width;
  6568. }
  6569. //---------------------------------------------------------------------------
  6570. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6571. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6572. {
  6573. for (int i = 0; i < Toolbar->Items->Count; i++)
  6574. {
  6575. TTBXCustomDropDownItem * DropDownItem;
  6576. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6577. if (DropDownItem != NULL)
  6578. {
  6579. ASize.x -= DropDownItem->EditWidth;
  6580. TControl * Control = this;
  6581. ASize.x += ScaleByTextHeight(Control, 50) /* minimal combo width */;
  6582. }
  6583. }
  6584. }
  6585. //---------------------------------------------------------------------------
  6586. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6587. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6588. {
  6589. if (WinConfiguration->DDWarnLackOfTempSpace)
  6590. {
  6591. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6592. if (!ADrive.IsEmpty())
  6593. {
  6594. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6595. DebugAssert(RequiredSpace >= 0);
  6596. __int64 RequiredWithReserve;
  6597. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6598. if (FreeSpace < RequiredWithReserve)
  6599. {
  6600. unsigned int Result;
  6601. TMessageParams Params(mpNeverAskAgainCheck);
  6602. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6603. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6604. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6605. if (Result == qaNeverAskAgain)
  6606. {
  6607. WinConfiguration->DDWarnLackOfTempSpace = false;
  6608. }
  6609. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6610. }
  6611. }
  6612. }
  6613. }
  6614. //---------------------------------------------------------------------------
  6615. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6616. {
  6617. DoOpenDirectoryDialog(odAddBookmark, Side);
  6618. }
  6619. //---------------------------------------------------------------------------
  6620. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6621. {
  6622. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6623. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6624. try
  6625. {
  6626. TCustomDirView * DView = DirView(Side);
  6627. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6628. {
  6629. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6630. }
  6631. }
  6632. catch (...)
  6633. {
  6634. delete VisitedDirectories;
  6635. throw;
  6636. }
  6637. return VisitedDirectories;
  6638. }
  6639. //---------------------------------------------------------------------------
  6640. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6641. TOpenDirectoryMode Mode, TOperationSide Side)
  6642. {
  6643. bool Continue = true;
  6644. if (Mode == odAddBookmark)
  6645. {
  6646. TMessageParams Params(mpNeverAskAgainCheck);
  6647. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6648. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6649. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6650. unsigned int Answer =
  6651. MessageDialog(Message,
  6652. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6653. if (Answer == qaNeverAskAgain)
  6654. {
  6655. Continue = true;
  6656. WinConfiguration->UseSharedBookmarks = true;
  6657. }
  6658. else if (Answer == qaOK)
  6659. {
  6660. Continue = true;
  6661. WinConfiguration->UseSharedBookmarks = false;
  6662. }
  6663. else
  6664. {
  6665. Continue = false;
  6666. }
  6667. }
  6668. if (Continue)
  6669. {
  6670. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6671. try
  6672. {
  6673. UnicodeString Name = DirView(Side)->PathName;
  6674. bool Repeat;
  6675. do
  6676. {
  6677. Repeat = false;
  6678. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6679. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6680. // do not allow switching to location profiles,
  6681. // if we are not connected
  6682. HasDirView[osLocal] && IsAvailableTerminal(Terminal)))
  6683. {
  6684. TWindowLock Lock(this);
  6685. if (!TryOpenDirectory(Side, Name))
  6686. {
  6687. Repeat = true;
  6688. Mode = odBrowse;
  6689. }
  6690. }
  6691. }
  6692. while (Repeat);
  6693. }
  6694. __finally
  6695. {
  6696. delete VisitedDirectories;
  6697. }
  6698. }
  6699. }
  6700. //---------------------------------------------------------------------------
  6701. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6702. {
  6703. DebugAssert(!Terminal->CommandSessionOpened);
  6704. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6705. }
  6706. //---------------------------------------------------------------------------
  6707. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6708. {
  6709. bool Result = Terminal->IsCapable[Capability] ||
  6710. Terminal->CommandSessionOpened;
  6711. if (!Result)
  6712. {
  6713. // We might get here for example when "checksum" synchronization is requested from command-line
  6714. // on server that supports neither checksum nor shell
  6715. if (!Terminal->IsCapable[fcSecondaryShell])
  6716. {
  6717. NotSupported();
  6718. }
  6719. else if (!GUIConfiguration->ConfirmCommandSession)
  6720. {
  6721. Result = true;
  6722. }
  6723. else
  6724. {
  6725. TMessageParams Params(mpNeverAskAgainCheck);
  6726. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6727. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6728. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6729. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6730. if (Answer == qaNeverAskAgain)
  6731. {
  6732. GUIConfiguration->ConfirmCommandSession = false;
  6733. Result = true;
  6734. }
  6735. else if (Answer == qaOK)
  6736. {
  6737. Result = true;
  6738. }
  6739. }
  6740. if (Result)
  6741. {
  6742. Result = CommandSessionFallback();
  6743. }
  6744. }
  6745. return Result;
  6746. }
  6747. //---------------------------------------------------------------------------
  6748. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6749. {
  6750. if (EnsureCommandSessionFallback(fcAnyCommand))
  6751. {
  6752. DoConsoleDialog(Terminal, Command);
  6753. }
  6754. }
  6755. //---------------------------------------------------------------------------
  6756. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6757. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6758. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6759. {
  6760. if (!IsSideLocalBrowser(osRemote) &&
  6761. IsFileControl(DropSourceControl, osRemote) &&
  6762. (FDDExtMapFile != NULL))
  6763. {
  6764. Accept = true;
  6765. }
  6766. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6767. DebugAssert(FDDTargetControl != NULL);
  6768. }
  6769. //---------------------------------------------------------------------------
  6770. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6771. _di_IDataObject DataObj, int KeyState,
  6772. const TPoint & Point, int & Effect, bool & Accept)
  6773. {
  6774. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6775. }
  6776. //---------------------------------------------------------------------------
  6777. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6778. _di_IDataObject DataObj, int KeyState,
  6779. const TPoint & Point, int & Effect, bool & Accept)
  6780. {
  6781. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6782. }
  6783. //---------------------------------------------------------------------------
  6784. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6785. TObject * Sender)
  6786. {
  6787. DebugUsedParam(Sender);
  6788. DebugAssert(FDDTargetControl == Sender);
  6789. FDDTargetControl = NULL;
  6790. }
  6791. //---------------------------------------------------------------------------
  6792. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave(int)
  6793. {
  6794. FileControlDDDragLeave(SessionsPageControl);
  6795. }
  6796. //---------------------------------------------------------------------------
  6797. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave(int)
  6798. {
  6799. FileControlDDDragLeave(QueueView3);
  6800. }
  6801. //---------------------------------------------------------------------------
  6802. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6803. {
  6804. DebugAssert(!IsSideLocalBrowser(Side));
  6805. DebugUsedParam(Side);
  6806. bool Edit = false;
  6807. TRemoteFile * File = NULL;
  6808. UnicodeString FileName;
  6809. UnicodeString PointTo;
  6810. bool SymbolicLink = true;
  6811. if (RemoteDirView->ItemFocused)
  6812. {
  6813. DebugAssert(RemoteDirView->ItemFocused->Data);
  6814. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6815. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6816. if (Edit)
  6817. {
  6818. FileName = File->FileName;
  6819. PointTo = File->LinkTo;
  6820. }
  6821. else if (!File->IsParentDirectory)
  6822. {
  6823. PointTo = File->FileName;
  6824. }
  6825. }
  6826. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6827. Terminal->IsCapable[fcHardLink]))
  6828. {
  6829. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6830. if (Edit)
  6831. {
  6832. DebugAssert(File->FileName == FileName);
  6833. int Params = dfNoRecursive;
  6834. Terminal->ExceptionOnFail = true;
  6835. try
  6836. {
  6837. Terminal->DeleteFile(L"", File, &Params);
  6838. }
  6839. __finally
  6840. {
  6841. Terminal->ExceptionOnFail = false;
  6842. }
  6843. }
  6844. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6845. }
  6846. }
  6847. //---------------------------------------------------------------------------
  6848. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6849. {
  6850. return
  6851. (IsSideLocalBrowser(Side) ||
  6852. (HasAvailableTerminal() &&
  6853. Terminal->ResolvingSymlinks &&
  6854. Terminal->IsCapable[fcSymbolicLink]));
  6855. }
  6856. //---------------------------------------------------------------------------
  6857. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6858. {
  6859. return
  6860. !IsSideLocalBrowser(FCurrentSide) &&
  6861. (RemoteDirView->ItemFocused != NULL) &&
  6862. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6863. Terminal->SessionData->ResolveSymlinks;
  6864. }
  6865. //---------------------------------------------------------------------------
  6866. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6867. {
  6868. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6869. FForceExecution = true;
  6870. try
  6871. {
  6872. DirView(osCurrent)->ExecuteCurrentFile();
  6873. }
  6874. __finally
  6875. {
  6876. FForceExecution = false;
  6877. }
  6878. }
  6879. //---------------------------------------------------------------------------
  6880. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6881. {
  6882. TEditorData ExternalEditor;
  6883. ExternalEditor.Editor = edExternal;
  6884. bool Remember = false;
  6885. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6886. {
  6887. if (Remember)
  6888. {
  6889. TEditorList * EditorList = new TEditorList;
  6890. try
  6891. {
  6892. *EditorList = *WinConfiguration->EditorList;
  6893. bool Found = false;
  6894. int i = 0;
  6895. while (!Found && (i < EditorList->Count))
  6896. {
  6897. const TEditorPreferences * Editor = EditorList->Editors[i];
  6898. if ((Editor->Data->Editor == edExternal) &&
  6899. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6900. {
  6901. Found = true;
  6902. }
  6903. i++;
  6904. }
  6905. if (!Found)
  6906. {
  6907. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6908. WinConfiguration->EditorList = EditorList;
  6909. }
  6910. }
  6911. __finally
  6912. {
  6913. delete EditorList;
  6914. }
  6915. }
  6916. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6917. }
  6918. }
  6919. //---------------------------------------------------------------------------
  6920. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6921. {
  6922. if (FFileFindTerminal == ATerminal)
  6923. {
  6924. FFileFindTerminal = NULL;
  6925. HideFileFindDialog();
  6926. }
  6927. if (FClipboardTerminal == ATerminal)
  6928. {
  6929. ClipboardClear(); // implies ClipboardStop
  6930. }
  6931. if ((FOnSynchronizeAbort != NULL) &&
  6932. (ATerminal == FManagedSession))
  6933. {
  6934. FOnSynchronizeAbort(NULL);
  6935. }
  6936. }
  6937. //---------------------------------------------------------------------------
  6938. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6939. {
  6940. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6941. DetachTerminal(Sender);
  6942. }
  6943. //---------------------------------------------------------------------------
  6944. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6945. const UnicodeString DebugUsedArg(FileName), TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6946. {
  6947. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6948. if (Data->Terminal == Terminal)
  6949. {
  6950. Data->Terminal = ATerminal;
  6951. }
  6952. }
  6953. //---------------------------------------------------------------------------
  6954. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6955. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6956. {
  6957. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6958. DebugUsedParam(FileName);
  6959. DebugAssert(Terminal != NULL);
  6960. if (Data->Terminal == Terminal)
  6961. {
  6962. Data->Terminal = NULL;
  6963. }
  6964. }
  6965. //---------------------------------------------------------------------------
  6966. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6967. {
  6968. return NULL;
  6969. }
  6970. //---------------------------------------------------------------------------
  6971. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6972. {
  6973. UpdateControls();
  6974. SessionColor = TColor(0);
  6975. UpdateRemotePathComboBox(false);
  6976. NeedSession(false);
  6977. }
  6978. //---------------------------------------------------------------------------
  6979. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6980. {
  6981. try
  6982. {
  6983. // Cache, as the login dialog can change its value.
  6984. // See also DoShow. Also see TTerminalManager::NewSession.
  6985. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6986. try
  6987. {
  6988. if (ShowLogin)
  6989. {
  6990. bool ReloadSessions = !Startup;
  6991. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6992. }
  6993. }
  6994. __finally
  6995. {
  6996. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6997. // (so there was no chance for the user to open any session yet)
  6998. if ((ShowLogin || !Startup) &&
  6999. !WinConfiguration->KeepOpenWhenNoSession &&
  7000. // this rules out the implicit Commander's local-local browser
  7001. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  7002. {
  7003. TerminateApplication();
  7004. }
  7005. }
  7006. }
  7007. catch (EAbort &)
  7008. {
  7009. // swallow
  7010. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  7011. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  7012. }
  7013. }
  7014. //---------------------------------------------------------------------------
  7015. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  7016. {
  7017. TTerminalManager * Manager = TTerminalManager::Instance();
  7018. DebugAssert(!Manager->Updating);
  7019. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  7020. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  7021. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  7022. SessionsPageControl->LockDrawing();
  7023. try
  7024. {
  7025. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  7026. while (SessionsPageControl->PageCount > Manager->Count + 1)
  7027. {
  7028. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  7029. }
  7030. for (int Index = 0; Index <= Manager->Count; Index++)
  7031. {
  7032. TThemeTabSheet * TabSheet;
  7033. if (Index >= SessionsPageControl->PageCount)
  7034. {
  7035. TabSheet = new TThemeTabSheet(SessionsPageControl);
  7036. TabSheet->PageControl = SessionsPageControl;
  7037. }
  7038. else
  7039. {
  7040. TabSheet = SessionsPageControl->Pages[Index];
  7041. }
  7042. bool IsSessionTab = (Index < Manager->Count);
  7043. if (IsSessionTab)
  7044. {
  7045. TTerminal * Terminal = Manager->Sessions[Index];
  7046. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  7047. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  7048. UpdateSessionTab(TabSheet);
  7049. }
  7050. else
  7051. {
  7052. TabSheet->Tag = 0; // not really needed
  7053. TabSheet->Shadowed = false;
  7054. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  7055. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  7056. // 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)
  7057. UpdateNewTabTab();
  7058. }
  7059. }
  7060. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  7061. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  7062. {
  7063. SessionsPageControl->UpdateTabsCaptionTruncation();
  7064. }
  7065. }
  7066. __finally
  7067. {
  7068. SessionsPageControl->UnlockDrawing();
  7069. }
  7070. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  7071. }
  7072. //---------------------------------------------------------------------------
  7073. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  7074. {
  7075. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  7076. }
  7077. //---------------------------------------------------------------------------
  7078. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  7079. {
  7080. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  7081. }
  7082. //---------------------------------------------------------------------------
  7083. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  7084. {
  7085. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  7086. }
  7087. //---------------------------------------------------------------------------
  7088. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  7089. {
  7090. TThemeTabSheet * TabSheet = GetNewTabTab();
  7091. UnicodeString TabCaption;
  7092. if (WinConfiguration->SelectiveToolbarText)
  7093. {
  7094. TabCaption = GetNewTabTabCaption();
  7095. }
  7096. TabSheet->BaseCaption = TabCaption;
  7097. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  7098. }
  7099. //---------------------------------------------------------------------------
  7100. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  7101. {
  7102. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  7103. }
  7104. //---------------------------------------------------------------------------
  7105. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  7106. {
  7107. DebugFail();
  7108. return UnicodeString();
  7109. }
  7110. //---------------------------------------------------------------------------
  7111. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  7112. {
  7113. if (DebugAlwaysTrue(TabSheet != NULL))
  7114. {
  7115. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  7116. if (DebugAlwaysTrue(ASession != NULL))
  7117. {
  7118. TColor Color = (ASession == Terminal) ? FSessionColor : static_cast<TColor>(ASession->StateData->Color);
  7119. if (ASession->LocalBrowser)
  7120. {
  7121. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  7122. }
  7123. else
  7124. {
  7125. TabSheet->ImageIndex = AddSessionColor(Color);
  7126. }
  7127. TTerminalManager * Manager = TTerminalManager::Instance();
  7128. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  7129. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  7130. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  7131. }
  7132. }
  7133. }
  7134. //---------------------------------------------------------------------------
  7135. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  7136. {
  7137. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  7138. }
  7139. //---------------------------------------------------------------------------
  7140. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  7141. {
  7142. DebugAssert(SessionsPageControl->ActivePage != NULL);
  7143. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  7144. bool Result = (Session != NULL);
  7145. if (Result)
  7146. {
  7147. TTerminalManager::Instance()->ActiveSession = Session;
  7148. }
  7149. else
  7150. {
  7151. try
  7152. {
  7153. NewTab();
  7154. }
  7155. __finally
  7156. {
  7157. SessionListChanged();
  7158. }
  7159. FSessionsPageControlNewTabTime = Now();
  7160. }
  7161. return Result;
  7162. }
  7163. //---------------------------------------------------------------------------
  7164. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  7165. {
  7166. TWindowLock Lock(this);
  7167. SessionTabSwitched();
  7168. }
  7169. //---------------------------------------------------------------------------
  7170. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  7171. {
  7172. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  7173. DebugAssert(TransferList != NULL);
  7174. UnicodeString Name;
  7175. if (TransferList->ItemIndex <= 0)
  7176. {
  7177. Name = L"";
  7178. }
  7179. else
  7180. {
  7181. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7182. }
  7183. if (FCopyParamAutoSelected.IsEmpty())
  7184. {
  7185. // if previous preset was not autoselected, make new preset the "default"
  7186. FCopyParamDefault = Name;
  7187. }
  7188. GUIConfiguration->CopyParamCurrent = Name;
  7189. }
  7190. //---------------------------------------------------------------------------
  7191. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7192. {
  7193. // sanity check
  7194. bool ExistingPreset =
  7195. (FTransferListHoverIndex >= 0) &&
  7196. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7197. DebugAssert(ExistingPreset);
  7198. if (ExistingPreset)
  7199. {
  7200. HDC DC = GetDC(0);
  7201. TCanvas * Canvas = new TCanvas();
  7202. try
  7203. {
  7204. Canvas->Handle = DC;
  7205. Canvas->Font = GetToolbarFont(this);
  7206. UnicodeString Name;
  7207. if (FTransferListHoverIndex == 0)
  7208. {
  7209. Name = L"";
  7210. }
  7211. else
  7212. {
  7213. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7214. }
  7215. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7216. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7217. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7218. static_cast<TObject*>(GetComponent(fcTransferList)));
  7219. UnicodeString InfoStr =
  7220. GUIConfiguration->CopyParamPreset[Name].
  7221. GetInfoStr(L"; ",
  7222. FLAGMASK(HasAvailableTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7223. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7224. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7225. {
  7226. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7227. {
  7228. InfoStr.SetLength(InfoStr.Length() - 1);
  7229. }
  7230. InfoStr += Ellipsis;
  7231. }
  7232. // UpdateCaption does not cause invalidation of whole submenu, while
  7233. // setting Caption property does.
  7234. // also it probably does not resize the label, even if necessary
  7235. // (we do not want that anyway)
  7236. TransferLabel->UpdateCaption(InfoStr);
  7237. }
  7238. __finally
  7239. {
  7240. Canvas->Handle = NULL;
  7241. ReleaseDC(0, DC);
  7242. delete Canvas;
  7243. }
  7244. }
  7245. }
  7246. //---------------------------------------------------------------------------
  7247. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7248. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7249. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7250. {
  7251. if (FTransferListHoverIndex != AHoverIndex)
  7252. {
  7253. FTransferListHoverIndex = AHoverIndex;
  7254. UpdateTransferLabel();
  7255. }
  7256. }
  7257. //---------------------------------------------------------------------------
  7258. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7259. {
  7260. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7261. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7262. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7263. {
  7264. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7265. {
  7266. if (!NonVisualDataModule->Busy)
  7267. {
  7268. OpenDirectory(GetSide(osCurrent));
  7269. }
  7270. Message.Result = 1;
  7271. }
  7272. else
  7273. {
  7274. TForm::Dispatch(&Message);
  7275. }
  7276. }
  7277. else
  7278. {
  7279. TForm::Dispatch(&Message);
  7280. }
  7281. }
  7282. //---------------------------------------------------------------------------
  7283. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7284. {
  7285. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7286. if ((FIgnoreNextDialogChar != 0) &&
  7287. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7288. {
  7289. Message.Result = 1;
  7290. }
  7291. else
  7292. {
  7293. TForm::Dispatch(&Message);
  7294. }
  7295. FIgnoreNextDialogChar = 0;
  7296. }
  7297. //---------------------------------------------------------------------------
  7298. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7299. {
  7300. // The four low-order bits are used internally by Windows
  7301. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7302. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7303. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7304. // 61730 - restore thru double click - undocumented
  7305. // 61490 - maximize thru double click - undocumented
  7306. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7307. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7308. {
  7309. SysResizing(Cmd);
  7310. }
  7311. TForm::Dispatch(&Message);
  7312. }
  7313. //---------------------------------------------------------------------------
  7314. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7315. {
  7316. AppLog(L"Windows session end query");
  7317. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7318. // Also there no point returning TRUE as we are not able to
  7319. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7320. // Hence the process termination might be safer :)
  7321. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7322. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7323. {
  7324. Message.Result = FALSE;
  7325. }
  7326. else
  7327. {
  7328. Message.Result = TRUE;
  7329. }
  7330. // Do not call default handling as that triggers OnCloseQuery,
  7331. // where our implementation will popup confirmation dialogs, what we do not want,
  7332. // as per Vista guidelines:
  7333. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7334. }
  7335. //---------------------------------------------------------------------------
  7336. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7337. {
  7338. AppLog(L"Windows session end");
  7339. if (Message.EndSession && IsApplicationMinimized())
  7340. {
  7341. // WORKAROUND
  7342. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7343. // when it receives WM_ENDSESSION,
  7344. // but that sometimes (particularly when application is minimized) cause crashes.
  7345. // Crash popups message that blocks log off.
  7346. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7347. // so we call ExitProcess() immediately, not even trying to cleanup.
  7348. // It still causes beep, so there's likely some popup, but it does not block
  7349. // log off.
  7350. ExitProcess(0);
  7351. }
  7352. TForm::Dispatch(&Message);
  7353. }
  7354. //---------------------------------------------------------------------------
  7355. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7356. {
  7357. }
  7358. //---------------------------------------------------------------------------
  7359. void __fastcall TCustomScpExplorerForm::DoShow()
  7360. {
  7361. // Called from TCustomScpExplorerForm::CMShowingChanged
  7362. // only now are the controls resized finally, so the size constraints
  7363. // will not conflict with possibly very small window size
  7364. RestoreFormParams();
  7365. // This indicates that the form was rescaled after parameters were loaded and
  7366. // as most probably the parameters were actually saved with the current form scaling
  7367. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7368. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7369. // and no rounding problems will occur.
  7370. // See also RestoreForm.
  7371. // (we should be safe to call RestoreParams unconditionally)
  7372. if (PixelsPerInch != Screen->PixelsPerInch)
  7373. {
  7374. RestoreParams();
  7375. }
  7376. FixControlsPlacement();
  7377. if (Position == poDefaultPosOnly)
  7378. {
  7379. CutFormToDesktop(this);
  7380. }
  7381. TForm::DoShow();
  7382. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7383. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7384. // This was previously in NeedSession, where other related code is.
  7385. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7386. // unpleasantly shows briefly.
  7387. if ((ManagedSession == NULL) &&
  7388. !WinConfiguration->ShowLoginWhenNoSession &&
  7389. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7390. // This detects if workspace was saved the last time the main widow was closed
  7391. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7392. {
  7393. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7394. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7395. }
  7396. // Before main window displays
  7397. if (ManagedSession == NULL)
  7398. {
  7399. StartingWithoutSession();
  7400. }
  7401. UpdatePixelsPerInchMainWindowCounter();
  7402. FShowing = true;
  7403. }
  7404. //---------------------------------------------------------------------------
  7405. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7406. {
  7407. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7408. }
  7409. //---------------------------------------------------------------------------
  7410. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7411. {
  7412. SessionListChanged();
  7413. InitStatusBar();
  7414. UpdateControls();
  7415. }
  7416. //---------------------------------------------------------------------------
  7417. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7418. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7419. TNotifyEvent OnBalloonClick, TObject * UserData)
  7420. {
  7421. bool Do;
  7422. UnicodeString Message;
  7423. if (E == NULL)
  7424. {
  7425. Message = Str;
  7426. Do = true;
  7427. }
  7428. else
  7429. {
  7430. Do = ExceptionMessage(E, Message);
  7431. }
  7432. if (Do && WinConfiguration->BalloonNotifications)
  7433. {
  7434. UnicodeString Title;
  7435. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7436. {
  7437. Message = TrimLeft(Message);
  7438. }
  7439. else
  7440. {
  7441. Message = UnformatMessage(Message);
  7442. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7443. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7444. Title = LoadResourceString(Captions[Type]);
  7445. if (Terminal != NULL)
  7446. {
  7447. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7448. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7449. }
  7450. }
  7451. if (Seconds == 0)
  7452. {
  7453. Seconds = WinConfiguration->NotificationsTimeout;
  7454. }
  7455. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7456. }
  7457. }
  7458. //---------------------------------------------------------------------------
  7459. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7460. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7461. UnicodeString HelpKeyword, const TMessageParams * Params,
  7462. TTerminal * Terminal)
  7463. {
  7464. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7465. (FOnFeedSynchronizeError != NULL)) &&
  7466. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7467. {
  7468. if (FOnFeedSynchronizeError != NULL)
  7469. {
  7470. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7471. }
  7472. else
  7473. {
  7474. DebugAssert(FErrorList != NULL);
  7475. TStringList * MoreMessagesCopy = NULL;
  7476. if (MoreMessages)
  7477. {
  7478. MoreMessagesCopy = new TStringList();
  7479. MoreMessagesCopy->Assign(MoreMessages);
  7480. }
  7481. FErrorList->AddObject(Message, MoreMessagesCopy);
  7482. }
  7483. PopupTrayBalloon(Terminal, Message, Type);
  7484. return ContinueAnswer(Answers);
  7485. }
  7486. else
  7487. {
  7488. bool UseBalloon = FTrayIcon->Visible;
  7489. if (UseBalloon)
  7490. {
  7491. PopupTrayBalloon(Terminal, Message, Type);
  7492. }
  7493. unsigned int Result;
  7494. try
  7495. {
  7496. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7497. }
  7498. __finally
  7499. {
  7500. // cancel only balloon we popped up, otherwise we may cancel notification
  7501. // balloon that was there before the message dialog
  7502. // (such as "dd confirmation opt in balloon)
  7503. if (UseBalloon)
  7504. {
  7505. FTrayIcon->CancelBalloon();
  7506. }
  7507. }
  7508. return Result;
  7509. }
  7510. }
  7511. //---------------------------------------------------------------------------
  7512. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7513. TTerminal * Terminal, Exception * E)
  7514. {
  7515. if (FTrayIcon->Visible)
  7516. {
  7517. PopupTrayBalloon(Terminal, L"", qtError, E);
  7518. }
  7519. // particularly prevent opening new session from jump list,
  7520. // while exception is shown
  7521. NonVisualDataModule->StartBusy();
  7522. try
  7523. {
  7524. ShowExtendedExceptionEx(Terminal, E);
  7525. }
  7526. __finally
  7527. {
  7528. NonVisualDataModule->EndBusy();
  7529. FTrayIcon->CancelBalloon();
  7530. }
  7531. }
  7532. //---------------------------------------------------------------------------
  7533. void __fastcall TCustomScpExplorerForm::SessionReady()
  7534. {
  7535. InitStatusBar();
  7536. // cannot rely on active page being page for active terminal,
  7537. // as it can happen that active page is the "new session" page
  7538. // (e.g. when reconnecting active terminal, while login dialog
  7539. // invoked from "new session" page is modal)
  7540. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7541. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7542. }
  7543. //---------------------------------------------------------------------------
  7544. void TCustomScpExplorerForm::InactiveTerminalNotify(
  7545. TManagedTerminal * Terminal, const UnicodeString & Message, TQueryType Type, Exception * E)
  7546. {
  7547. Notify(Terminal, Message, Type, false, NULL, NULL, E);
  7548. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7549. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7550. {
  7551. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7552. }
  7553. }
  7554. //---------------------------------------------------------------------------
  7555. void TCustomScpExplorerForm::Notify(
  7556. TManagedTerminal * Terminal, const UnicodeString & AMessage, TQueryType Type,
  7557. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7558. {
  7559. UnicodeString Message = AMessage;
  7560. if ((E == NULL) ||
  7561. ExceptionMessage(E, Message))
  7562. {
  7563. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7564. if (Important)
  7565. {
  7566. Seconds *= 5;
  7567. }
  7568. UnicodeString NoteMessage(UnformatMessage(Message));
  7569. if (Terminal != NULL)
  7570. {
  7571. NoteMessage = TTerminalManager::Instance()->FormatTerminalNoteMessage(Terminal, NoteMessage);
  7572. }
  7573. if (WinConfiguration->BalloonNotifications)
  7574. {
  7575. AddNote(NoteMessage);
  7576. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7577. }
  7578. else
  7579. {
  7580. FlashOnBackground();
  7581. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7582. }
  7583. }
  7584. }
  7585. //---------------------------------------------------------------------------
  7586. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7587. {
  7588. RestoreApp();
  7589. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7590. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7591. !NonVisualDataModule->Busy)
  7592. {
  7593. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7594. TTerminalManager::Instance()->ActiveSession = Terminal;
  7595. if (!ComponentVisible[fcQueueView])
  7596. {
  7597. ToggleQueueVisibility();
  7598. GoToQueue();
  7599. }
  7600. }
  7601. }
  7602. //---------------------------------------------------------------------------
  7603. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7604. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7605. {
  7606. UnicodeString Message;
  7607. TNotifyEvent OnClick = NULL;
  7608. TObject * UserData = NULL;
  7609. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7610. switch (Event)
  7611. {
  7612. case qeEmptyButMonitored:
  7613. if ((ATerminal != Terminal) || QueueInvisible)
  7614. {
  7615. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7616. OnClick = QueueEmptyNoteClicked;
  7617. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7618. TerminalNoteData->Terminal = ATerminal;
  7619. UserData = TerminalNoteData;
  7620. }
  7621. break;
  7622. case qeEmpty:
  7623. OperationComplete(ATerminal->QueueOperationStart);
  7624. break;
  7625. case qePendingUserAction:
  7626. if ((ATerminal != Terminal) ||
  7627. (QueueInvisible && !IsQueueAutoPopup()))
  7628. {
  7629. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7630. }
  7631. break;
  7632. default:
  7633. DebugFail();
  7634. }
  7635. if (!Message.IsEmpty())
  7636. {
  7637. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7638. }
  7639. }
  7640. //---------------------------------------------------------------------------
  7641. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7642. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7643. {
  7644. if (FDDExtMapFile != NULL)
  7645. {
  7646. CloseHandle(FDDExtMapFile);
  7647. FDDExtMapFile = NULL;
  7648. }
  7649. if (WinConfiguration->DDFakeFile)
  7650. {
  7651. DDFakeFileInitDrag(FileList, Created);
  7652. }
  7653. }
  7654. //---------------------------------------------------------------------------
  7655. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7656. {
  7657. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7658. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7659. {
  7660. FFakeFileDropTarget = FileName;
  7661. }
  7662. }
  7663. //---------------------------------------------------------------------------
  7664. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7665. {
  7666. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7667. if (!ForceDirectories(ApiPath(Result)))
  7668. {
  7669. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7670. }
  7671. FileSetAttr(ApiPath(Result), faHidden);
  7672. return Result;
  7673. }
  7674. //---------------------------------------------------------------------------
  7675. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7676. bool & Created)
  7677. {
  7678. FFakeFileDropTarget = UnicodeString();
  7679. FDragFakeDirectory = CreateFakeTransferDirectory();
  7680. FileList->AddItem(NULL, FDragFakeDirectory);
  7681. Created = true;
  7682. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7683. {
  7684. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7685. }
  7686. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7687. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7688. {
  7689. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7690. TDragExtCommStruct* CommStruct;
  7691. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7692. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7693. DebugAssert(CommStruct != NULL);
  7694. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7695. CommStruct->Dragging = true;
  7696. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7697. LENOF(CommStruct->DropDest));
  7698. NULL_TERMINATE(CommStruct->DropDest);
  7699. UnmapViewOfFile(CommStruct);
  7700. }
  7701. }
  7702. //---------------------------------------------------------------------------
  7703. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7704. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7705. {
  7706. bool Result;
  7707. DebugAssert(!IsLocalBrowserMode());
  7708. if (Sender == RemoteDirView)
  7709. {
  7710. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7711. }
  7712. else
  7713. {
  7714. DebugAssert(Sender == RemoteDriveView);
  7715. TStrings * FileList = RemoteDriveView->DragFileList();
  7716. try
  7717. {
  7718. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7719. }
  7720. __finally
  7721. {
  7722. delete FileList;
  7723. }
  7724. }
  7725. if (FDDTargetControl == RemoteDriveView)
  7726. {
  7727. RemoteDriveView->UpdateDropTarget();
  7728. }
  7729. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7730. // or from tree view to dir view.
  7731. // foMove happens when file/dir is dragged from remote tree view outside of
  7732. // application via dragex
  7733. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7734. (DropSourceControl == RemoteDriveView))
  7735. {
  7736. RemoteDriveView->UpdateDropSource();
  7737. }
  7738. return Result;
  7739. }
  7740. //---------------------------------------------------------------------------
  7741. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7742. {
  7743. DebugAssert(!IsLocalBrowserMode());
  7744. // This also handles drops of remote files to queue.
  7745. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7746. SAFE_DESTROY(FDDFileList);
  7747. if (!FFakeFileDropTarget.IsEmpty())
  7748. {
  7749. RemoveDir(ApiPath(FFakeFileDropTarget));
  7750. }
  7751. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7752. {
  7753. try
  7754. {
  7755. TDragResult DDResult = (Sender == RemoteDirView) ?
  7756. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7757. // Focus is moved to the target application,
  7758. // but as we are going to present the UI, we need to steal the focus back.
  7759. // This most likely won't work though (windows does not allow application
  7760. // to steal focus most of the time)
  7761. Application->BringToFront();
  7762. // On older version of Windows we never got drMove here, see also comment below.
  7763. // On Windows 10, we get the "move".
  7764. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7765. {
  7766. UnicodeString TargetDirectory;
  7767. TFileOperation Operation;
  7768. // drInvalid may mean drMove, see comment below
  7769. switch (DDResult)
  7770. {
  7771. case drCopy:
  7772. Operation = foCopy;
  7773. break;
  7774. case drMove:
  7775. Operation = foMove;
  7776. break;
  7777. default:
  7778. DebugFail();
  7779. case drInvalid:
  7780. // prefer "copy" for safety
  7781. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7782. break;
  7783. }
  7784. TTransferOperationParam Param;
  7785. UnicodeString CounterName;
  7786. bool ForceQueue;
  7787. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7788. {
  7789. // we get drInvalid both if d&d was intercepted by ddext,
  7790. // and when users drops on no-drop location.
  7791. // we tell the difference by existence of response from ddext,
  7792. // so we ignore absence of response in this case
  7793. if (DDResult != drInvalid)
  7794. {
  7795. // here we know that the extension is installed,
  7796. // as it is checked as soon as drag&drop starts from
  7797. // RemoteFileControlDDCreateDragFileList
  7798. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7799. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7800. {
  7801. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7802. }
  7803. else
  7804. {
  7805. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7806. }
  7807. }
  7808. }
  7809. else
  7810. {
  7811. // download using fake file
  7812. Param.Temp = false;
  7813. Param.DragDrop = true;
  7814. if (ForceQueue)
  7815. {
  7816. Param.Queue = asOn;
  7817. }
  7818. if (Sender == RemoteDirView)
  7819. {
  7820. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7821. }
  7822. if (RemoteFileControlFileOperation(Sender, Operation,
  7823. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7824. {
  7825. Configuration->Usage->Inc(CounterName);
  7826. }
  7827. }
  7828. }
  7829. }
  7830. __finally
  7831. {
  7832. CloseHandle(FDDExtMapFile);
  7833. FDDExtMapFile = NULL;
  7834. delete FDragFakeMonitors;
  7835. FDragFakeMonitors = NULL;
  7836. RemoveDir(ApiPath(FDragFakeDirectory));
  7837. FDragFakeDirectory = L"";
  7838. FFakeFileDropTarget = UnicodeString();
  7839. }
  7840. }
  7841. if (FDragDropSshTerminate.get() != NULL)
  7842. {
  7843. FDragDropSshTerminate->Rethrow();
  7844. }
  7845. }
  7846. //---------------------------------------------------------------------------
  7847. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7848. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7849. {
  7850. // Remember drop effect so we know (when user drops files), if we copy or move
  7851. FLastDropEffect = dwEffect;
  7852. }
  7853. //---------------------------------------------------------------------------
  7854. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7855. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7856. {
  7857. bool Result;
  7858. if (FDDTargetControl == QueueView3)
  7859. {
  7860. Directory = DefaultDownloadTargetDirectory();
  7861. Result = true;
  7862. CounterName = L"DownloadsDragDropQueue";
  7863. ForceQueue = true;
  7864. }
  7865. else if (!FFakeFileDropTarget.IsEmpty())
  7866. {
  7867. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7868. Result = true;
  7869. ForceQueue = false;
  7870. CounterName = L"DownloadsDragDropFakeFile";
  7871. }
  7872. else
  7873. {
  7874. ForceQueue = false;
  7875. Enabled = false;
  7876. try
  7877. {
  7878. int Timer = 0;
  7879. Result = false;
  7880. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7881. {
  7882. {
  7883. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7884. TDragExtCommStruct* CommStruct;
  7885. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7886. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7887. DebugAssert(CommStruct != NULL);
  7888. Result = !CommStruct->Dragging;
  7889. if (Result)
  7890. {
  7891. Directory = ExtractFilePath(CommStruct->DropDest);
  7892. CounterName = L"DownloadsDragDropExternalExt";
  7893. }
  7894. UnmapViewOfFile(CommStruct);
  7895. }
  7896. if (!Result)
  7897. {
  7898. Sleep(50);
  7899. Timer += 50;
  7900. Application->ProcessMessages();
  7901. }
  7902. }
  7903. }
  7904. __finally
  7905. {
  7906. Enabled = true;
  7907. }
  7908. }
  7909. return Result;
  7910. }
  7911. //---------------------------------------------------------------------------
  7912. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7913. const UnicodeString TempDir, int SecDelay)
  7914. {
  7915. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7916. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7917. if (FDelayedDeletionTimer == NULL)
  7918. {
  7919. DebugAssert(HandleAllocated());
  7920. FDelayedDeletionTimer = new TTimer(this);
  7921. FDelayedDeletionTimer->Interval = 10000;
  7922. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7923. }
  7924. else
  7925. {
  7926. FDelayedDeletionTimer->Enabled = true;
  7927. }
  7928. }
  7929. //---------------------------------------------------------------------------
  7930. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7931. {
  7932. DebugAssert(FDelayedDeletionList != NULL);
  7933. TDateTime N = Now();
  7934. TDateTime Alert;
  7935. UnicodeString Directory;
  7936. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7937. {
  7938. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7939. if ((N >= Alert) || (Sender == NULL))
  7940. {
  7941. Directory = FDelayedDeletionList->Strings[Index];
  7942. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7943. {
  7944. FDelayedDeletionList->Delete(Index);
  7945. }
  7946. }
  7947. }
  7948. if (FDelayedDeletionList->Count == 0)
  7949. {
  7950. FDelayedDeletionTimer->Enabled = false;
  7951. }
  7952. }
  7953. //---------------------------------------------------------------------------
  7954. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7955. {
  7956. DebugAssert(!IsLocalBrowserMode());
  7957. if (IsFileControl(FDDTargetControl, osRemote) ||
  7958. (FDDTargetControl == SessionsPageControl))
  7959. {
  7960. TManagedTerminal * TargetTerminal = NULL;
  7961. TFileOperation Operation = foNone;
  7962. if (FDDTargetControl == SessionsPageControl)
  7963. {
  7964. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7965. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7966. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7967. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7968. if (IsAvailableTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7969. {
  7970. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7971. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7972. {
  7973. Operation = foRemoteMove;
  7974. }
  7975. else
  7976. {
  7977. Operation = foRemoteCopy;
  7978. }
  7979. }
  7980. }
  7981. else
  7982. {
  7983. if (FLastDropEffect == DROPEFFECT_MOVE)
  7984. {
  7985. Operation = foRemoteMove;
  7986. }
  7987. else if (FLastDropEffect == DROPEFFECT_COPY)
  7988. {
  7989. Operation = foRemoteCopy;
  7990. }
  7991. }
  7992. if (Operation != foNone)
  7993. {
  7994. RemoteFileControlFileOperation(DropSourceControl,
  7995. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7996. }
  7997. // abort drag&drop
  7998. Abort();
  7999. }
  8000. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  8001. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  8002. (FDDTargetControl != QueueView3))
  8003. {
  8004. DebugAssert(!FDragTempDir.IsEmpty());
  8005. TTransferType Type;
  8006. UnicodeString TempDir = FDragTempDir;
  8007. // We clear FDragTempDir before calling
  8008. // just in case it fail (raises exception)
  8009. FDragTempDir = L"";
  8010. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  8011. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  8012. // empty directory parameter means temp directory -> don't display it!
  8013. UnicodeString TargetDir = L"";
  8014. int Options = 0;
  8015. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  8016. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  8017. {
  8018. Abort();
  8019. }
  8020. // TargetDir is set when dropped on local file control
  8021. // (this was workaround for legacy dirview event handling, now it should be
  8022. // made prettier)
  8023. if (TargetDir.IsEmpty())
  8024. {
  8025. TargetDir = TempDir;
  8026. if (ForceDirectories(ApiPath(TargetDir)))
  8027. {
  8028. DebugAssert(Terminal && !TargetDir.IsEmpty());
  8029. FPendingTempSpaceWarn = true;
  8030. try
  8031. {
  8032. FDragDropOperation = true;
  8033. int Params = cpTemporary |
  8034. (Type == ttMove ? cpDelete : 0);
  8035. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  8036. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  8037. }
  8038. __finally
  8039. {
  8040. FDragDropOperation = false;
  8041. FPendingTempSpaceWarn = false;
  8042. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  8043. }
  8044. }
  8045. else
  8046. {
  8047. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  8048. }
  8049. }
  8050. }
  8051. }
  8052. //---------------------------------------------------------------------------
  8053. void __fastcall TCustomScpExplorerForm::DDDownload(
  8054. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  8055. {
  8056. DebugAssert(!IsLocalBrowserMode());
  8057. TAutoBatch AutoBatch(this);
  8058. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  8059. UpdateCopyParamCounters(*CopyParam);
  8060. FMoveToQueue = false;
  8061. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  8062. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  8063. {
  8064. RemoteDriveView->UpdateDropSource();
  8065. }
  8066. }
  8067. //---------------------------------------------------------------------------
  8068. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  8069. {
  8070. public:
  8071. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  8072. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  8073. {
  8074. }
  8075. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  8076. {
  8077. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  8078. TDataObjectFilesEx::AllowData(FormatEtc);
  8079. }
  8080. };
  8081. //---------------------------------------------------------------------------
  8082. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  8083. TObject * Sender, TDataObject *& DataObject)
  8084. {
  8085. if (FDDExtMapFile != NULL)
  8086. {
  8087. TFileList * FileList = DragDropFiles(Sender)->FileList;
  8088. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  8089. {
  8090. Abort();
  8091. }
  8092. if (FileList->Count > 0)
  8093. {
  8094. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  8095. if (!FilesObject->IsValid(true, true))
  8096. {
  8097. FilesObject->_Release();
  8098. }
  8099. else
  8100. {
  8101. DataObject = FilesObject;
  8102. }
  8103. }
  8104. }
  8105. }
  8106. //---------------------------------------------------------------------------
  8107. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  8108. {
  8109. DebugFail();
  8110. }
  8111. //---------------------------------------------------------------------------
  8112. void __fastcall TCustomScpExplorerForm::GoToTree()
  8113. {
  8114. ComponentVisible[fcRemoteTree] = true;
  8115. DriveView(osRemote)->SetFocus();
  8116. }
  8117. //---------------------------------------------------------------------------
  8118. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  8119. TPanelExport Export)
  8120. {
  8121. TCustomDirView * DirView = this->DirView(Side);
  8122. std::unique_ptr<TStrings> ExportData(new TStringList());
  8123. switch (Export)
  8124. {
  8125. case pePath:
  8126. ExportData->Add(DirView->PathName);
  8127. break;
  8128. case peFileList:
  8129. case peFullFileList:
  8130. {
  8131. bool FullPath = (Export == peFullFileList);
  8132. DirView->CreateFileList(false, FullPath, ExportData.get());
  8133. for (int Index = 0; Index < ExportData->Count; Index++)
  8134. {
  8135. if (ExportData->Strings[Index].Pos(L" ") > 0)
  8136. {
  8137. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  8138. }
  8139. }
  8140. }
  8141. break;
  8142. default:
  8143. DebugFail();
  8144. }
  8145. return ExportData.release();
  8146. }
  8147. //---------------------------------------------------------------------------
  8148. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  8149. TPanelExport Export, TPanelExportDestination Destination)
  8150. {
  8151. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  8152. PanelExportStore(Side, Export, Destination, ExportData.get());
  8153. }
  8154. //---------------------------------------------------------------------------
  8155. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  8156. TPanelExport /*Export*/, TPanelExportDestination Destination,
  8157. TStrings * ExportData)
  8158. {
  8159. if (Destination == pedClipboard)
  8160. {
  8161. TInstantOperationVisualizer Visualizer;
  8162. CopyToClipboard(ExportData);
  8163. }
  8164. else
  8165. {
  8166. DebugFail();
  8167. }
  8168. }
  8169. //---------------------------------------------------------------------------
  8170. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8171. {
  8172. TCustomDirView * DirView = this->DirView(Side);
  8173. UnicodeString Mask = DirView->Mask;
  8174. if (DoFilterMaskDialog(DirView, Mask))
  8175. {
  8176. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8177. Configuration->Usage->Inc(L"Filters");
  8178. }
  8179. }
  8180. //---------------------------------------------------------------------------
  8181. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8182. {
  8183. return FQueueController->DefaultOperation();
  8184. }
  8185. //---------------------------------------------------------------------------
  8186. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8187. TQueueOperation Operation, unsigned long * Param)
  8188. {
  8189. switch (Operation)
  8190. {
  8191. case qoPreferences:
  8192. return true;
  8193. case qoGoTo:
  8194. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8195. case qoOnceEmpty:
  8196. return IsAnythingQueued();
  8197. default:
  8198. return FQueueController->AllowOperation(Operation, Param);
  8199. }
  8200. }
  8201. //---------------------------------------------------------------------------
  8202. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8203. {
  8204. if (DebugAlwaysTrue(QueueView3->Visible))
  8205. {
  8206. QueueView3->SetFocus();
  8207. }
  8208. }
  8209. //---------------------------------------------------------------------------
  8210. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8211. TQueueOperation Operation, unsigned long Param)
  8212. {
  8213. if (Operation == qoGoTo)
  8214. {
  8215. GoToQueue();
  8216. }
  8217. else if (Operation == qoPreferences)
  8218. {
  8219. PreferencesDialog(pmQueue);
  8220. }
  8221. else
  8222. {
  8223. FQueueController->ExecuteOperation(Operation, Param);
  8224. }
  8225. }
  8226. //---------------------------------------------------------------------------
  8227. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8228. {
  8229. return (Queue != NULL) && Queue->Enabled;
  8230. }
  8231. //---------------------------------------------------------------------------
  8232. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8233. {
  8234. DebugAssert(Queue != NULL);
  8235. if (Queue != NULL)
  8236. {
  8237. Queue->Enabled = !Queue->Enabled;
  8238. }
  8239. }
  8240. //---------------------------------------------------------------------------
  8241. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8242. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8243. {
  8244. FQueueActedItem = QueueView3->ItemFocused;
  8245. }
  8246. //---------------------------------------------------------------------------
  8247. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8248. {
  8249. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8250. }
  8251. //---------------------------------------------------------------------------
  8252. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8253. {
  8254. return
  8255. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8256. (QueueDock->Visible ? QueueDock->Height : 0) +
  8257. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8258. }
  8259. //---------------------------------------------------------------------------
  8260. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8261. {
  8262. return ScaleByTextHeight(this, 48);
  8263. }
  8264. //---------------------------------------------------------------------------
  8265. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8266. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8267. {
  8268. // when queue is hidden by double-clicking splitter, stray attempt to
  8269. // resize the panel with strange value arrives, make sure it is ignored
  8270. if (ComponentVisible[fcQueueView])
  8271. {
  8272. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8273. if (NewSize > MaxHeightLimit)
  8274. {
  8275. NewSize = MaxHeightLimit;
  8276. }
  8277. int MinHeightLimit =
  8278. GetStaticQueuePanelComponentsHeight() +
  8279. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8280. GetMinQueueViewHeight();
  8281. if (NewSize < MinHeightLimit)
  8282. {
  8283. NewSize = MinHeightLimit;
  8284. }
  8285. }
  8286. else
  8287. {
  8288. Accept = false;
  8289. }
  8290. }
  8291. //---------------------------------------------------------------------------
  8292. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8293. {
  8294. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8295. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8296. if (QueueViewHeight < GetMinQueueViewHeight())
  8297. {
  8298. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8299. }
  8300. }
  8301. //---------------------------------------------------------------------------
  8302. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8303. TDragObject *& /*DragObject*/)
  8304. {
  8305. FQueueActedItem = QueueView3->ItemFocused;
  8306. FQueueScrollOnDragOver->StartDrag();
  8307. }
  8308. //---------------------------------------------------------------------------
  8309. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8310. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8311. {
  8312. FQueueScrollOnDragOver->EndDrag();
  8313. }
  8314. //---------------------------------------------------------------------------
  8315. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8316. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8317. {
  8318. Accept = true;
  8319. if (Source == QueueView3)
  8320. {
  8321. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8322. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8323. if (Accept)
  8324. {
  8325. TQueueItemProxy * QueueItem;
  8326. TQueueItemProxy * DestQueueItem;
  8327. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8328. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8329. Accept = (QueueItem != DestQueueItem) &&
  8330. (QueueItem->Status == TQueueItem::qsPending) &&
  8331. (DestQueueItem->Status == TQueueItem::qsPending);
  8332. }
  8333. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8334. }
  8335. }
  8336. //---------------------------------------------------------------------------
  8337. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8338. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8339. {
  8340. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8341. {
  8342. TQueueItemProxy * QueueItem;
  8343. TQueueItemProxy * DestQueueItem;
  8344. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8345. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8346. QueueItem->Move(DestQueueItem);
  8347. }
  8348. }
  8349. //---------------------------------------------------------------------------
  8350. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8351. {
  8352. if ((QueueView3->ItemFocused == NULL) &&
  8353. (QueueView3->Items->Count > 0))
  8354. {
  8355. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8356. }
  8357. QueueLabelUpdateStatus();
  8358. }
  8359. //---------------------------------------------------------------------------
  8360. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8361. {
  8362. QueueLabelUpdateStatus();
  8363. }
  8364. //---------------------------------------------------------------------------
  8365. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8366. {
  8367. QueueLabel->UpdateStatus();
  8368. }
  8369. //---------------------------------------------------------------------------
  8370. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8371. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8372. {
  8373. if (Selected)
  8374. {
  8375. NonVisualDataModule->UpdateNonVisibleActions();
  8376. }
  8377. }
  8378. //---------------------------------------------------------------------------
  8379. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8380. {
  8381. TDragDropFilesEx * Result = NULL;
  8382. if (Sender == SessionsPageControl)
  8383. {
  8384. Result = FSessionsDragDropFilesEx;
  8385. }
  8386. else if (Sender == QueueView3)
  8387. {
  8388. Result = FQueueDragDropFilesEx;
  8389. }
  8390. else
  8391. {
  8392. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8393. if (DirView != NULL)
  8394. {
  8395. Result = DirView->DragDropFilesEx;
  8396. }
  8397. else
  8398. {
  8399. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8400. if (DriveView != NULL)
  8401. {
  8402. Result = DriveView->DragDropFilesEx;
  8403. }
  8404. }
  8405. }
  8406. DebugAssert(Result != NULL);
  8407. return Result;
  8408. }
  8409. //---------------------------------------------------------------------------
  8410. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8411. {
  8412. return (DView->SelCount == DView->FilesCount);
  8413. }
  8414. //---------------------------------------------------------------------------
  8415. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8416. {
  8417. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8418. }
  8419. //---------------------------------------------------------------------------
  8420. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8421. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8422. {
  8423. DebugAssert(!IsLocalBrowserMode());
  8424. TFileOperation Operation;
  8425. switch (Effect)
  8426. {
  8427. case DROPEFFECT_MOVE:
  8428. Operation = foMove;
  8429. break;
  8430. case DROPEFFECT_COPY:
  8431. // occures on WinXP (reported by user)
  8432. default:
  8433. Operation = foCopy;
  8434. break;
  8435. };
  8436. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8437. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8438. if (DragDropFilesEx->FileList->Count > 0)
  8439. {
  8440. TStrings * FileList = new TStringList();
  8441. try
  8442. {
  8443. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8444. {
  8445. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8446. }
  8447. FDragDropOperation = true;
  8448. TTransferOperationParam Param;
  8449. Param.TargetDirectory = TargetPath;
  8450. // upload, no temp dirs
  8451. Param.Temp = false;
  8452. Param.DragDrop = DragDrop;
  8453. Param.Options =
  8454. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8455. if (ForceQueue)
  8456. {
  8457. Param.Queue = asOn;
  8458. }
  8459. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8460. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8461. {
  8462. if (IsFileControl(DropSourceControl, osLocal))
  8463. {
  8464. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8465. }
  8466. else
  8467. {
  8468. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8469. }
  8470. }
  8471. }
  8472. __finally
  8473. {
  8474. FDragDropOperation = false;
  8475. delete FileList;
  8476. }
  8477. }
  8478. }
  8479. //---------------------------------------------------------------------------
  8480. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8481. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8482. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8483. {
  8484. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8485. }
  8486. //---------------------------------------------------------------------------
  8487. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8488. TObject * Sender, int grfKeyState, int & dwEffect)
  8489. {
  8490. DebugAssert(!IsLocalBrowserMode());
  8491. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8492. if ((dwEffect != DROPEFFECT_NONE) &&
  8493. IsFileControl(DropSourceControl, osRemote))
  8494. {
  8495. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8496. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8497. (RemoteDirView->DropTarget == NULL))
  8498. {
  8499. dwEffect = DROPEFFECT_NONE;
  8500. }
  8501. else
  8502. {
  8503. if (dwEffect == DROPEFFECT_COPY)
  8504. {
  8505. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8506. // currently we support copying always (at least via temporary directory);
  8507. // remove associated checks once this all proves stable and working
  8508. bool CopyCapable = true;
  8509. // if we do not support neither of operations, there's no discussion
  8510. if (!MoveCapable && !CopyCapable)
  8511. {
  8512. dwEffect = DROPEFFECT_NONE;
  8513. }
  8514. else
  8515. {
  8516. // The default effect inside remote panel is move,
  8517. // unless we do not support it, but support copy
  8518. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8519. {
  8520. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8521. }
  8522. else
  8523. {
  8524. // with ctrl-down, we want copy unless it is not supported
  8525. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8526. }
  8527. }
  8528. }
  8529. }
  8530. }
  8531. }
  8532. //---------------------------------------------------------------------------
  8533. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8534. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8535. {
  8536. DebugAssert(!IsLocalBrowserMode());
  8537. if (FDDTotalSize >= 0)
  8538. {
  8539. if (File->IsDirectory)
  8540. {
  8541. FDDTotalSize = -1;
  8542. }
  8543. else
  8544. {
  8545. FDDTotalSize += File->Size;
  8546. }
  8547. }
  8548. DebugAssert(!FDragTempDir.IsEmpty());
  8549. // TODO: this is quite ineffective
  8550. // TODO: what if invalid character replacement is disabled?
  8551. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8552. UnicodeString TransferFileName;
  8553. if (Sender == RemoteDriveView)
  8554. {
  8555. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8556. }
  8557. else
  8558. {
  8559. TransferFileName = File->FileName;
  8560. }
  8561. FDDFileList->AddObject(TransferFileName, File);
  8562. }
  8563. //---------------------------------------------------------------------------
  8564. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8565. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8566. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8567. {
  8568. // sometimes we do not get DDEnd so the list is not released
  8569. SAFE_DESTROY(FDDFileList);
  8570. FDDFileList = new TStringList();
  8571. FDragTempDir = WinConfiguration->TemporaryDir();
  8572. FDDTotalSize = 0;
  8573. FDragDropSshTerminate.reset(NULL);
  8574. }
  8575. //---------------------------------------------------------------------------
  8576. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8577. TObject * /*Sender*/, LongBool /*FEscapePressed*/, int /*grfKeyState*/,
  8578. HRESULT & Result)
  8579. {
  8580. if (Result == DRAGDROP_S_DROP)
  8581. {
  8582. try
  8583. {
  8584. GlobalDragImageList->HideDragImage();
  8585. try
  8586. {
  8587. RemoteFileControlDDTargetDrop();
  8588. }
  8589. catch(ESshTerminate & E)
  8590. {
  8591. FDragDropSshTerminate.reset(E.Clone());
  8592. }
  8593. }
  8594. catch (Exception &E)
  8595. {
  8596. // If downloading fails we need to cancel drag&drop, otherwise
  8597. // Explorer shows error
  8598. // But by the way exception probably never reach this point as
  8599. // it's catched on way.
  8600. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8601. Result = DRAGDROP_S_CANCEL;
  8602. ShowExtendedException(Terminal, &E);
  8603. }
  8604. }
  8605. }
  8606. //---------------------------------------------------------------------------
  8607. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8608. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8609. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8610. {
  8611. TFileMasks::TParams MaskParams;
  8612. MaskParams.Size = Size;
  8613. MaskParams.Modification = Modification;
  8614. // this does not re-parse the mask if it is the same as the last time
  8615. FDirViewMatchMask = Masks;
  8616. bool ImplicitMatch;
  8617. Matches =
  8618. // Local and RecurseInclude parameters have no effect as there's no path.
  8619. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8620. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8621. (AllowImplicitMatches || !ImplicitMatch);
  8622. }
  8623. //---------------------------------------------------------------------------
  8624. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8625. TObject * Sender, TListItem * Item, WORD & Indexes)
  8626. {
  8627. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8628. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8629. {
  8630. Indexes |= oiPartial;
  8631. }
  8632. }
  8633. //---------------------------------------------------------------------------
  8634. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8635. {
  8636. return
  8637. DirViewEnabled(osCurrent) &&
  8638. DirView(osCurrent)->CanPasteFromClipBoard();
  8639. }
  8640. //---------------------------------------------------------------------------
  8641. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8642. {
  8643. bool Result = false;
  8644. if (CanPasteToDirViewFromClipBoard())
  8645. {
  8646. Result = true;
  8647. }
  8648. else
  8649. {
  8650. UnicodeString ClipboardText;
  8651. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8652. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8653. {
  8654. if (StoredSessions->IsUrl(ClipboardText))
  8655. {
  8656. Result = true;
  8657. }
  8658. else
  8659. {
  8660. Result = DirViewEnabled(osCurrent);
  8661. }
  8662. }
  8663. }
  8664. return Result;
  8665. }
  8666. //---------------------------------------------------------------------------
  8667. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8668. {
  8669. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8670. if (DoesClipboardContainOurFiles())
  8671. {
  8672. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8673. {
  8674. DebugAssert(!IsLocalBrowserMode());
  8675. TTerminalManager * Manager = TTerminalManager::Instance();
  8676. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8677. Manager->ActiveSession = FClipboardTerminal;
  8678. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8679. }
  8680. }
  8681. else if (CanPasteToDirViewFromClipBoard())
  8682. {
  8683. DirView(osCurrent)->PasteFromClipBoard();
  8684. }
  8685. else
  8686. {
  8687. UnicodeString ClipboardText;
  8688. if (NonEmptyTextFromClipboard(ClipboardText))
  8689. {
  8690. if (StoredSessions->IsUrl(ClipboardText))
  8691. {
  8692. NewSession(ClipboardText);
  8693. }
  8694. else
  8695. {
  8696. DirView(osCurrent)->Path = ClipboardText;
  8697. }
  8698. }
  8699. }
  8700. }
  8701. //---------------------------------------------------------------------------
  8702. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8703. {
  8704. // TBD
  8705. }
  8706. //---------------------------------------------------------------------------
  8707. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8708. {
  8709. TCustomDirView * ADirView = DirView(Side);
  8710. ADirView->SelectAll(Mode);
  8711. ADirView->SetFocus();
  8712. }
  8713. //---------------------------------------------------------------------------
  8714. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8715. {
  8716. TCustomDirView * ADirView = DirView(Side);
  8717. TFileFilter Filter;
  8718. DefaultFileFilter(Filter);
  8719. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8720. {
  8721. Configuration->Usage->Inc(L"MaskSelections");
  8722. ADirView->SelectFiles(Filter, Select);
  8723. ADirView->SetFocus();
  8724. }
  8725. }
  8726. //---------------------------------------------------------------------------
  8727. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8728. {
  8729. TCustomDirView * ADirView = DirView(Side);
  8730. ADirView->RestoreSelectedNames();
  8731. ADirView->SetFocus();
  8732. }
  8733. //---------------------------------------------------------------------------
  8734. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8735. {
  8736. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8737. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8738. {
  8739. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8740. UnicodeString Ext;
  8741. if (!IsSideLocalBrowser(osCurrent))
  8742. {
  8743. Ext = UnixExtractFileExt(FileName);
  8744. }
  8745. else
  8746. {
  8747. Ext = ExtractFileExt(FileName);
  8748. }
  8749. if (Ext.IsEmpty())
  8750. {
  8751. Ext = L".";
  8752. }
  8753. TFileFilter Filter;
  8754. Filter.Masks = FORMAT(L"*%s", (Ext));
  8755. Filter.Directories = false;
  8756. CurrentDirView->SelectFiles(Filter, Select);
  8757. }
  8758. }
  8759. //---------------------------------------------------------------------------
  8760. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8761. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8762. {
  8763. UnicodeString Result;
  8764. if (FIncrementalSearchState.Searching && (Side == GetSide(osCurrent)))
  8765. {
  8766. Result = FormatIncrementalSearchStatus(FIncrementalSearchState);
  8767. }
  8768. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8769. {
  8770. // noop
  8771. }
  8772. else
  8773. {
  8774. Result =
  8775. FMTLOAD(FILE_INFO_FORMAT,
  8776. (FormatBytes(FileInfo.SelectedSize),
  8777. FormatBytes(FileInfo.FilesSize),
  8778. FormatNumber(FileInfo.SelectedCount),
  8779. FormatNumber(FileInfo.FilesCount)));
  8780. }
  8781. return Result;
  8782. }
  8783. //---------------------------------------------------------------------------
  8784. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8785. TTBXStatusPanel * Panel, TOperationSide Side)
  8786. {
  8787. if (Panel->Index == 1)
  8788. {
  8789. ToggleShowHiddenFiles();
  8790. }
  8791. else if (Panel->Index == 2)
  8792. {
  8793. Filter(Side);
  8794. }
  8795. }
  8796. //---------------------------------------------------------------------------
  8797. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8798. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8799. {
  8800. DebugAssert(!StatusBar->SimplePanel);
  8801. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8802. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8803. }
  8804. //---------------------------------------------------------------------------
  8805. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8806. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8807. {
  8808. DebugAssert(StatusBar->Panels->Count >= 3);
  8809. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8810. if (FileInfo.HiddenCount > 0)
  8811. {
  8812. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8813. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8814. }
  8815. else
  8816. {
  8817. HiddenFilesPanel->ViewPriority = 0;
  8818. // not really necessary, just to cleanup no-longer-valid data
  8819. HiddenFilesPanel->Caption = L"";
  8820. }
  8821. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8822. if (FileInfo.FilteredCount > 0)
  8823. {
  8824. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8825. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8826. }
  8827. else
  8828. {
  8829. FilteredFilesPanel->ViewPriority = 0;
  8830. // not really necessary, just to cleanup no-longer-valid data
  8831. FilteredFilesPanel->Caption = L"";
  8832. }
  8833. }
  8834. //---------------------------------------------------------------------------
  8835. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8836. TObject * /*Sender*/)
  8837. {
  8838. if (DirView(osOther)->Enabled)
  8839. {
  8840. DirView(osOther)->SetFocus();
  8841. }
  8842. }
  8843. //---------------------------------------------------------------------------
  8844. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8845. {
  8846. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8847. switch (Config.Show)
  8848. {
  8849. case qvShow:
  8850. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8851. {
  8852. Config.Show = qvHide;
  8853. }
  8854. else
  8855. {
  8856. Config.Show = Config.LastHideShow;
  8857. }
  8858. break;
  8859. case qvHideWhenEmpty:
  8860. if (ComponentVisible[fcQueueView])
  8861. {
  8862. Config.Show = qvHide;
  8863. }
  8864. else
  8865. {
  8866. Config.LastHideShow = Config.Show;
  8867. Config.Show = qvShow;
  8868. }
  8869. break;
  8870. case qvHide:
  8871. Config.LastHideShow = Config.Show;
  8872. Config.Show = qvShow;
  8873. break;
  8874. }
  8875. WinConfiguration->QueueView = Config;
  8876. }
  8877. //---------------------------------------------------------------------------
  8878. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8879. {
  8880. UnicodeString Result;
  8881. if (Terminal != NULL)
  8882. {
  8883. switch (WinConfiguration->PathInCaption)
  8884. {
  8885. case picShort:
  8886. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8887. break;
  8888. case picFull:
  8889. Result = Terminal->CurrentDirectory;
  8890. break;
  8891. }
  8892. }
  8893. return Result;
  8894. }
  8895. //---------------------------------------------------------------------------
  8896. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8897. {
  8898. TColor Result = GetWindowColor(FSessionColor);
  8899. return Result;
  8900. }
  8901. //---------------------------------------------------------------------------
  8902. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8903. {
  8904. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8905. return Result;
  8906. }
  8907. //---------------------------------------------------------------------------
  8908. void TCustomScpExplorerForm::UpdatePanelControls(TCustomDirView * ADirView, TCustomDriveView * ADriveView)
  8909. {
  8910. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8911. ADirView->DarkMode = UseDarkTheme;
  8912. ADriveView->DarkMode = UseDarkTheme;
  8913. }
  8914. //---------------------------------------------------------------------------
  8915. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8916. {
  8917. if (!FSessionChanging)
  8918. {
  8919. TTerminalManager::Instance()->UpdateAppTitle();
  8920. }
  8921. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8922. // background to gray on Windows 7 (works on Windows 10).
  8923. // See also EnableControl
  8924. if (Showing)
  8925. {
  8926. if (ManagedSession != NULL)
  8927. {
  8928. // Update path when it changes
  8929. if ((SessionsPageControl->ActivePage != NULL) &&
  8930. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8931. {
  8932. UpdateSessionTab(SessionsPageControl->ActivePage);
  8933. }
  8934. }
  8935. NonVisualDataModule->ReconnectSessionAction->Update();
  8936. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8937. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8938. CenterReconnectToolbar();
  8939. // The only place, where we use IsOpenedTerminal and not IsAvailableTerminal
  8940. // (i.e. not checking for reconnecting status)
  8941. // Otherwise it causes flicker [particularly in dark mode] during the short time
  8942. // between the authentication window is closed and FOpeningTerminal is cleared.
  8943. // Should be solved smarter.
  8944. bool HasTerminal = TTerminalManager::Instance()->IsOpenedTerminal(Terminal);
  8945. RemoteDirView->Enabled = HasTerminal;
  8946. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8947. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8948. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8949. RemoteDriveView->Color = RemoteDirView->Color;
  8950. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8951. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8952. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8953. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8954. QueueFileList->Enabled = QueueView3->Enabled;
  8955. QueueFileList->Color = QueueView3->Color;
  8956. QueueFileList->Font->Color = QueueView3->Font->Color;
  8957. QueueLabelUpdateStatus();
  8958. UpdatePanelControls(RemoteDirView, RemoteDriveView);
  8959. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8960. if (FImmersiveDarkMode != UseDarkTheme)
  8961. {
  8962. UpdateDarkMode();
  8963. }
  8964. SessionsPageControl->TabTheme = UseDarkTheme ? CurrentTheme : NULL;
  8965. QueueView3->DarkMode = UseDarkTheme;
  8966. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8967. bool HiContrast = WinConfiguration->HiContrast;
  8968. UnicodeString NewHiContrastThemeName = HiContrast ? GetThemeName(!UseDarkTheme) : EmptyStr;
  8969. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8970. {
  8971. ReleaseHiContrastTheme();
  8972. if (!NewHiContrastThemeName.IsEmpty())
  8973. {
  8974. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8975. }
  8976. }
  8977. SessionsPageControl->ActiveTabTheme = HiContrast ? DebugNotNull(FHiContrastTheme) : NULL;
  8978. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8979. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8980. }
  8981. }
  8982. //---------------------------------------------------------------------------
  8983. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8984. {
  8985. UpdateControls();
  8986. }
  8987. //---------------------------------------------------------------------------
  8988. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8989. TObject * Sender)
  8990. {
  8991. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8992. DebugAssert(DirView != NULL);
  8993. DoDirViewLoaded(DirView);
  8994. TransferPresetAutoSelect();
  8995. TUnixDirView * UnixDirView = dynamic_cast<TUnixDirView *>(DirView);
  8996. if (UnixDirView != NULL)
  8997. {
  8998. TManagedTerminal * ATerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(UnixDirView->Terminal));
  8999. TTerminalManager::Instance()->TerminalLoadedDirectory(ATerminal);
  9000. }
  9001. }
  9002. //---------------------------------------------------------------------------
  9003. void __fastcall TCustomScpExplorerForm::StartUpdates()
  9004. {
  9005. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  9006. // first run after installation
  9007. if (double(Updates.LastCheck) == 0)
  9008. {
  9009. AppLog(L"First run, scheduling updates check for the next run");
  9010. // make sure next time there will be an update (if enabled)
  9011. Updates.LastCheck = TDateTime(1);
  9012. WinConfiguration->Updates = Updates;
  9013. }
  9014. else
  9015. {
  9016. TDateTime Period;
  9017. if (IsUWP() && !IsOfficialPackage())
  9018. {
  9019. Period = DefaultUpdatesPeriod;
  9020. AppLog(L"Thirdparty UWP package, using default updates check period");
  9021. }
  9022. else
  9023. {
  9024. Period = Updates.Period;
  9025. }
  9026. AppLogFmt(L"Updates check period: %.2f", (DateTimeToVariant(Period)));
  9027. if (double(Period) > 0)
  9028. {
  9029. TDateTime Interval = Now() - Updates.LastCheck;
  9030. AppLogFmt(L"Interval since the last updates check: %.2f", (DateTimeToVariant(Interval)));
  9031. if (Interval >= Period)
  9032. {
  9033. StartUpdateThread(UpdatesChecked);
  9034. }
  9035. }
  9036. }
  9037. }
  9038. //---------------------------------------------------------------------------
  9039. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  9040. {
  9041. AppLog(L"Updates check done");
  9042. UnicodeString Message;
  9043. bool New;
  9044. TQueryType Type;
  9045. GetUpdatesMessage(Message, New, Type, false);
  9046. if (!Message.IsEmpty())
  9047. {
  9048. AppLogFmt(L"Updates check message: %s", (Message));
  9049. if (New)
  9050. {
  9051. AppLog(L"New version detected");
  9052. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  9053. }
  9054. if (!New && (Type != qtWarning))
  9055. {
  9056. AppLog(L"Posting non-critical updates note");
  9057. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked);
  9058. }
  9059. else
  9060. {
  9061. AppLog(L"Posting new version or critical message notification");
  9062. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  9063. }
  9064. if (New)
  9065. {
  9066. Configuration->Usage->Inc(L"UpdateNotifications");
  9067. }
  9068. }
  9069. }
  9070. //---------------------------------------------------------------------------
  9071. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  9072. {
  9073. RestoreApp();
  9074. bool CanDisplay = !NonVisualDataModule->Busy;
  9075. if (!CanDisplay && (Screen->ActiveForm != NULL))
  9076. {
  9077. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  9078. }
  9079. if (CanDisplay)
  9080. {
  9081. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  9082. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  9083. NonVisualDataModule->StartBusy();
  9084. try
  9085. {
  9086. CheckForUpdates(true);
  9087. }
  9088. __finally
  9089. {
  9090. NonVisualDataModule->EndBusy();
  9091. }
  9092. }
  9093. else
  9094. {
  9095. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  9096. }
  9097. }
  9098. //---------------------------------------------------------------------------
  9099. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  9100. TCopyParamRuleData & Data)
  9101. {
  9102. DebugAssert(Terminal != NULL);
  9103. Data.HostName = Terminal->SessionData->HostNameExpanded;
  9104. Data.UserName = Terminal->SessionData->UserNameExpanded;
  9105. Data.RemoteDirectory = RemoteDirView->PathName;
  9106. }
  9107. //---------------------------------------------------------------------------
  9108. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  9109. {
  9110. // Terminal can be null when we are changing local directory implicitly,
  9111. // because it has been deleted, while no session is connected
  9112. // (Login dialog is open)
  9113. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  9114. {
  9115. DebugAssert(!IsLocalBrowserMode());
  9116. TCopyParamRuleData Data;
  9117. GetTransferPresetAutoSelectData(Data);
  9118. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  9119. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  9120. if (CopyParamIndex < 0)
  9121. {
  9122. // there is no preset that matches autoselection
  9123. // set preset that we consider "default"
  9124. FCopyParamAutoSelected = L""; // forget last autoselected preset
  9125. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  9126. }
  9127. else
  9128. {
  9129. // there is preset matching autoselection
  9130. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  9131. if (CopyParamName == FCopyParamAutoSelected)
  9132. {
  9133. // autoselected the same preset as the last time
  9134. // make no change (i.e. preserve custom user preset, if any)
  9135. }
  9136. else
  9137. {
  9138. // autoselected the different preset then the last time (or there
  9139. // was default preset set)
  9140. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  9141. GUIConfiguration->CopyParamCurrent = CopyParamName;
  9142. }
  9143. }
  9144. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  9145. {
  9146. if (CopyParamIndex >= 0)
  9147. {
  9148. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  9149. }
  9150. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  9151. try
  9152. {
  9153. int Fmt =
  9154. (CopyParamIndex < 0) ?
  9155. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  9156. COPY_PARAM_AUTOSELECTED;
  9157. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  9158. Data->Message = MainInstructions(Message);
  9159. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  9160. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  9161. CopyParamAttrs);
  9162. if (CopyParamIndex >= 0)
  9163. {
  9164. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  9165. Info = FORMAT(L"%s\n \n%s", (Info,
  9166. FMTLOAD(COPY_PARAM_RULE,
  9167. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  9168. }
  9169. Data->Message += L"\n\n" + Info;
  9170. if (WinConfiguration->CopyParamAutoSelectNotice)
  9171. {
  9172. TransferPresetNoteMessage(Data, true);
  9173. }
  9174. else
  9175. {
  9176. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  9177. Data = NULL; // ownership passed
  9178. }
  9179. }
  9180. __finally
  9181. {
  9182. delete Data;
  9183. }
  9184. }
  9185. }
  9186. }
  9187. //---------------------------------------------------------------------------
  9188. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9189. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9190. {
  9191. DebugAssert(NoteData != NULL);
  9192. DebugAssert(!IsLocalBrowserMode());
  9193. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9194. TQueryButtonAlias Aliases[1];
  9195. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9196. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9197. Params.Aliases = Aliases;
  9198. Params.AliasesCount = LENOF(Aliases);
  9199. unsigned int Result =
  9200. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9201. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9202. switch (Result)
  9203. {
  9204. case qaNeverAskAgain:
  9205. DebugAssert(AllowNeverAskAgain);
  9206. WinConfiguration->CopyParamAutoSelectNotice = false;
  9207. break;
  9208. case qaIgnore:
  9209. PreferencesDialog(pmPresets);
  9210. break;
  9211. }
  9212. }
  9213. //---------------------------------------------------------------------------
  9214. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9215. {
  9216. // as of now useless, as this is used for notes only, never for balloons, ...
  9217. RestoreApp();
  9218. // .. and we should never be busy here
  9219. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9220. {
  9221. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9222. }
  9223. }
  9224. //---------------------------------------------------------------------------
  9225. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9226. TPreferencesMode APreferencesMode)
  9227. {
  9228. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9229. TCopyParamRuleData Data;
  9230. if (Terminal != NULL)
  9231. {
  9232. PreferencesData.reset(new TPreferencesDialogData());
  9233. GetTransferPresetAutoSelectData(Data);
  9234. PreferencesData->CopyParamRuleData = &Data;
  9235. }
  9236. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9237. }
  9238. //---------------------------------------------------------------------------
  9239. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9240. const TCustomCommandType & Command)
  9241. {
  9242. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9243. {
  9244. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9245. }
  9246. }
  9247. //---------------------------------------------------------------------------
  9248. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9249. {
  9250. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9251. TCustomCommandType Command;
  9252. // make sure we use local custom command when remote are not supported
  9253. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9254. {
  9255. Command = FLastCustomCommand;
  9256. }
  9257. else
  9258. {
  9259. Command.Params = Command.Params | ccLocal;
  9260. }
  9261. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9262. FEditingFocusedAdHocCommand = OnFocused;
  9263. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9264. int Options =
  9265. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9266. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9267. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9268. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9269. {
  9270. FLastCustomCommand = Command;
  9271. UpdateCustomCommandsToolbar();
  9272. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9273. }
  9274. }
  9275. //---------------------------------------------------------------------------
  9276. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9277. {
  9278. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9279. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9280. DebugAssert(State > 0);
  9281. if (State <= 0)
  9282. {
  9283. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9284. }
  9285. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9286. }
  9287. //---------------------------------------------------------------------------
  9288. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9289. TCustomCommandType & Command, int & State)
  9290. {
  9291. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9292. if (Result)
  9293. {
  9294. Command = FLastCustomCommand;
  9295. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9296. }
  9297. return Result;
  9298. }
  9299. //---------------------------------------------------------------------------
  9300. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9301. {
  9302. ResetIncrementalSearch();
  9303. }
  9304. //---------------------------------------------------------------------------
  9305. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9306. {
  9307. DebugAssert(ComponentVisible[Component]);
  9308. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9309. }
  9310. //---------------------------------------------------------------------------
  9311. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9312. {
  9313. // when queue panel is resized here directly, the status bar is stretched
  9314. // over whole space the panel occupied
  9315. PostComponentHide(fcQueueView);
  9316. }
  9317. //---------------------------------------------------------------------------
  9318. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9319. {
  9320. ComponentVisible[fcQueueFileList] = false;
  9321. }
  9322. //---------------------------------------------------------------------------
  9323. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9324. {
  9325. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9326. // Scrollbars colors are refreshed by WM_THEMECHANGED.
  9327. RefreshColorMode();
  9328. ResetSysDarkTheme();
  9329. ConfigurationChanged();
  9330. ConfigureInterface();
  9331. // To update references to recreated/destroyed themes in SessionsPageControl
  9332. UpdateControls();
  9333. }
  9334. //---------------------------------------------------------------------------
  9335. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9336. {
  9337. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9338. if (!FInvalid &&
  9339. (Message.LParam != 0) &&
  9340. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9341. {
  9342. ThemeChanged();
  9343. }
  9344. TForm::Dispatch(&Message);
  9345. }
  9346. //---------------------------------------------------------------------------
  9347. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9348. {
  9349. TMessage * M = static_cast<TMessage*>(Message);
  9350. switch (M->Msg)
  9351. {
  9352. case CM_DIALOGCHAR:
  9353. CMDialogChar(*M);
  9354. break;
  9355. case WM_APPCOMMAND:
  9356. WMAppCommand(*M);
  9357. break;
  9358. case WM_SYSCOMMAND:
  9359. WMSysCommand(*M);
  9360. break;
  9361. case WM_QUERYENDSESSION:
  9362. WMQueryEndSession(*M);
  9363. break;
  9364. case WM_ENDSESSION:
  9365. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9366. break;
  9367. case WM_COMPONENT_HIDE:
  9368. {
  9369. Byte Component = static_cast<Byte>(M->WParam);
  9370. // sanity check
  9371. if (ComponentVisible[Component])
  9372. {
  9373. // special treatment
  9374. if (Component == fcQueueView)
  9375. {
  9376. ToggleQueueVisibility();
  9377. DebugAssert(!ComponentVisible[fcQueueView]);
  9378. }
  9379. else
  9380. {
  9381. ComponentVisible[Component] = false;
  9382. }
  9383. }
  9384. }
  9385. break;
  9386. case WM_COPYDATA:
  9387. WMCopyData(*M);
  9388. break;
  9389. case WM_MANAGES_CAPTION:
  9390. // caption managed in TTerminalManager::UpdateAppTitle()
  9391. M->Result = 1;
  9392. break;
  9393. case WM_WANTS_MOUSEWHEEL:
  9394. M->Result = 1;
  9395. break;
  9396. case CM_SHOWINGCHANGED:
  9397. CMShowingChanged(*M);
  9398. break;
  9399. case WM_CLOSE:
  9400. WMClose(*M);
  9401. break;
  9402. case WM_DPICHANGED:
  9403. WMDpiChanged(*M);
  9404. break;
  9405. case WM_SETTINGCHANGE:
  9406. WMSettingChange(*M);
  9407. break;
  9408. case CM_DIALOGKEY:
  9409. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9410. break;
  9411. case WM_PASTE_FILES:
  9412. PasteFiles();
  9413. break;
  9414. case WM_IS_HIDDEN:
  9415. // To treat master password prompt as a main window while showing it when workspace is loading while
  9416. // the exporer is showing up (Visible is true already)
  9417. M->Result = !FShowing;
  9418. break;
  9419. case WM_SHOWWINDOW:
  9420. if (M->WParam)
  9421. {
  9422. AddStartupSequence(L"J");
  9423. }
  9424. TForm::Dispatch(Message);
  9425. break;
  9426. case WM_QUEUE_CALLBACK:
  9427. WMQueueCallback(*M);
  9428. break;
  9429. default:
  9430. TForm::Dispatch(Message);
  9431. break;
  9432. }
  9433. }
  9434. //---------------------------------------------------------------------------
  9435. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9436. {
  9437. // noop
  9438. }
  9439. //---------------------------------------------------------------------------
  9440. void TCustomScpExplorerForm::RegenerateSessionColorsImageList()
  9441. {
  9442. FSessionColors->Clear();
  9443. AddFixedSessionImages();
  9444. ::RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9445. UpdateImages();
  9446. }
  9447. //---------------------------------------------------------------------------
  9448. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9449. {
  9450. TForm::Dispatch(&Message);
  9451. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9452. UpdatePixelsPerInchMainWindowCounter();
  9453. }
  9454. //---------------------------------------------------------------------------
  9455. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9456. {
  9457. AppLog(L"Main window WM_CLOSE");
  9458. // Cannot close window while we are busy.
  9459. // We cannot test this in FormCloseQuery as that is called also from
  9460. // Close(), which is called by CloseApplicationAction. So we can be busy
  9461. // there already even, when it is legitimate to close the application.
  9462. // Possibly a better place to handle this would be WMSysCommand.
  9463. if (NonVisualDataModule->Busy)
  9464. {
  9465. Message.Result = 1;
  9466. }
  9467. else
  9468. {
  9469. TForm::Dispatch(&Message);
  9470. }
  9471. }
  9472. //---------------------------------------------------------------------------
  9473. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9474. {
  9475. if (!FShowingChanged)
  9476. {
  9477. AddStartupSequence(L"D");
  9478. FShowingChanged = true;
  9479. }
  9480. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9481. bool NoSession = (ManagedSession == NULL);
  9482. // This calls TCustomScpExplorerForm::DoShow
  9483. TForm::Dispatch(&Message);
  9484. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9485. if (Showing && !FStarted)
  9486. {
  9487. FStarted = true;
  9488. InterfaceStarted();
  9489. }
  9490. if (Showing && NoSession)
  9491. {
  9492. // When we are starting minimized (i.e. from an installer),
  9493. // postpone showing Login dialog until we get restored.
  9494. // Otherwise the Login dialog (and Authentication window) show restored
  9495. // over invisible (minimized) main window.
  9496. if (WindowState == wsMinimized)
  9497. {
  9498. FNeedSession = true;
  9499. }
  9500. else
  9501. {
  9502. // This happens before application ever goes idle, so the toolbars would
  9503. // stay enabled (initial state) until the Login dialog is dismissed.
  9504. UpdateActions();
  9505. NonVisualDataModule->StartBusy();
  9506. try
  9507. {
  9508. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9509. // otherwise the dialog does not receive focus.
  9510. // With Commander interface the ProcessMessages is called already
  9511. // by TDriveView, but with Explorer interface, we need to call it explicily
  9512. Application->ProcessMessages();
  9513. // do not reload sessions, they have been loaded just now (optimization)
  9514. NeedSession(true);
  9515. }
  9516. __finally
  9517. {
  9518. NonVisualDataModule->EndBusy();
  9519. }
  9520. }
  9521. }
  9522. }
  9523. //---------------------------------------------------------------------------
  9524. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9525. {
  9526. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9527. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9528. }
  9529. //---------------------------------------------------------------------------
  9530. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9531. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9532. int & MaxHeight)
  9533. {
  9534. // workaround for bug in TWinControl.CalcConstraints
  9535. // Check for empty rect (restore from iconic state) is done there only after
  9536. // call to AdjustClientRect, which enlarges the rect (for forms).
  9537. TRect R = GetClientRect();
  9538. // when restoring from iconic state, place no restrictions
  9539. if (IsRectEmpty(R))
  9540. {
  9541. MinWidth = 0;
  9542. MinHeight = 0;
  9543. MaxWidth = 32000;
  9544. MaxHeight = 32000;
  9545. }
  9546. }
  9547. //---------------------------------------------------------------------------
  9548. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9549. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9550. {
  9551. // terminal can be already closed (e.g. dropped connection)
  9552. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9553. {
  9554. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9555. try
  9556. {
  9557. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9558. }
  9559. catch(...)
  9560. {
  9561. if (!Terminal->Active)
  9562. {
  9563. Close = true;
  9564. }
  9565. throw;
  9566. }
  9567. }
  9568. }
  9569. //---------------------------------------------------------------------------
  9570. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9571. {
  9572. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9573. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9574. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9575. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9576. {
  9577. OnGetSpaceAvailable = GetSpaceAvailable;
  9578. }
  9579. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9580. OnGetSpaceAvailable);
  9581. }
  9582. //---------------------------------------------------------------------------
  9583. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9584. {
  9585. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9586. Terminal->FillSessionDataForCode(Data.get());
  9587. return Data.release();
  9588. }
  9589. //---------------------------------------------------------------------------
  9590. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9591. {
  9592. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9593. DoGenerateUrlDialog(Data.get(), Paths);
  9594. }
  9595. //---------------------------------------------------------------------------
  9596. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9597. {
  9598. GenerateUrl(NULL);
  9599. }
  9600. //---------------------------------------------------------------------------
  9601. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9602. {
  9603. std::unique_ptr<TStrings> Paths(new TStringList());
  9604. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9605. GenerateUrl(Paths.get());
  9606. }
  9607. //---------------------------------------------------------------------------
  9608. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9609. {
  9610. FSessionColor = value;
  9611. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9612. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9613. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9614. DebugAssert(ColorItem != NULL);
  9615. ColorItem->Color = C;
  9616. NonVisualDataModule->ColorMenuItem->Color = C;
  9617. UpdateControls();
  9618. }
  9619. //---------------------------------------------------------------------------
  9620. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9621. {
  9622. if (value != FSessionColor)
  9623. {
  9624. UpdateSessionColor(value);
  9625. // Is null when called from LastTerminalClosed
  9626. if (Terminal != NULL)
  9627. {
  9628. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9629. }
  9630. }
  9631. }
  9632. //---------------------------------------------------------------------------
  9633. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9634. {
  9635. bool Result = FNoteTimer->Enabled;
  9636. if (Result)
  9637. {
  9638. // cannot cancel note too early
  9639. bool NotEarly =
  9640. (Now() - FNoteShown >
  9641. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9642. if (Force || NotEarly)
  9643. {
  9644. FNoteTimer->Enabled = false;
  9645. FNote = L"";
  9646. SAFE_DESTROY(FNoteData);
  9647. FOnNoteClick = NULL;
  9648. FNoteHints = FNotes->Text;
  9649. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9650. UpdateStatusBar();
  9651. }
  9652. }
  9653. return Result;
  9654. }
  9655. //---------------------------------------------------------------------------
  9656. void TCustomScpExplorerForm::CancelNote(const UnicodeString & Note)
  9657. {
  9658. if (FNote == Note)
  9659. {
  9660. CancelNote(true);
  9661. }
  9662. }
  9663. //---------------------------------------------------------------------------
  9664. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9665. {
  9666. DebugAssert(FNoteTimer->Enabled);
  9667. CancelNote(true);
  9668. }
  9669. //---------------------------------------------------------------------------
  9670. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9671. {
  9672. FNoteHints = FNotes->Text.TrimRight();
  9673. }
  9674. //---------------------------------------------------------------------------
  9675. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9676. {
  9677. int P = Note.Pos(L"\n");
  9678. if (P > 0)
  9679. {
  9680. Note.SetLength(P - 1);
  9681. }
  9682. FNotes->Add(FORMAT(L"[%s] %s",
  9683. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9684. while (FNotes->Count > 10)
  9685. {
  9686. FNotes->Delete(0);
  9687. }
  9688. if (UpdateNow)
  9689. {
  9690. UpdateNoteHints();
  9691. UpdateStatusBar();
  9692. }
  9693. }
  9694. //---------------------------------------------------------------------------
  9695. void TCustomScpExplorerForm::PostNote(
  9696. const UnicodeString & ANote, unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9697. {
  9698. UnicodeString Note = ANote;
  9699. int P = Note.Pos(L"\n");
  9700. if (P > 0)
  9701. {
  9702. Note.SetLength(P - 1);
  9703. }
  9704. UpdateNoteHints();
  9705. FNote = Note;
  9706. SAFE_DESTROY(FNoteData);
  9707. FNoteData = NoteData;
  9708. FOnNoteClick = OnNoteClick;
  9709. AddNote(Note, false);
  9710. UpdateStatusBar();
  9711. FNoteShown = Now();
  9712. FNoteTimer->Enabled = false;
  9713. if (Seconds == 0)
  9714. {
  9715. Seconds = WinConfiguration->NotificationsTimeout;
  9716. }
  9717. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9718. FNoteTimer->Enabled = true;
  9719. }
  9720. //---------------------------------------------------------------------------
  9721. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9722. {
  9723. PostNote(LoadStr(DIRECTORY_READING_CANCELLED));
  9724. }
  9725. //---------------------------------------------------------------------------
  9726. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9727. {
  9728. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9729. {
  9730. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9731. }
  9732. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9733. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9734. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))));
  9735. }
  9736. //---------------------------------------------------------------------------
  9737. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9738. {
  9739. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9740. UnicodeString Note =
  9741. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9742. PostNote(Note);
  9743. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9744. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9745. }
  9746. //---------------------------------------------------------------------------
  9747. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9748. {
  9749. WinConfiguration->FormatSizeBytes = Style;
  9750. }
  9751. //---------------------------------------------------------------------------
  9752. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9753. {
  9754. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9755. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9756. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9757. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))));
  9758. }
  9759. //---------------------------------------------------------------------------
  9760. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9761. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9762. {
  9763. if (Panel->Index == 0)
  9764. {
  9765. if (FOnNoteClick != NULL)
  9766. {
  9767. // prevent the user data from being freed by possible call
  9768. // to CancelNote or PostNote during call to OnNoteClick
  9769. std::unique_ptr<TObject> NoteData(FNoteData);
  9770. TNotifyEvent OnNoteClick = FOnNoteClick;
  9771. FNoteData = NULL;
  9772. // need to cancel the note as we are going to delete its user data
  9773. CancelNote(true);
  9774. OnNoteClick(NoteData.get());
  9775. }
  9776. }
  9777. if (HasAvailableTerminal() &&
  9778. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9779. {
  9780. FileSystemInfo();
  9781. }
  9782. }
  9783. //---------------------------------------------------------------------------
  9784. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9785. {
  9786. // workaround:
  9787. // 1) for unknown reason, disabling window, while minimized,
  9788. // prevents it from restoring, even if it was enabled again meanwhile
  9789. // 2) when disabling the main window, while another has focus
  9790. // minimize is no longer possible
  9791. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9792. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9793. // Shouldn't we use IsApplicationMinimized() here?
  9794. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9795. {
  9796. AppLog(L"Disabling window");
  9797. Enabled = false;
  9798. }
  9799. FLockLevel++;
  9800. }
  9801. //---------------------------------------------------------------------------
  9802. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9803. {
  9804. DebugAssert(FLockLevel > 0);
  9805. FLockLevel--;
  9806. if (FLockLevel == 0)
  9807. {
  9808. DebugAssert(FLockSuspendLevel == 0);
  9809. AppLog(L"Re-enabling window");
  9810. Enabled = true;
  9811. // VCL_COPY (TCustomForm.SetWindowFocus)
  9812. if (Active && (ActiveControl != NULL))
  9813. {
  9814. ::SetFocus(ActiveControl->Handle);
  9815. if (GetFocus() == ActiveControl->Handle)
  9816. {
  9817. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9818. }
  9819. }
  9820. }
  9821. }
  9822. //---------------------------------------------------------------------------
  9823. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9824. {
  9825. // We need to make sure that window is enabled when the last modal window closes
  9826. // otherwise focus is not restored correctly.
  9827. // So we re-enable the window when modal window opens and
  9828. // disable it back after is closes
  9829. if (FLockLevel > 0)
  9830. {
  9831. // while we have nesting counter, we know that we never be called
  9832. // recursivelly as Application->OnModalBegin is called only
  9833. // for the top-level modal window
  9834. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9835. {
  9836. // won't be disabled when conditions in LockWindow() were not satisfied
  9837. FDisabledOnLockSuspend = !Enabled;
  9838. // When minimized to tray (or actually when set to SW_HIDE),
  9839. // setting Enabled makes the window focusable even when there's
  9840. // modal window over it
  9841. if (!FTrayIcon->Visible)
  9842. {
  9843. Enabled = true;
  9844. }
  9845. }
  9846. FLockSuspendLevel++;
  9847. }
  9848. }
  9849. //---------------------------------------------------------------------------
  9850. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9851. {
  9852. if (FLockSuspendLevel > 0)
  9853. {
  9854. DebugAssert(FLockLevel > 0);
  9855. FLockSuspendLevel--;
  9856. // see comment in SuspendWindowLock
  9857. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9858. {
  9859. // Note that window can be enabled here, when we were minized to tray when
  9860. // was SuspendWindowLock() called.
  9861. // We should possibly do the same check as in LockWindow(),
  9862. // if it is ever possible that the consitions change between
  9863. // SuspendWindowLock() and ResumeWindowLock()
  9864. Enabled = !FDisabledOnLockSuspend;
  9865. }
  9866. }
  9867. }
  9868. //---------------------------------------------------------------------------
  9869. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9870. {
  9871. TTBXComboBoxItem * RemotePathComboBox =
  9872. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9873. if (!TextOnly)
  9874. {
  9875. TStrings * Items = RemotePathComboBox->Strings;
  9876. Items->BeginUpdate();
  9877. try
  9878. {
  9879. Items->Clear();
  9880. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9881. {
  9882. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9883. while (!IsUnixRootPath(APath))
  9884. {
  9885. int P = APath.LastDelimiter(L'/');
  9886. DebugAssert(P >= 0);
  9887. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9888. APath.SetLength(P - 1);
  9889. }
  9890. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9891. }
  9892. }
  9893. __finally
  9894. {
  9895. Items->EndUpdate();
  9896. }
  9897. }
  9898. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9899. // Setting ItemIndex to -1 does not reset its text
  9900. if (RemotePathComboBox->Strings->Count == 0)
  9901. {
  9902. RemotePathComboBox->Text = L"";
  9903. }
  9904. }
  9905. //---------------------------------------------------------------------------
  9906. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9907. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9908. {
  9909. if (AIndex < 0)
  9910. {
  9911. AIndex = Sender->ItemIndex;
  9912. }
  9913. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9914. }
  9915. //---------------------------------------------------------------------------
  9916. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9917. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9918. int & ImageIndex)
  9919. {
  9920. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9921. }
  9922. //---------------------------------------------------------------------------
  9923. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9924. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9925. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9926. {
  9927. if (!IsLocalBrowserMode())
  9928. {
  9929. ARect.Left += (10 * AIndex);
  9930. }
  9931. }
  9932. //---------------------------------------------------------------------------
  9933. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9934. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9935. {
  9936. AWidth += (10 * AIndex);
  9937. }
  9938. //---------------------------------------------------------------------------
  9939. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9940. {
  9941. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9942. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9943. int Index = RemotePathComboBox->ItemIndex;
  9944. while (Index < RemotePathComboBox->Strings->Count - 1)
  9945. {
  9946. APath = UnixExtractFileDir(APath);
  9947. Index++;
  9948. }
  9949. // VanDyke style paths
  9950. if (APath.IsEmpty())
  9951. {
  9952. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9953. APath = ROOTDIRECTORY;
  9954. }
  9955. if (RemoteDirView->Path != APath)
  9956. {
  9957. RemoteDirView->Path = APath;
  9958. }
  9959. }
  9960. //---------------------------------------------------------------------------
  9961. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9962. {
  9963. DoRemotePathComboBoxItemClick(Sender);
  9964. }
  9965. //---------------------------------------------------------------------------
  9966. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9967. {
  9968. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9969. DebugUsedParam(Sender);
  9970. UpdateRemotePathComboBox(true);
  9971. }
  9972. //---------------------------------------------------------------------------
  9973. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9974. {
  9975. DoRemotePathComboBoxCancel(Sender);
  9976. }
  9977. //---------------------------------------------------------------------------
  9978. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9979. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9980. {
  9981. ResetIncrementalSearch();
  9982. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9983. DebugAssert(DirView != NULL);
  9984. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9985. {
  9986. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9987. // OnEditing is called also from TCustomListView::CanEdit
  9988. if (Edit != NULL)
  9989. {
  9990. EditSelectBaseName(Edit);
  9991. }
  9992. }
  9993. }
  9994. //---------------------------------------------------------------------------
  9995. //---------------------------------------------------------------------------
  9996. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9997. {
  9998. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9999. Result->AutoDetectDnD = false;
  10000. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  10001. Result->RenderDataOn = rdoEnterAndDropSync;
  10002. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  10003. return Result;
  10004. }
  10005. //---------------------------------------------------------------------------
  10006. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  10007. {
  10008. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  10009. UseDarkMode(this);
  10010. }
  10011. //---------------------------------------------------------------------------
  10012. void __fastcall TCustomScpExplorerForm::CreateWnd()
  10013. {
  10014. TForm::CreateWnd();
  10015. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  10016. UpdateDarkMode();
  10017. if (FSessionsDragDropFilesEx == NULL)
  10018. {
  10019. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  10020. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  10021. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  10022. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  10023. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  10024. }
  10025. if (FQueueDragDropFilesEx == NULL)
  10026. {
  10027. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  10028. // No need to set OnDragOver as we do not have any restrictions
  10029. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  10030. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  10031. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  10032. }
  10033. }
  10034. //---------------------------------------------------------------------------
  10035. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  10036. {
  10037. TForm::DestroyWnd();
  10038. FSessionsDragDropFilesEx->DragDropControl = NULL;
  10039. FQueueDragDropFilesEx->DragDropControl = NULL;
  10040. }
  10041. //---------------------------------------------------------------------------
  10042. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  10043. {
  10044. SideEnter(FCurrentSide);
  10045. FEverShown = true;
  10046. }
  10047. //---------------------------------------------------------------------------
  10048. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  10049. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  10050. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  10051. {
  10052. if (!NonVisualDataModule->Busy)
  10053. {
  10054. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  10055. Configuration->Usage->Inc(L"FileFinds");
  10056. LockWindow(true);
  10057. NonVisualDataModule->StartBusy();
  10058. WinConfiguration->LockedInterface = true;
  10059. try
  10060. {
  10061. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  10062. }
  10063. __finally
  10064. {
  10065. WinConfiguration->LockedInterface = false;
  10066. NonVisualDataModule->EndBusy();
  10067. UnlockWindow();
  10068. }
  10069. }
  10070. }
  10071. //---------------------------------------------------------------------------
  10072. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  10073. {
  10074. if (!NonVisualDataModule->Busy)
  10075. {
  10076. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  10077. SetFocus();
  10078. RemoteDirView->Path = UnixExtractFilePath(Path);
  10079. UnicodeString FileName = UnixExtractFileName(Path);
  10080. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  10081. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  10082. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  10083. if (Item == NULL)
  10084. {
  10085. ReloadDirectory(osRemote);
  10086. Item = RemoteDirView->FindFileItem(FileName);
  10087. }
  10088. if (Item != NULL)
  10089. {
  10090. RemoteDirView->ItemFocused = Item;
  10091. RemoteDirView->ItemFocused->MakeVisible(false);
  10092. RemoteDirView->SetFocus();
  10093. }
  10094. }
  10095. }
  10096. //---------------------------------------------------------------------------
  10097. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  10098. {
  10099. bool Result = !NonVisualDataModule->Busy;
  10100. if (Result)
  10101. {
  10102. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  10103. }
  10104. return Result;
  10105. }
  10106. //---------------------------------------------------------------------------
  10107. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  10108. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10109. {
  10110. if (CanOperateOnFoundFiles(ATerminal))
  10111. {
  10112. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished, OnFileOperationFinished);
  10113. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  10114. }
  10115. }
  10116. //---------------------------------------------------------------------------
  10117. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  10118. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10119. {
  10120. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  10121. }
  10122. //---------------------------------------------------------------------------
  10123. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  10124. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10125. {
  10126. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  10127. }
  10128. //---------------------------------------------------------------------------
  10129. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  10130. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10131. {
  10132. if (CanOperateOnFoundFiles(ATerminal))
  10133. {
  10134. for (int Index = 0; Index < FileList->Count; Index++)
  10135. {
  10136. UnicodeString FileName = FileList->Strings[Index];
  10137. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  10138. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  10139. OnFileOperationFinished(osRemote, FileName, true, true);
  10140. }
  10141. }
  10142. }
  10143. //---------------------------------------------------------------------------
  10144. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  10145. {
  10146. FFileFindTerminal = Terminal;
  10147. ShowFileFindDialog(
  10148. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  10149. DoDownloadFoundFiles, DoEditFoundFiles);
  10150. }
  10151. //---------------------------------------------------------------------------
  10152. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  10153. {
  10154. FTaskbarList = TaskbarList;
  10155. }
  10156. //---------------------------------------------------------------------------
  10157. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  10158. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  10159. {
  10160. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10161. if (Index >= 0)
  10162. {
  10163. if (Button == mbLeft)
  10164. {
  10165. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  10166. // If switching tab (switching session) takes long enough for user
  10167. // to actually release the button, "mouse down" is still raised,
  10168. // but we do not get "mouse up" event, so dragging is not cancelled,
  10169. // prevent that by not beginning dragging in the first place.
  10170. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  10171. if (IsKeyPressed(Key))
  10172. {
  10173. // when user clicks the "+", we get mouse down only after the session
  10174. // is closed, when new session tab is already on X:Y, so dragging
  10175. // starts, prevent that
  10176. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  10177. {
  10178. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10179. if (Terminal != NULL)
  10180. {
  10181. SessionsPageControl->BeginDrag(false);
  10182. }
  10183. }
  10184. }
  10185. }
  10186. else if (Button == mbMiddle)
  10187. {
  10188. // ignore middle-click for "New session tab" and the last local-local tab
  10189. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10190. if ((Session != NULL) && CanCloseSession(Session))
  10191. {
  10192. CloseSessionTab(Index);
  10193. }
  10194. }
  10195. }
  10196. }
  10197. //---------------------------------------------------------------------------
  10198. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10199. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10200. {
  10201. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10202. // do not allow dropping on the "+" tab
  10203. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10204. if ((TargetTerminal != NULL) &&
  10205. (SessionsPageControl->ActivePage->PageIndex != Index))
  10206. {
  10207. Configuration->Usage->Inc(L"SessionTabMoves");
  10208. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10209. // but we want to actually prevent that to avoid flicker
  10210. SessionsPageControl->ActivePage->PageIndex = Index;
  10211. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10212. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10213. }
  10214. }
  10215. //---------------------------------------------------------------------------
  10216. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10217. TObject * Sender, TObject * Source, int X, int Y,
  10218. TDragState /*State*/, bool & Accept)
  10219. {
  10220. Accept = (Sender == Source);
  10221. if (Accept)
  10222. {
  10223. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10224. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10225. // do not allow dragging to the "+" tab
  10226. Accept = (Terminal != NULL);
  10227. }
  10228. }
  10229. //---------------------------------------------------------------------------
  10230. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10231. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10232. {
  10233. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10234. if (Index < 0)
  10235. {
  10236. Effect = DROPEFFECT_NONE;
  10237. }
  10238. else
  10239. {
  10240. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10241. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10242. if (!IsAvailableTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10243. {
  10244. Effect = DROPEFFECT_NONE;
  10245. }
  10246. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10247. {
  10248. Effect = DROPEFFECT_COPY;
  10249. }
  10250. }
  10251. }
  10252. //---------------------------------------------------------------------------
  10253. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10254. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10255. {
  10256. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10257. // do not allow dropping on local-local, disconnected and the "+" tab
  10258. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10259. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10260. if (DebugAlwaysTrue(IsAvailableTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10261. {
  10262. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10263. if (!IsFileControl(DropSourceControl, osRemote))
  10264. {
  10265. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10266. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10267. // Why don't we use Terminal->CurrentDirectory directly?
  10268. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10269. // do not force queue, drag drop
  10270. false, true);
  10271. }
  10272. }
  10273. }
  10274. //---------------------------------------------------------------------------
  10275. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10276. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10277. {
  10278. // Downloads are handled in RemoteFileControlDDEnd
  10279. if (!IsFileControl(DropSourceControl, osRemote))
  10280. {
  10281. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10282. Terminal->CurrentDirectory,
  10283. // force queue, drag drop
  10284. true, true);
  10285. }
  10286. }
  10287. //---------------------------------------------------------------------------
  10288. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10289. {
  10290. FShowing = false;
  10291. // Do not save empty workspace
  10292. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10293. {
  10294. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10295. UnicodeString Name = WorkspaceName();
  10296. DoSaveWorkspace(
  10297. Name, DataList.get(),
  10298. !Configuration->DisablePasswordStoring &&
  10299. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10300. WinConfiguration->LastStoredSession = Name;
  10301. }
  10302. AppLog(L"Closing main window");
  10303. }
  10304. //---------------------------------------------------------------------------
  10305. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10306. {
  10307. TManagedTerminal * ManagedTerminal =
  10308. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10309. if (ManagedTerminal != NULL)
  10310. {
  10311. ManagedTerminal->DirectoryLoaded = Now();
  10312. }
  10313. }
  10314. //---------------------------------------------------------------------------
  10315. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10316. TListItem * /*Item*/, bool /*Selected*/)
  10317. {
  10318. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10319. switch (DirView->LastSelectMethod)
  10320. {
  10321. case smKeyboard:
  10322. Configuration->Usage->Inc(L"KeyboardSelections");
  10323. break;
  10324. case smMouse:
  10325. Configuration->Usage->Inc(L"MouseSelections");
  10326. break;
  10327. }
  10328. }
  10329. //---------------------------------------------------------------------------
  10330. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10331. {
  10332. if (Color != 0)
  10333. {
  10334. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10335. }
  10336. else
  10337. {
  10338. return FSessionTabImageIndex;
  10339. }
  10340. }
  10341. //---------------------------------------------------------------------------
  10342. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10343. {
  10344. TPngImageCollectionItem * Item =
  10345. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10346. FSessionColors->AddPng(Item->PngImage);
  10347. return FSessionColors->Count - 1;
  10348. }
  10349. //---------------------------------------------------------------------------
  10350. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10351. {
  10352. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10353. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10354. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10355. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10356. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10357. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10358. }
  10359. //---------------------------------------------------------------------------
  10360. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10361. {
  10362. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10363. }
  10364. //---------------------------------------------------------------------------
  10365. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10366. {
  10367. switch (Side)
  10368. {
  10369. case osLocal:
  10370. return FNewLocalTabTabImageIndex;
  10371. case osRemote:
  10372. case osCurrent:
  10373. return FNewRemoteTabTabImageIndex;
  10374. default:
  10375. DebugFail();
  10376. return -1;
  10377. }
  10378. }
  10379. //---------------------------------------------------------------------------
  10380. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10381. {
  10382. for (int Index = 0; Index < Control->ControlCount; Index++)
  10383. {
  10384. TControl * AControl = Control->Controls[Index];
  10385. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10386. if (WinControl != NULL)
  10387. {
  10388. CollectItemsWithTextDisplayMode(WinControl);
  10389. }
  10390. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10391. if (Toolbar != NULL)
  10392. {
  10393. // we care for top-level items only
  10394. TTBCustomItem * Items = Toolbar->Items;
  10395. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10396. {
  10397. TTBCustomItem * Item = Items->Items[ItemIndex];
  10398. if (((Item->DisplayMode == nbdmImageAndText) ||
  10399. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10400. EligibleForImageDisplayMode(Item))
  10401. {
  10402. FItemsWithTextDisplayMode.insert(Item);
  10403. }
  10404. }
  10405. }
  10406. }
  10407. }
  10408. //---------------------------------------------------------------------------
  10409. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10410. {
  10411. return true;
  10412. }
  10413. //---------------------------------------------------------------------------
  10414. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10415. {
  10416. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10417. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10418. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10419. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10420. bool Result = true;
  10421. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10422. {
  10423. TTBCustomItem * Item = *i;
  10424. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10425. if (Label != NULL)
  10426. {
  10427. // optimization
  10428. if (Label->Visible == SelectiveToolbarText)
  10429. {
  10430. Result = false;
  10431. }
  10432. else
  10433. {
  10434. Label->Visible = SelectiveToolbarText;
  10435. }
  10436. }
  10437. else
  10438. {
  10439. // optimization
  10440. if (Item->DisplayMode == DisplayMode)
  10441. {
  10442. Result = false;
  10443. }
  10444. else
  10445. {
  10446. Item->DisplayMode = DisplayMode;
  10447. }
  10448. }
  10449. ++i;
  10450. }
  10451. UpdateNewTabTab();
  10452. return Result;
  10453. }
  10454. //---------------------------------------------------------------------------
  10455. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10456. {
  10457. DebugFail();
  10458. }
  10459. //---------------------------------------------------------------------------
  10460. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10461. {
  10462. // Among other, a lock level is non zero, while directory is being loaded,
  10463. // even when it happens as a result of dirview navigation,
  10464. // i.e. when TNonVisualDataModule is NOT FBusy.
  10465. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10466. // Among other this prevents a panel auto update to occur while
  10467. // directory is changing.
  10468. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10469. }
  10470. //---------------------------------------------------------------------------
  10471. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10472. {
  10473. // While the window is disabled, we still seem to process menu shortcuts at least,
  10474. // so stop it at least here.
  10475. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10476. bool Result;
  10477. if (Allowed == aaUpdate)
  10478. {
  10479. Result = true;
  10480. }
  10481. else
  10482. {
  10483. Result = !NonVisualDataModule->Busy;
  10484. if (Result && (Allowed == aaShortCut))
  10485. {
  10486. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10487. Action->Update();
  10488. Result = Action->Enabled;
  10489. }
  10490. }
  10491. return Result;
  10492. }
  10493. //---------------------------------------------------------------------------
  10494. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10495. {
  10496. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10497. }
  10498. //---------------------------------------------------------------------------
  10499. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10500. {
  10501. // This is somewhat redundant to LockWindow() call from
  10502. // TTerminalManager::TerminalReadDirectoryProgress.
  10503. // But disabling window is known not to block keyboard shorcuts
  10504. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10505. if (Busy > 0)
  10506. {
  10507. if (NonVisualDataModule->Busy)
  10508. {
  10509. State = false;
  10510. }
  10511. else
  10512. {
  10513. NonVisualDataModule->StartBusy();
  10514. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10515. LockWindow();
  10516. }
  10517. }
  10518. else if (Busy < 0)
  10519. {
  10520. UnlockWindow();
  10521. NonVisualDataModule->EndBusy();
  10522. }
  10523. else
  10524. {
  10525. State = NonVisualDataModule->Busy;
  10526. }
  10527. }
  10528. //---------------------------------------------------------------------------
  10529. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10530. {
  10531. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10532. if (Index >= 0)
  10533. {
  10534. TPopupMenu * PopupMenu = NULL;
  10535. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10536. if (Session != NULL)
  10537. {
  10538. SessionsPageControl->ActivePageIndex = Index;
  10539. if (DebugAlwaysTrue(SessionTabSwitched()))
  10540. {
  10541. // copied from TControl.WMContextMenu
  10542. SendCancelMode(SessionsPageControl);
  10543. // explicit popup instead of using PopupMenu property
  10544. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10545. // while connecting yet not-connected session and hence
  10546. // allowing an access to commands over not-completely connected session
  10547. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10548. }
  10549. }
  10550. else
  10551. {
  10552. if (SupportsLocalBrowser())
  10553. {
  10554. PopupMenu = NonVisualDataModule->NewTabPopup;
  10555. }
  10556. }
  10557. if (PopupMenu != NULL)
  10558. {
  10559. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10560. PopupMenu->PopupComponent = SessionsPageControl;
  10561. PopupMenu->Popup(Point.x, Point.y);
  10562. }
  10563. }
  10564. Handled = true;
  10565. }
  10566. //---------------------------------------------------------------------------
  10567. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10568. {
  10569. return HasAvailableTerminal() && Terminal->IsCapable[fcChangePassword];
  10570. }
  10571. //---------------------------------------------------------------------------
  10572. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10573. {
  10574. Configuration->Usage->Inc(L"PasswordChanges");
  10575. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10576. ChangePasswordData->DisableAuthentationsExceptPassword();
  10577. ChangePasswordData->ChangePassword = true;
  10578. std::unique_ptr<TTerminal> ChangePasswordSession(
  10579. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10580. ChangePasswordSession->AutoReadDirectory = false;
  10581. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10582. {
  10583. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10584. }
  10585. else
  10586. {
  10587. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10588. }
  10589. }
  10590. //---------------------------------------------------------------------------
  10591. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10592. {
  10593. // No nice way to assert SSH2
  10594. return HasAvailableTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10595. }
  10596. //---------------------------------------------------------------------------
  10597. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10598. {
  10599. TOperationVisualizer OperationVisualizer;
  10600. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10601. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10602. }
  10603. //---------------------------------------------------------------------------
  10604. void __fastcall TCustomScpExplorerForm::FormAfterMonitorDpiChanged(TObject *, int OldDPI, int NewDPI)
  10605. {
  10606. DebugUsedParam(OldDPI);
  10607. DebugAssert(NewDPI == GetControlPixelsPerInch(this));
  10608. GlyphsModule->PixelsPerInch = NewDPI;
  10609. // Can be called too early when primary monitor has non-system dpi
  10610. if (FSessionColors != NULL)
  10611. {
  10612. RegenerateSessionColorsImageList();
  10613. }
  10614. UpdateTabsSize();
  10615. UpdateSessionsPageControlHeight();
  10616. QueueFileListColumnAutoSize();
  10617. }
  10618. //---------------------------------------------------------------------------
  10619. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10620. {
  10621. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10622. }
  10623. //---------------------------------------------------------------------
  10624. class TPublicControl : public TControl
  10625. {
  10626. friend class TCustomScpExplorerForm;
  10627. };
  10628. //---------------------------------------------------------------------------
  10629. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10630. {
  10631. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10632. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10633. }
  10634. //---------------------------------------------------------------------------
  10635. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10636. {
  10637. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10638. OpenBookmark(Side, Bookmark);
  10639. }
  10640. //---------------------------------------------------------------------------
  10641. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10642. {
  10643. DoBookmarkClick(osLocal, Sender);
  10644. }
  10645. //---------------------------------------------------------------------------
  10646. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10647. {
  10648. DoBookmarkClick(osRemote, Sender);
  10649. }
  10650. //---------------------------------------------------------------------------
  10651. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10652. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10653. {
  10654. if (BookmarkList != NULL)
  10655. {
  10656. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10657. if (IsLocalBrowserMode())
  10658. {
  10659. Side = osLocal;
  10660. }
  10661. if (!WinConfiguration->UseLocationProfiles)
  10662. {
  10663. std::unique_ptr<TStringList> Directories(new TStringList());
  10664. Directories->CaseSensitive = (Side == osRemote);
  10665. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10666. {
  10667. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10668. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10669. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10670. {
  10671. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10672. Item->Caption = EscapeHotkey(Directory);
  10673. Item->ShortCut = Bookmark->ShortCut;
  10674. Item->OnClick = OnBookmarkClick;
  10675. Item->Tag = reinterpret_cast<int>(Bookmark);
  10676. Directories->Add(Directory);
  10677. Menu->Add(Item.release());
  10678. }
  10679. }
  10680. }
  10681. else
  10682. {
  10683. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10684. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10685. {
  10686. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10687. if (!Bookmark->Node.IsEmpty())
  10688. {
  10689. Folders->Add(Bookmark->Node);
  10690. }
  10691. }
  10692. for (int Index = 0; Index < Folders->Count; Index++)
  10693. {
  10694. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10695. Item->Caption = Folders->Strings[Index];
  10696. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10697. Folders->Objects[Index] = Item.get();
  10698. Menu->Add(Item.release());
  10699. }
  10700. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10701. {
  10702. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10703. TTBCustomItem * Parent;
  10704. if (!Bookmark->Node.IsEmpty())
  10705. {
  10706. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10707. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10708. }
  10709. else
  10710. {
  10711. Parent = Menu;
  10712. }
  10713. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10714. Item->Caption = Bookmark->Name;
  10715. Item->ShortCut = Bookmark->ShortCut;
  10716. Item->OnClick = OnBookmarkClick;
  10717. Item->Tag = reinterpret_cast<int>(Bookmark);
  10718. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10719. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10720. {
  10721. // No hint for location profiles that are actually mere "bookmarks"
  10722. }
  10723. else
  10724. {
  10725. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10726. UnicodeString LongHint;
  10727. if (!Bookmark->Local.IsEmpty())
  10728. {
  10729. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10730. }
  10731. if (!Bookmark->Remote.IsEmpty())
  10732. {
  10733. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10734. }
  10735. AddToList(Hint, LongHint, L"|");
  10736. Item->Hint = Hint;
  10737. }
  10738. Parent->Add(Item.release());
  10739. }
  10740. }
  10741. AddMenuSeparator(Menu);
  10742. }
  10743. }
  10744. //---------------------------------------------------------------------------
  10745. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10746. {
  10747. Menu->Clear();
  10748. std::unique_ptr<TTBCustomItem> Item;
  10749. Item.reset(new TTBXItem(Owner));
  10750. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10751. Item->Options = Item->Options << tboDefault;
  10752. Menu->Add(Item.release());
  10753. AddMenuSeparator(Menu);
  10754. if (Terminal != NULL)
  10755. {
  10756. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10757. }
  10758. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10759. Item.reset(new TTBXItem(Owner));
  10760. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10761. Menu->Add(Item.release());
  10762. }
  10763. //---------------------------------------------------------------------------
  10764. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10765. {
  10766. bool Result = true;
  10767. bool Remote = !IsSideLocalBrowser(Side);
  10768. try
  10769. {
  10770. UnicodeString APath = Path;
  10771. if (Remote)
  10772. {
  10773. Terminal->ExceptionOnFail = true;
  10774. }
  10775. else
  10776. {
  10777. APath = ExpandEnvironmentVariables(Path);
  10778. }
  10779. try
  10780. {
  10781. DirView(Side)->Path = APath;
  10782. }
  10783. __finally
  10784. {
  10785. if (Remote)
  10786. {
  10787. Terminal->ExceptionOnFail = false;
  10788. }
  10789. }
  10790. }
  10791. catch (Exception & E)
  10792. {
  10793. if (!Remote || Terminal->Active)
  10794. {
  10795. ShowExtendedExceptionEx(Terminal, &E);
  10796. Result = false;
  10797. }
  10798. else
  10799. {
  10800. throw;
  10801. }
  10802. }
  10803. return Result;
  10804. }
  10805. //---------------------------------------------------------------------------
  10806. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10807. {
  10808. // Make sure there some feedback even when loading tiny local folders
  10809. TInstantOperationVisualizer Visualizer;
  10810. DirView(Side)->ReloadDirectory();
  10811. }
  10812. //---------------------------------------------------------------------------
  10813. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10814. {
  10815. if (Index == SessionsPageControl->TabIndex)
  10816. {
  10817. CloseTab();
  10818. }
  10819. else
  10820. {
  10821. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10822. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10823. TTerminalManager * Manager = TTerminalManager::Instance();
  10824. if (!Terminal->Active)
  10825. {
  10826. Manager->FreeTerminal(Terminal);
  10827. }
  10828. else
  10829. {
  10830. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10831. if (CanCloseQueue(Queue))
  10832. {
  10833. Manager->FreeTerminal(Terminal);
  10834. }
  10835. }
  10836. }
  10837. }
  10838. //---------------------------------------------------------------------------
  10839. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10840. {
  10841. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10842. if (Session == NULL)
  10843. {
  10844. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10845. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10846. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10847. //P = SessionsPageControl->ClientToScreen(P);
  10848. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10849. }
  10850. else
  10851. {
  10852. CloseSessionTab(Index);
  10853. }
  10854. }
  10855. //---------------------------------------------------------------------------
  10856. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10857. {
  10858. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10859. {
  10860. TInstantOperationVisualizer Visualizer;
  10861. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10862. // before we create a new data object
  10863. ClipboardClear();
  10864. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10865. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10866. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10867. // Intermediate variable to WORKAROUND a crash in compiler
  10868. TObjectList * ClipboardFakeMonitors =
  10869. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10870. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10871. if (FClipboardDragDropFilesEx.get() == NULL)
  10872. {
  10873. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10874. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10875. }
  10876. FClipboardDragDropFilesEx->FileList->Clear();
  10877. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10878. FClipboardDragDropFilesEx->CopyToClipboard();
  10879. FClipboardTerminal = Terminal;
  10880. // Need full paths, as cwd can be different once files are pasted
  10881. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10882. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10883. {
  10884. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10885. }
  10886. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10887. }
  10888. }
  10889. //---------------------------------------------------------------------------
  10890. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10891. {
  10892. if (OpenClipboard(0))
  10893. {
  10894. AppLog(L"Clearing clipboard");
  10895. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10896. CloseClipboard();
  10897. }
  10898. }
  10899. //---------------------------------------------------------------------------
  10900. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10901. {
  10902. return !FClipboardFakeDirectory.IsEmpty();
  10903. }
  10904. //---------------------------------------------------------------------------
  10905. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10906. {
  10907. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10908. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10909. FClipboardFakeDirectory = UnicodeString();
  10910. FClipboardTerminal = NULL;
  10911. if (FDownloadingFromClipboard)
  10912. {
  10913. // We are called by the monitor, so attempt to release it would deadlock
  10914. FClipboardFakeMonitorsPendingReset = true;
  10915. }
  10916. else
  10917. {
  10918. FClipboardFakeMonitors.reset(NULL);
  10919. }
  10920. }
  10921. //---------------------------------------------------------------------------
  10922. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10923. {
  10924. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10925. {
  10926. ClipboardStop();
  10927. }
  10928. }
  10929. //---------------------------------------------------------------------------
  10930. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10931. {
  10932. TTerminalManager * Manager = TTerminalManager::Instance();
  10933. Manager->ActiveSession = FClipboardTerminal;
  10934. TTransferOperationParam Params;
  10935. Params.TargetDirectory = TargetDirectory;
  10936. Params.DragDrop = DragDrop;
  10937. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10938. }
  10939. //---------------------------------------------------------------------------
  10940. void TCustomScpExplorerForm::PasteFilesCleanupRetry(const UnicodeString & Target)
  10941. {
  10942. bool Removed = RemoveDir(ApiPath(Target));
  10943. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10944. }
  10945. //---------------------------------------------------------------------------
  10946. void TCustomScpExplorerForm::PasteFiles()
  10947. {
  10948. // Guard against possible race conditions
  10949. if (!FClipboardPasteTarget.IsEmpty())
  10950. {
  10951. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10952. UnicodeString Target = FClipboardPasteTarget;
  10953. FClipboardPasteTarget = EmptyStr;
  10954. // Can fail as it can be e.g. locked by AV, so we retry that later
  10955. bool Removed = RemoveDir(ApiPath(Target));
  10956. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10957. try
  10958. {
  10959. if (NonVisualDataModule->Busy)
  10960. {
  10961. AppLog(L"Is busy, cannot paste");
  10962. }
  10963. else
  10964. {
  10965. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10966. FClipboardFakeMonitorsPendingReset = false;
  10967. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10968. TAutoFlag Flag(FDownloadingFromClipboard);
  10969. AppLog(L"Downloading to paste target...");
  10970. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10971. AppLog(L"Downloaded to paste target...");
  10972. }
  10973. }
  10974. __finally
  10975. {
  10976. if (!Removed)
  10977. {
  10978. PasteFilesCleanupRetry(Target);
  10979. }
  10980. }
  10981. }
  10982. }
  10983. //---------------------------------------------------------------------------
  10984. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10985. {
  10986. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10987. // (as it pumps a Windows message queue while being shutted down)
  10988. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10989. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10990. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10991. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10992. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10993. {
  10994. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10995. FClipboardPasteTarget = FileName;
  10996. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10997. // Postponing removing (or actually whole pasting operation) seems to help.
  10998. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10999. }
  11000. }
  11001. //---------------------------------------------------------------------------
  11002. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  11003. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  11004. {
  11005. TFileMasks::TParams MaskParams;
  11006. MaskParams.Size = Size;
  11007. MaskParams.Modification = Modification;
  11008. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  11009. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  11010. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  11011. if (!Local && Directory)
  11012. {
  11013. FileName = UnixExcludeTrailingBackslash(FileName);
  11014. }
  11015. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  11016. {
  11017. bool ImplicitMatch;
  11018. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  11019. !ImplicitMatch)
  11020. {
  11021. Color = Iter->Color;
  11022. break;
  11023. }
  11024. }
  11025. }
  11026. //---------------------------------------------------------------------------
  11027. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  11028. {
  11029. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  11030. if (!DirView->IsEditing())
  11031. {
  11032. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  11033. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  11034. // while searching
  11035. if (Key == VK_BACK)
  11036. {
  11037. if (FIncrementalSearchState.Searching)
  11038. {
  11039. if (FIncrementalSearchState.Text.Length() <= 1)
  11040. {
  11041. ResetIncrementalSearch();
  11042. }
  11043. else
  11044. {
  11045. UnicodeString NewText = LeftStr(FIncrementalSearchState.Text, FIncrementalSearchState.Text.Length() - 1);
  11046. IncrementalSearch(NewText, false, false);
  11047. }
  11048. Key = 0;
  11049. }
  11050. }
  11051. }
  11052. }
  11053. //---------------------------------------------------------------------------
  11054. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  11055. {
  11056. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  11057. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  11058. {
  11059. // Filter control sequences.
  11060. // When not searching yet, prefer use of the space for toggling file selection
  11061. // (so we cannot incrementally search for a string starting with a space).
  11062. if ((Key > VK_SPACE) ||
  11063. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && FIncrementalSearchState.Searching))
  11064. {
  11065. IncrementalSearch(FIncrementalSearchState.Text + Key, false, false);
  11066. Key = 0;
  11067. }
  11068. }
  11069. }
  11070. //---------------------------------------------------------------------------
  11071. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  11072. {
  11073. if (FIncrementalSearchState.Searching)
  11074. {
  11075. FIncrementalSearchState.Reset();
  11076. DirView(osCurrent)->UpdateStatusBar();
  11077. }
  11078. }
  11079. //---------------------------------------------------------------------------
  11080. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  11081. {
  11082. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  11083. if (Item == NULL)
  11084. {
  11085. MessageBeep(MB_ICONHAND);
  11086. }
  11087. else
  11088. {
  11089. TCustomDirView * ADirView = DirView(osCurrent);
  11090. {
  11091. TAutoNestingCounter Guard(FIncrementalSearching);
  11092. ADirView->FocusItem(Item);
  11093. if (ADirView->NortonLike == nlOff)
  11094. {
  11095. if ((ADirView->Selected != Item) ||
  11096. (ADirView->SelCount > 1))
  11097. {
  11098. ADirView->ClearSelection();
  11099. ADirView->Selected = Item;
  11100. }
  11101. }
  11102. }
  11103. FIncrementalSearchState.Searching = true;
  11104. FIncrementalSearchState.Text = Text;
  11105. Item->MakeVisible(false);
  11106. TListItem * NextItem = SearchFile(Text, true, Reverse);
  11107. FIncrementalSearchState.HaveNext = (NextItem != NULL) && (NextItem != Item);
  11108. ADirView->UpdateStatusBar();
  11109. }
  11110. }
  11111. //---------------------------------------------------------------------------
  11112. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  11113. {
  11114. int Index = Item->Index;
  11115. if (!Reverse)
  11116. {
  11117. Index++;
  11118. if (Index >= Item->Owner->Count)
  11119. {
  11120. Index = 0;
  11121. }
  11122. }
  11123. else
  11124. {
  11125. Index--;
  11126. if (Index < 0)
  11127. {
  11128. Index = Item->Owner->Count - 1;
  11129. }
  11130. }
  11131. return Item->Owner->Item[Index];
  11132. }
  11133. //---------------------------------------------------------------------------
  11134. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  11135. {
  11136. TCustomDirView * ADirView = DirView(osCurrent);
  11137. if (ADirView->Items->Count == 0)
  11138. {
  11139. return NULL;
  11140. }
  11141. else
  11142. {
  11143. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  11144. TListItem * Item = CurrentItem;
  11145. if (SkipCurrent)
  11146. {
  11147. Item = DebugNotNull(GetNextFile(Item, Reverse));
  11148. }
  11149. while (true)
  11150. {
  11151. bool Matches = false;
  11152. switch (WinConfiguration->PanelSearch)
  11153. {
  11154. case isNameStartOnly:
  11155. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  11156. break;
  11157. case isName:
  11158. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  11159. break;
  11160. case isAll:
  11161. int ColCount = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Count : 1;
  11162. int Index = 0;
  11163. while ((Index < ColCount) && !Matches)
  11164. {
  11165. bool Visible = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Visible[Index] : true;
  11166. if (Visible)
  11167. {
  11168. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  11169. }
  11170. Index++;
  11171. }
  11172. break;
  11173. }
  11174. if (Matches)
  11175. {
  11176. return Item;
  11177. }
  11178. Item = GetNextFile(Item, Reverse);
  11179. if (Item == CurrentItem)
  11180. {
  11181. return NULL;
  11182. }
  11183. }
  11184. }
  11185. }
  11186. //---------------------------------------------------------------------------
  11187. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  11188. {
  11189. ResetIncrementalSearch();
  11190. }
  11191. //---------------------------------------------------------------------------
  11192. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  11193. {
  11194. if (Message.CharCode == VK_TAB)
  11195. {
  11196. if (!FIncrementalSearchState.Text.IsEmpty())
  11197. {
  11198. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11199. bool Reverse = Shift.Contains(ssShift);
  11200. IncrementalSearch(FIncrementalSearchState.Text, true, Reverse);
  11201. Message.Result = 1;
  11202. return;
  11203. }
  11204. }
  11205. else if (Message.CharCode == VK_ESCAPE)
  11206. {
  11207. if (FIncrementalSearchState.Searching)
  11208. {
  11209. ResetIncrementalSearch();
  11210. Message.Result = 1;
  11211. return;
  11212. }
  11213. }
  11214. TForm::Dispatch(&Message);
  11215. }
  11216. //---------------------------------------------------------------------------
  11217. void __fastcall TCustomScpExplorerForm::Deactivate()
  11218. {
  11219. TForm::Deactivate();
  11220. // E.g. when switching to an internal editor window
  11221. ResetIncrementalSearch();
  11222. }
  11223. //---------------------------------------------------------------------------
  11224. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11225. {
  11226. // When switching to another application
  11227. ResetIncrementalSearch();
  11228. }
  11229. //---------------------------------------------------------------------------
  11230. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11231. {
  11232. ResetIncrementalSearch();
  11233. }
  11234. //---------------------------------------------------------------------------
  11235. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11236. {
  11237. if (FIncrementalSearching <= 0)
  11238. {
  11239. ResetIncrementalSearch();
  11240. }
  11241. }
  11242. //---------------------------------------------------------------------------
  11243. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11244. {
  11245. CountClicksForWindowPrint(this);
  11246. }
  11247. //---------------------------------------------------------------------------
  11248. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11249. {
  11250. CenterReconnectToolbar();
  11251. }
  11252. //---------------------------------------------------------------------------
  11253. void TCustomScpExplorerForm::DoExploreFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11254. {
  11255. if (!FileName.IsEmpty())
  11256. {
  11257. DirView->FocusByName(FileName);
  11258. if (DirView->ItemFocused != NULL)
  11259. {
  11260. DirView->ItemFocused->Selected = true;
  11261. }
  11262. }
  11263. }
  11264. //---------------------------------------------------------------------------
  11265. void __fastcall TCustomScpExplorerForm::ExploreFile(const UnicodeString & FileName)
  11266. {
  11267. DoExploreFile(RemoteDirView, FileName);
  11268. }
  11269. //---------------------------------------------------------------------------
  11270. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11271. {
  11272. if (!FQueueStatusUpdating)
  11273. {
  11274. bool Refresh;
  11275. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11276. {
  11277. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11278. }
  11279. else
  11280. {
  11281. Refresh = (FQueueFileList->GetCount() > 0);
  11282. if (Refresh)
  11283. {
  11284. FQueueFileList->Clear();
  11285. }
  11286. }
  11287. int Count = FQueueFileList->GetCount();
  11288. if (QueueFileList->Items->Count != Count)
  11289. {
  11290. DebugAssert(Refresh);
  11291. QueueFileList->Items->Count = Count;
  11292. }
  11293. if (Refresh)
  11294. {
  11295. QueueFileList->Invalidate();
  11296. }
  11297. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11298. }
  11299. }
  11300. //---------------------------------------------------------------------------
  11301. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11302. {
  11303. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11304. }
  11305. //---------------------------------------------------------------------------
  11306. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11307. {
  11308. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11309. // See TSynchronizeChecklistDialog::UpdateTimer
  11310. if (QueueFileList->Items->Count > 0)
  11311. {
  11312. QueueFileList->Items->Item[0]->MakeVisible(false);
  11313. }
  11314. UpdateQueueFileList();
  11315. }
  11316. //---------------------------------------------------------------------------
  11317. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11318. {
  11319. Active = QueueView3->Focused() || QueueFileList->Focused();
  11320. }
  11321. //---------------------------------------------------------------------------
  11322. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11323. {
  11324. QueueLabelUpdateStatus();
  11325. }
  11326. //---------------------------------------------------------------------------
  11327. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11328. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11329. {
  11330. int State = FQueueFileList->GetState(Item->Index);
  11331. if (State == qfsProcessed)
  11332. {
  11333. Sender->Canvas->Font->Color = clGrayText;
  11334. }
  11335. }
  11336. //---------------------------------------------------------------------------
  11337. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11338. {
  11339. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11340. QueueFileList->Column[0]->Width =
  11341. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11342. }
  11343. //---------------------------------------------------------------------------
  11344. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11345. {
  11346. QueueFileListColumnAutoSize();
  11347. }
  11348. //---------------------------------------------------------------------------
  11349. void __fastcall TCustomScpExplorerForm::CloseApp()
  11350. {
  11351. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11352. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11353. // So we clear the flag here.
  11354. DebugAssert(NonVisualDataModule->Busy);
  11355. NonVisualDataModule->EndBusy();
  11356. try
  11357. {
  11358. Close();
  11359. }
  11360. __finally
  11361. {
  11362. NonVisualDataModule->StartBusy();
  11363. }
  11364. }
  11365. //---------------------------------------------------------------------------
  11366. bool TCustomScpExplorerForm::IsAvailableTerminal(TTerminal * Terminal)
  11367. {
  11368. return TTerminalManager::Instance()->IsAvailableTerminal(Terminal);
  11369. }
  11370. //---------------------------------------------------------------------------
  11371. bool TCustomScpExplorerForm::HasAvailableTerminal()
  11372. {
  11373. return IsAvailableTerminal(Terminal);
  11374. }
  11375. //---------------------------------------------------------------------------
  11376. void TCustomScpExplorerForm::LocalLocalCopy(
  11377. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11378. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11379. {
  11380. DebugFail();
  11381. }
  11382. //---------------------------------------------------------------------------
  11383. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11384. {
  11385. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11386. }
  11387. //---------------------------------------------------------------------------
  11388. void TCustomScpExplorerForm::UpdateTabsSize()
  11389. {
  11390. // 1) Changing tab list triggers the OnResize.
  11391. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11392. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11393. {
  11394. // UpdateTabsCaptionTruncation should be enough
  11395. SessionListChanged(true);
  11396. }
  11397. }
  11398. //---------------------------------------------------------------------------
  11399. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11400. {
  11401. UpdateTabsSize();
  11402. }
  11403. //---------------------------------------------------------------------------
  11404. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11405. {
  11406. if (ASession == ManagedSession)
  11407. {
  11408. UpdateSession(ASession);
  11409. }
  11410. TSessionData * Data = ASession->StateData;
  11411. UnicodeString Result;
  11412. if (Side == osLocal)
  11413. {
  11414. Result = Data->LocalDirectory;
  11415. }
  11416. else if (DebugAlwaysTrue(Side == osOther))
  11417. {
  11418. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11419. }
  11420. return Result;
  11421. }
  11422. //---------------------------------------------------------------------------
  11423. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11424. {
  11425. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11426. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11427. if (Title == Result)
  11428. {
  11429. Result = EmptyStr;
  11430. }
  11431. else
  11432. {
  11433. Result += L"\n";
  11434. }
  11435. return Result;
  11436. }
  11437. //---------------------------------------------------------------------------
  11438. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11439. {
  11440. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11441. if (!ASession->Active)
  11442. {
  11443. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11444. }
  11445. else
  11446. {
  11447. Result += GetSessionPath(ASession, osRemote);
  11448. }
  11449. return Result;
  11450. }
  11451. //---------------------------------------------------------------------------
  11452. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11453. {
  11454. return LoadStr(NEW_REMOTE_TAB_HINT);
  11455. }
  11456. //---------------------------------------------------------------------------
  11457. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11458. {
  11459. if (Index >= 0)
  11460. {
  11461. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11462. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11463. if (TabSession == NULL)
  11464. {
  11465. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11466. if (NewTabTabCaption != TabSheet->Caption)
  11467. {
  11468. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11469. }
  11470. }
  11471. else
  11472. {
  11473. TTerminalManager * Manager = TTerminalManager::Instance();
  11474. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11475. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11476. }
  11477. }
  11478. }
  11479. //---------------------------------------------------------------------------
  11480. typedef std::vector<TListItem *> TListItemsVector;
  11481. struct TCalculateSizeOperation
  11482. {
  11483. TCalculateSizeStats Stats;
  11484. TListItemsVector ListItems;
  11485. size_t Index;
  11486. };
  11487. //---------------------------------------------------------------------------
  11488. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11489. {
  11490. TCalculateSizeOperation CalculateSizeOperation;
  11491. Side = GetSide(Side);
  11492. TCustomDirView * ADirView = DirView(Side);
  11493. bool LocalSide = IsSideLocalBrowser(Side);
  11494. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11495. std::unique_ptr<TStrings> FileList(new TStringList());
  11496. for (int Index = 0; Index < AllFileList->Count; Index++)
  11497. {
  11498. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11499. if (ADirView->ItemIsDirectory(Item))
  11500. {
  11501. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11502. CalculateSizeOperation.ListItems.push_back(Item);
  11503. }
  11504. }
  11505. CalculateSizeOperation.Index = 0;
  11506. __int64 Size = 0;
  11507. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation, &CalculateSizeOperation);
  11508. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11509. FOnFileOperationFinished = DirectorySizeCalculated;
  11510. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation, foCalculateSize);
  11511. TCalculatedSizes CalculatedSizes;
  11512. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11513. if (LocalSide)
  11514. {
  11515. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, Side);
  11516. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11517. }
  11518. else
  11519. {
  11520. TCalculateSizeParams Params;
  11521. Params.Stats = &CalculateSizeOperation.Stats;
  11522. Params.UseCache = true;
  11523. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11524. }
  11525. }
  11526. //---------------------------------------------------------------------------
  11527. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(
  11528. TOperationSide Side, const UnicodeString & FileName, bool Success, bool NotCancelled)
  11529. {
  11530. DebugAssert(FCalculateSizeOperation != NULL);
  11531. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11532. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11533. // optimization
  11534. bool GotExpectedItem =
  11535. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11536. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11537. int Index = -1;
  11538. if (DebugAlwaysTrue(GotExpectedItem))
  11539. {
  11540. Index = FCalculateSizeOperation->Index;
  11541. FCalculateSizeOperation->Index++;
  11542. }
  11543. else
  11544. {
  11545. TListItemsVector::iterator I =
  11546. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11547. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11548. {
  11549. Index = I - FCalculateSizeOperation->ListItems.begin();
  11550. }
  11551. }
  11552. if (DebugAlwaysTrue(Index >= 0) && Success && NotCancelled)
  11553. {
  11554. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11555. ADirView->SetItemCalculatedSize(Item, Size);
  11556. }
  11557. }
  11558. //---------------------------------------------------------------------------
  11559. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11560. {
  11561. Accept = false;
  11562. }
  11563. //---------------------------------------------------------------------------
  11564. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11565. {
  11566. // Send Ctrl+Gray+ to the list view
  11567. TKeyboardState KeyState;
  11568. GetKeyboardState(KeyState);
  11569. TKeyboardState NewKeyState;
  11570. memset(NewKeyState, 0, sizeof(NewKeyState));
  11571. NewKeyState[VK_CONTROL] = 0x81;
  11572. SetKeyboardState(NewKeyState);
  11573. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11574. SetKeyboardState(KeyState);
  11575. }
  11576. //---------------------------------------------------------------------------
  11577. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11578. {
  11579. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11580. }
  11581. //---------------------------------------------------------------------------
  11582. void * TCustomScpExplorerForm::SaveFocus()
  11583. {
  11584. return NULL;
  11585. }
  11586. //---------------------------------------------------------------------------
  11587. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11588. {
  11589. DebugUsedParam(Focus);
  11590. DebugAssert(Focus == NULL);
  11591. }
  11592. //---------------------------------------------------------------------------
  11593. void TCustomScpExplorerForm::IncrementalSearchStart()
  11594. {
  11595. TCustomDirView * ADirView = DirView(osCurrent);
  11596. ADirView->SetFocus();
  11597. if (!FIncrementalSearchState.Searching)
  11598. {
  11599. FIncrementalSearchState.Searching = true;
  11600. FIncrementalSearchState.HaveNext = false;
  11601. DebugAssert(FIncrementalSearchState.Text.IsEmpty());
  11602. ADirView->UpdateStatusBar();
  11603. }
  11604. }
  11605. //---------------------------------------------------------------------------
  11606. void __fastcall TCustomScpExplorerForm::RemoteDirViewThumbnailNeeded(
  11607. TUnixDirView *, TListItem * Item, TRemoteFile * File, const TSize & Size, TBitmap *& Bitmap)
  11608. {
  11609. // though when downloading to temporary folder, encryption should not be a problem
  11610. if (Terminal->IsCapable[fcBackgroundTransfers] &&
  11611. !File->IsDirectory)
  11612. {
  11613. UnicodeString FileName = File->FullFileName;
  11614. TFileMasks::TParams MaskParams;
  11615. MaskParams.Size = File->Size;
  11616. MaskParams.Modification = File->Modification;
  11617. if ((File->Size <= static_cast<__int64>(WinConfiguration->RemoteThumbnailSizeLimit) * 1024) &&
  11618. FRemoteThumbnailMask.Matches(FileName, false, File->IsDirectory, &MaskParams))
  11619. {
  11620. Bitmap = TTerminalManager::Instance()->ThumbnailNeeded(Terminal, Item->Index, File, Size);
  11621. }
  11622. }
  11623. }
  11624. //---------------------------------------------------------------------------
  11625. TThumbnailDownloadQueueItem * TCustomScpExplorerForm::AddThumbnailDownloadQueueItem(TManagedTerminal * ATerminal)
  11626. {
  11627. DebugAssert(ATerminal == Terminal);
  11628. TCopyParamType CopyParam = TemporaryFileCopyParam();
  11629. CopyParam.TransferMode = tmBinary;
  11630. UnicodeString SourceDir = ATerminal->CurrentDirectory;
  11631. UnicodeString TempDir, RootTempDir;
  11632. TemporaryDirectoryForRemoteFiles(SourceDir, CopyParam, true, TempDir, RootTempDir);
  11633. TTerminalQueue * AQueue = TTerminalManager::Instance()->FindQueueForTerminal(ATerminal);
  11634. DebugAssert((Queue == NULL) || (AQueue == Queue)); // we might get here before queue is set
  11635. TThumbnailDownloadQueueItem * QueueItem =
  11636. new TThumbnailDownloadQueueItem(this, Terminal, SourceDir, TempDir, &CopyParam);
  11637. AddQueueItem(AQueue, QueueItem, ATerminal);
  11638. return QueueItem;
  11639. }
  11640. //---------------------------------------------------------------------------
  11641. enum { qccRemoteItemVisible, qccRemoteItemRedraw };
  11642. typedef std::pair<int, UnicodeString> TRemoteItemVisibleData;
  11643. //---------------------------------------------------------------------------
  11644. void TCustomScpExplorerForm::PostThumbnailVisibleQueueQuery(int Index, const UnicodeString & FileName)
  11645. {
  11646. // The queue might be destroyed before the WM_QUEUE_CALLBACK is processed
  11647. TRemoteItemVisibleData * Data = new TRemoteItemVisibleData();
  11648. Data->first = Index;
  11649. Data->second = FileName;
  11650. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemVisible, reinterpret_cast<WPARAM>(Data));
  11651. }
  11652. //---------------------------------------------------------------------------
  11653. void TCustomScpExplorerForm::PostThumbnailDrawRequest(int Index)
  11654. {
  11655. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemRedraw, Index);
  11656. }
  11657. //---------------------------------------------------------------------------
  11658. void TCustomScpExplorerForm::WMQueueCallback(TMessage & Message)
  11659. {
  11660. int Command = Message.WParam;
  11661. if (Command == qccRemoteItemVisible)
  11662. {
  11663. TRemoteItemVisibleData * Data = reinterpret_cast<TRemoteItemVisibleData *>(Message.LParam);
  11664. int Index = Data->first;
  11665. UnicodeString FileName = Data->second;
  11666. delete Data;
  11667. TGuard Guard(Terminal->ThumbnailsSection.get());
  11668. bool Visible = False;
  11669. if (Terminal->ThumbnailsEnabled &&
  11670. // though we should better also disable thumbnails once we switch to different view style
  11671. (RemoteDirView->DirViewStyle == dvsThumbnail))
  11672. {
  11673. // The message might be processed, while we are already loading a different directory
  11674. if ((Index >= 0) &&
  11675. (Index < RemoteDirView->Items->Count))
  11676. {
  11677. TListItem * Item = RemoteDirView->Items->Item[Index];
  11678. Visible =
  11679. (RemoteDirView->ItemFullFileName(Item) == FileName) &&
  11680. ListView_IsItemVisible(RemoteDirView->Handle, Index);
  11681. }
  11682. }
  11683. Terminal->ThumbnailVisible(Index, FileName, Visible);
  11684. }
  11685. else if (Command == qccRemoteItemRedraw)
  11686. {
  11687. int Index = Message.LParam;
  11688. if ((Index >= 0) &&
  11689. (Index < RemoteDirView->Items->Count))
  11690. {
  11691. RemoteDirView->InvalidateItem(RemoteDirView->Items->Item[Index]);
  11692. }
  11693. }
  11694. }
  11695. //---------------------------------------------------------------------------
  11696. void TCustomScpExplorerForm::InitializeRemoteThumbnailMask()
  11697. {
  11698. UnicodeString DefaultRemoteThumbnailMask = L"*.jpg;*.jpeg;*.gif;*.png;*.svg;*.bmp;*.raw;*.ico;*.heic;*.webp";
  11699. UnicodeString RemoteThumbnailMask = WinConfiguration->RemoteThumbnailMask;
  11700. if (RemoteThumbnailMask.IsEmpty() ||
  11701. StartsStr(L"+", RemoteThumbnailMask) || StartsStr(L"-", RemoteThumbnailMask) || StartsStr(L"*", RemoteThumbnailMask))
  11702. {
  11703. std::unique_ptr<TStrings> RemoteThumbnailMasks(new TStringList());
  11704. while (!DefaultRemoteThumbnailMask.IsEmpty())
  11705. {
  11706. RemoteThumbnailMasks->Add(CutToChar(DefaultRemoteThumbnailMask, L';', true));
  11707. }
  11708. RemoteThumbnailMasks.reset(ProcessFeatures(RemoteThumbnailMasks.get(), RemoteThumbnailMask));
  11709. RemoteThumbnailMask = EmptyStr;
  11710. for (int Index = 0; Index < RemoteThumbnailMasks->Count; Index++)
  11711. {
  11712. AddToList(RemoteThumbnailMask, RemoteThumbnailMasks->Strings[Index], L";");
  11713. }
  11714. }
  11715. FRemoteThumbnailMask.Masks = RemoteThumbnailMask;
  11716. }
  11717. //---------------------------------------------------------------------------
  11718. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartLoading(TObject *)
  11719. {
  11720. Terminal->StartLoadingDirectory();
  11721. }
  11722. //---------------------------------------------------------------------------
  11723. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartReading(TObject *)
  11724. {
  11725. Terminal->DisableThumbnails();
  11726. }
  11727. //---------------------------------------------------------------------------
  11728. void TCustomScpExplorerForm::ChangeDirViewStyle(TOperationSide Side, TDirViewStyle DirViewStyle)
  11729. {
  11730. TCustomDirView * ADirView = DirView(Side);
  11731. if (ADirView->DirViewStyle != DirViewStyle)
  11732. {
  11733. if (DirViewStyle == dvsThumbnail)
  11734. {
  11735. if (dynamic_cast<TUnixDirView *>(ADirView) != NULL)
  11736. {
  11737. Configuration->Usage->Inc(L"ThumbnailsRemote");
  11738. }
  11739. else
  11740. {
  11741. Configuration->Usage->Inc(L"ThumbnailsLocal");
  11742. }
  11743. }
  11744. ADirView->DirViewStyle = DirViewStyle;
  11745. UpdateControls();
  11746. }
  11747. }