CustomScpExplorer.cpp 419 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442
  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. FOperationStatusWindow = nullptr;
  261. FOperationStatusWindowTimer = nullptr;
  262. DebugAssert(OnActiveFormChange == nullptr);
  263. OnActiveFormChange = ActiveFormChange;
  264. }
  265. //---------------------------------------------------------------------------
  266. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  267. {
  268. AppLog(L"Destroying main window");
  269. FInvalid = true;
  270. ReleaseHiContrastTheme();
  271. if (FClipboardTerminal != NULL)
  272. {
  273. ClipboardClear(); // implies ClipboardStop
  274. }
  275. // this has to be one of the very first things to do
  276. StopUpdateThread();
  277. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  278. TTerminalManager::Instance()->ScpExplorer = NULL;
  279. delete FCustomCommandLocalFileList;
  280. delete FCustomCommandRemoteFileList;
  281. delete FCustomCommandMenu;
  282. delete FTrayIcon;
  283. FTrayIcon = NULL;
  284. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  285. delete FEditorManager;
  286. ForceCloseLocalEditors();
  287. delete FLocalEditors;
  288. HideFileFindDialog();
  289. if (FDelayedDeletionTimer)
  290. {
  291. DoDelayedDeletion(NULL);
  292. SAFE_DESTROY(FDelayedDeletionTimer);
  293. }
  294. SAFE_DESTROY(FDelayedDeletionList);
  295. // sometimes we do not get DDEnd so the list is not released
  296. SAFE_DESTROY(FDDFileList);
  297. DebugAssert(FSynchronizeController == NULL);
  298. CloseHandle(FDDExtMutex);
  299. FDDExtMutex = NULL;
  300. FreeLibrary(FOle32Library);
  301. FOle32Library = NULL;
  302. FDragMoveCursor = NULL;
  303. DebugAssert(!FErrorList);
  304. if (FEverShown)
  305. {
  306. // when window is never shown (like when running command-line operation),
  307. // particularly window site is not restored correctly (BoundsRect value set
  308. // in RestoreForm gets lost during handle allocation), so we do not want
  309. // it to be stored
  310. AppLog(L"Storing main window configuration");
  311. StoreParams();
  312. }
  313. ManagedSession = NULL;
  314. Queue = NULL;
  315. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  316. NonVisualDataModule->ScpExplorer = NULL;
  317. delete FQueueScrollOnDragOver;
  318. FQueueScrollOnDragOver = NULL;
  319. delete FQueueController;
  320. FQueueController = NULL;
  321. delete FQueueStatusSection;
  322. FQueueStatusSection = NULL;
  323. delete FQueueStatus;
  324. FQueueStatus = NULL;
  325. delete FUserActionTimer;
  326. FUserActionTimer = NULL;
  327. delete FNoteTimer;
  328. delete FNotes;
  329. delete FNoteData;
  330. SAFE_DESTROY(FDocks);
  331. SessionsPageControl->Images = NULL;
  332. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  333. SAFE_DESTROY(FSessionColors);
  334. SAFE_DESTROY(FSessionsDragDropFilesEx);
  335. SAFE_DESTROY(FHistoryMenu[0][0]);
  336. SAFE_DESTROY(FHistoryMenu[0][1]);
  337. SAFE_DESTROY(FHistoryMenu[1][0]);
  338. SAFE_DESTROY(FHistoryMenu[1][1]);
  339. if (FHiddenWindow != NULL)
  340. {
  341. DestroyWindow(FHiddenWindow);
  342. FHiddenWindow = NULL;
  343. }
  344. AppLog(L"Main window destroyed");
  345. }
  346. //---------------------------------------------------------------------------
  347. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  348. {
  349. if (FHiContrastTheme != NULL)
  350. {
  351. ReleaseTBXTheme(FHiContrastTheme);
  352. FHiContrastTheme = NULL;
  353. }
  354. }
  355. //---------------------------------------------------------------------------
  356. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  357. {
  358. std::unique_ptr<TSessionData> Data;
  359. if (!Session.IsEmpty())
  360. {
  361. bool DefaultsOnly;
  362. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  363. }
  364. TTerminalManager * Manager = TTerminalManager::Instance();
  365. for (int Index = 0; Index < Manager->Count; Index++)
  366. {
  367. TTerminal * Terminal = Manager->Sessions[Index];
  368. if (Session.IsEmpty() ||
  369. Manager->IsAvailableTerminalForSite(Terminal, Data.get()))
  370. {
  371. if (Path.IsEmpty())
  372. {
  373. Terminal->ClearCaches();
  374. }
  375. else
  376. {
  377. Terminal->DirectoryModified(Path, true);
  378. }
  379. }
  380. }
  381. // We should flag a pending refresh for the background terminals or busy foreground terminals
  382. if (HasAvailableTerminal() &&
  383. CanCommandLineFromAnotherInstance() &&
  384. (Session.IsEmpty() || Manager->IsAvailableTerminalForSite(Terminal, Data.get())) &&
  385. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  386. {
  387. Terminal->ReloadDirectory();
  388. }
  389. }
  390. //---------------------------------------------------------------------------
  391. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  392. {
  393. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  394. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  395. size_t MessageSize = sizeof(TCopyDataMessage);
  396. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  397. if (Result)
  398. {
  399. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  400. Result = (Message.Version == TCopyDataMessage::Version1);
  401. if (Result)
  402. {
  403. switch (Message.Command)
  404. {
  405. case TCopyDataMessage::CommandCanCommandLine:
  406. Result = CanCommandLineFromAnotherInstance();
  407. if (Result)
  408. {
  409. AppLog(L"Can process command-line from other instance");
  410. }
  411. else
  412. {
  413. AppLog(L"Cannot process command-line from other instance");
  414. }
  415. break;
  416. case TCopyDataMessage::CommandCommandLine:
  417. {
  418. UnicodeString CommandLine(Message.Data.CommandLine);
  419. Result = CommandLineFromAnotherInstance(CommandLine);
  420. }
  421. break;
  422. case TCopyDataMessage::RefreshPanel:
  423. RefreshPanel(Message.Data.Refresh.Session, Message.Data.Refresh.Path);
  424. break;
  425. case TCopyDataMessage::MainWindowCheck:
  426. Result = true;
  427. break;
  428. default:
  429. Result = false;
  430. break;
  431. }
  432. }
  433. }
  434. Message.Result = Result ? 1 : 0;
  435. }
  436. //---------------------------------------------------------------------------
  437. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  438. {
  439. WNDCLASS WindowClass = {};
  440. WindowClass.lpfnWndProc = DefWindowProc;
  441. WindowClass.hInstance = HInstance;
  442. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  443. FHiddenWindow = NULL;
  444. if (RegisterClass(&WindowClass))
  445. {
  446. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  447. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  448. }
  449. }
  450. //---------------------------------------------------------------------------
  451. bool __fastcall TCustomScpExplorerForm::CanConsole()
  452. {
  453. return
  454. HasAvailableTerminal() &&
  455. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  456. }
  457. //---------------------------------------------------------------------------
  458. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  459. {
  460. bool Result = Visible && !NonVisualDataModule->Busy;
  461. return Result;
  462. }
  463. //---------------------------------------------------------------------------
  464. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  465. const UnicodeString & CommandLine)
  466. {
  467. TProgramParams Params(CommandLine);
  468. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  469. if (Result)
  470. {
  471. NonVisualDataModule->StartBusy();
  472. try
  473. {
  474. // this action is initiated from another process,
  475. // so it's likely that our window is not visible,
  476. // and user won't see what is going on
  477. Application->BringToFront();
  478. // reload sessions as we may be asked to open a session
  479. // just stored by another instance
  480. StoredSessions->Reload();
  481. UnicodeString SessionName = Params.Param[1];
  482. std::unique_ptr<TObjectList> DataList(new TObjectList());
  483. try
  484. {
  485. UnicodeString DownloadFile; // unused
  486. int Flags = GetCommandLineParseUrlFlags(&Params);
  487. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  488. }
  489. catch (EAbort &)
  490. {
  491. // Happens when opening session in PuTTY and in other situations,
  492. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  493. // to process the command-line on its own (or to pass it to yet another instance)
  494. }
  495. if (DataList->Count > 0)
  496. {
  497. TTerminalManager * Manager = TTerminalManager::Instance();
  498. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  499. }
  500. }
  501. __finally
  502. {
  503. NonVisualDataModule->EndBusy();
  504. }
  505. }
  506. return Result;
  507. }
  508. //---------------------------------------------------------------------------
  509. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  510. {
  511. TManagedTerminal * Result;
  512. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  513. {
  514. Result = FManagedSession;
  515. }
  516. else
  517. {
  518. Result = NULL;
  519. }
  520. return Result;
  521. }
  522. //---------------------------------------------------------------------------
  523. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  524. {
  525. if (FManagedSession != value)
  526. {
  527. TWindowLock Lock(this);
  528. SessionChanging();
  529. DoSetManagedSession(value, false);
  530. }
  531. }
  532. //---------------------------------------------------------------------------
  533. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  534. {
  535. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  536. FManagedSession = value;
  537. {
  538. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect, false);
  539. TAutoFlag SessionChangingFlag(FSessionChanging);
  540. SessionChanged(Replace);
  541. }
  542. if (Terminal != NULL)
  543. {
  544. TransferPresetAutoSelect();
  545. }
  546. // Update app and tab titles, prevented above by FSessionChanging.
  547. UpdateControls();
  548. }
  549. //---------------------------------------------------------------------------
  550. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  551. {
  552. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  553. DoSetManagedSession(value, true);
  554. }
  555. //---------------------------------------------------------------------------
  556. void __fastcall TCustomScpExplorerForm::SessionChanging()
  557. {
  558. if (ManagedSession != NULL)
  559. {
  560. UpdateSession(ManagedSession);
  561. }
  562. }
  563. //---------------------------------------------------------------------------
  564. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  565. {
  566. if (ManagedSession != NULL)
  567. {
  568. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  569. }
  570. if (!TTerminalManager::Instance()->Updating)
  571. {
  572. SessionListChanged();
  573. }
  574. if (Terminal != NULL)
  575. {
  576. TObject * State = NULL;
  577. if (WinConfiguration->PreservePanelState)
  578. {
  579. State = Terminal->RemoteExplorerState;
  580. DirView(osRemote)->AnnounceState(State);
  581. }
  582. try
  583. {
  584. if (Replaced)
  585. {
  586. RemoteDirView->ReplaceTerminal(Terminal);
  587. }
  588. else
  589. {
  590. RemoteDirView->Terminal = Terminal;
  591. }
  592. if (Terminal->Active)
  593. {
  594. Terminal->RefreshDirectory();
  595. }
  596. if (State != NULL)
  597. {
  598. DirView(osRemote)->RestoreState(State);
  599. }
  600. }
  601. __finally
  602. {
  603. DirView(osRemote)->AnnounceState(NULL);
  604. }
  605. }
  606. else
  607. {
  608. RemoteDirView->Terminal = NULL;
  609. }
  610. InitStatusBar();
  611. UpdateTransferList();
  612. // Update panels Enable state before refreshing the labels
  613. UpdateControls();
  614. }
  615. //---------------------------------------------------------------------------
  616. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  617. {
  618. if (Queue != value)
  619. {
  620. if (FQueue != NULL)
  621. {
  622. FQueue->OnListUpdate = NULL;
  623. FQueue->OnQueueItemUpdate = NULL;
  624. }
  625. FQueue = value;
  626. if (FQueue != NULL)
  627. {
  628. DebugAssert(FQueue->OnListUpdate == NULL);
  629. FQueue->OnListUpdate = QueueListUpdate;
  630. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  631. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  632. }
  633. QueueChanged();
  634. }
  635. }
  636. //---------------------------------------------------------------------------
  637. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  638. TListItem * Item)
  639. {
  640. if (FQueueActedItem == Item)
  641. {
  642. FQueueActedItem = NULL;
  643. if ((QueueView3->PopupMenu != NULL) &&
  644. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  645. {
  646. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  647. ReleaseCapture();
  648. }
  649. }
  650. if (Item->Data == FPendingQueueActionItem)
  651. {
  652. FPendingQueueActionItem = NULL;
  653. }
  654. }
  655. //---------------------------------------------------------------------------
  656. bool TCustomScpExplorerForm::IsAnythingQueued()
  657. {
  658. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  659. }
  660. //---------------------------------------------------------------------------
  661. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  662. {
  663. {
  664. TGuard Guard(FQueueStatusSection);
  665. FQueueStatusInvalidated = false;
  666. if (FQueue != NULL)
  667. {
  668. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  669. }
  670. }
  671. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  672. {
  673. FMaxQueueLength = FQueueStatus->Count;
  674. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  675. }
  676. {
  677. TAutoFlag Flag(FQueueStatusUpdating);
  678. FQueueController->UpdateQueueStatus(FQueueStatus);
  679. }
  680. UpdateQueueFileList();
  681. SetQueueProgress();
  682. UpdateQueueView();
  683. bool IsEmpty = !IsAnythingQueued();
  684. if (IsEmpty && (Terminal != NULL))
  685. {
  686. TOnceDoneOperation OnceDoneOperation =
  687. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  688. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  689. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  690. {
  691. FQueue->Enabled = false;
  692. }
  693. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  694. {
  695. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  696. }
  697. }
  698. }
  699. //---------------------------------------------------------------------------
  700. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  701. {
  702. UnicodeString Result;
  703. if (FQueueStatus != NULL)
  704. {
  705. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  706. {
  707. TFileOperationProgressType * ProgressData =
  708. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  709. if ((ProgressData != NULL) && ProgressData->InProgress)
  710. {
  711. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  712. }
  713. }
  714. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  715. {
  716. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  717. }
  718. }
  719. return Result;
  720. }
  721. //---------------------------------------------------------------------------
  722. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  723. {
  724. ComponentVisible[fcQueueView] =
  725. !IsLocalBrowserMode() &&
  726. ((WinConfiguration->QueueView.Show == qvShow) ||
  727. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  728. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  729. }
  730. //---------------------------------------------------------------------------
  731. void __fastcall TCustomScpExplorerForm::QueueChanged()
  732. {
  733. if (FQueueStatus != NULL)
  734. {
  735. // UpdateFileList implementation relies on the status being recreated when session changes
  736. delete FQueueStatus;
  737. FQueueStatus = NULL;
  738. }
  739. UpdateQueueStatus(true);
  740. }
  741. //---------------------------------------------------------------------------
  742. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  743. {
  744. if (FQueue == Queue)
  745. {
  746. FQueueStatusInvalidated = true;
  747. }
  748. }
  749. //---------------------------------------------------------------------------
  750. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  751. TQueueItem * Item)
  752. {
  753. if (FQueue == Queue)
  754. {
  755. TGuard Guard(FQueueStatusSection);
  756. // this may be running in parallel with QueueChanged
  757. if (FQueueStatus != NULL)
  758. {
  759. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  760. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  761. {
  762. FRefreshLocalDirectory = (QueueItem == NULL) ||
  763. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  764. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  765. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  766. }
  767. if (QueueItem != NULL)
  768. {
  769. QueueItem->UserData = (void*)true;
  770. FQueueItemInvalidated = true;
  771. }
  772. }
  773. }
  774. }
  775. //---------------------------------------------------------------------------
  776. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  777. {
  778. // during standalone editing, we have no way to see/control queue,
  779. // so we have to always popup prompts automatically
  780. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  781. }
  782. //---------------------------------------------------------------------------
  783. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  784. {
  785. if (FQueueStatus != NULL)
  786. {
  787. bool QueueAutoPopup = IsQueueAutoPopup();
  788. bool NeedRefresh = FQueueController->NeedRefresh();
  789. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  790. FQueueItemInvalidated = false;
  791. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  792. bool Updated = false;
  793. TQueueItemProxy * QueueItem;
  794. bool WasUserAction;
  795. for (int Index = 0; Index < Limit; Index++)
  796. {
  797. bool Update = false;
  798. QueueItem = FQueueStatus->Items[Index];
  799. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  800. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  801. (FPendingQueueActionItem == NULL))
  802. {
  803. FPendingQueueActionItem = QueueItem;
  804. FUserActionTimer->Enabled = true;
  805. }
  806. if ((bool)QueueItem->UserData)
  807. {
  808. QueueItem->UserData = (void*)false;
  809. QueueItem->Update();
  810. Updated = true;
  811. Update = true;
  812. }
  813. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  814. {
  815. Update = true;
  816. }
  817. if (Update)
  818. {
  819. FQueueController->RefreshQueueItem(QueueItem);
  820. }
  821. }
  822. if (Updated)
  823. {
  824. NonVisualDataModule->UpdateNonVisibleActions();
  825. SetQueueProgress();
  826. UpdateQueueFileList();
  827. }
  828. }
  829. }
  830. //---------------------------------------------------------------------------
  831. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  832. {
  833. if (FTaskbarList != NULL)
  834. {
  835. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  836. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  837. }
  838. }
  839. //---------------------------------------------------------------------------
  840. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  841. {
  842. if (Progress >= 0)
  843. {
  844. if (FTaskbarList != NULL)
  845. {
  846. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  847. }
  848. }
  849. else
  850. {
  851. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  852. }
  853. }
  854. //---------------------------------------------------------------------------
  855. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  856. {
  857. int OverallProgress;
  858. // FProgressForm is null when this is called from SetQueueProgress
  859. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  860. {
  861. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  862. }
  863. else if (!ProgressData->IsIndeterminate())
  864. {
  865. OverallProgress = ProgressData->OverallProgress();
  866. }
  867. else
  868. {
  869. OverallProgress = -1;
  870. }
  871. SetTaskbarListProgressValue(OverallProgress);
  872. }
  873. //---------------------------------------------------------------------------
  874. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  875. {
  876. TTerminalManager::Instance()->QueueStatusUpdated();
  877. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  878. {
  879. // Do not animate task bar button, when items are queued, but processing is disabled
  880. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  881. {
  882. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  883. {
  884. TFileOperationProgressType * ProgressData = NULL;
  885. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  886. {
  887. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  888. }
  889. if ((ProgressData != NULL) &&
  890. ProgressData->InProgress)
  891. {
  892. SetTaskbarListProgressValue(ProgressData);
  893. }
  894. else
  895. {
  896. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  897. }
  898. }
  899. else
  900. {
  901. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  902. }
  903. }
  904. else
  905. {
  906. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  907. }
  908. }
  909. UpdateQueueLabel();
  910. }
  911. //---------------------------------------------------------------------------
  912. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  913. {
  914. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  915. if (FQueueStatus != NULL)
  916. {
  917. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  918. if (ActiveAndPendingPrimaryCount > 0)
  919. {
  920. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  921. }
  922. }
  923. QueueLabel->Caption = Caption;
  924. }
  925. //---------------------------------------------------------------------------
  926. void TCustomScpExplorerForm::CheckStoreTransition()
  927. {
  928. if (WinConfiguration->StoreTransition == stInit)
  929. {
  930. if (IsUWP())
  931. {
  932. WinConfiguration->StoreTransition = stStoreFresh;
  933. AppLog(L"Fresh UWP/store installation");
  934. }
  935. else
  936. {
  937. WinConfiguration->StoreTransition = stStandard;
  938. AppLog(L"Fresh standard installation");
  939. }
  940. }
  941. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  942. {
  943. WinConfiguration->StoreTransition = stStoreMigrated;
  944. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  945. AppLog(L"Standard installation migrated to store installation");
  946. }
  947. if (WinConfiguration->StoreTransition == stStoreMigrated)
  948. {
  949. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  950. Toolbar->Parent = MessageDock;
  951. Toolbar->FullSize = true;
  952. Toolbar->Color = Application->HintColor;
  953. TTBXLabelItem * LabelItem;
  954. LabelItem = new TTBXLabelItem(Toolbar);
  955. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  956. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  957. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  958. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  959. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  960. Toolbar->Items->Add(LabelItem);
  961. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  962. LinkItem->FontSettings->Color = GetLightLinkColor(); // the background is not themed yet
  963. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  964. LinkItem->OnClick = StoreTransitionLinkClick;
  965. Toolbar->Items->Add(LinkItem);
  966. AddMenuSeparator(Toolbar->Items);
  967. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  968. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  969. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  970. CloseItem->OnClick = StoreTransitionCloseClick;
  971. Toolbar->Items->Add(CloseItem);
  972. GiveTBItemPriority(CloseItem);
  973. }
  974. }
  975. //---------------------------------------------------------------------------
  976. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  977. {
  978. ShowHelp(HELP_STORE_TRANSITION);
  979. }
  980. //---------------------------------------------------------------------------
  981. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  982. {
  983. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  984. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  985. delete Toolbar;
  986. WinConfiguration->StoreTransition = stStoreAcknowledged;
  987. UpdateControls();
  988. }
  989. //---------------------------------------------------------------------------
  990. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  991. {
  992. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  993. static_cast<TComponent*>(GetComponent(fcTransferList)));
  994. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  995. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  996. TransferList->Strings->BeginUpdate();
  997. try
  998. {
  999. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  1000. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  1001. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  1002. if (FTransferDropDownHint.IsEmpty())
  1003. {
  1004. FTransferDropDownHint = TransferDropDown->Hint;
  1005. }
  1006. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1007. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1008. TransferDropDown->Text = StripHotkey(Name);
  1009. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1010. (FTransferDropDownHint, StripHotkey(Name),
  1011. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1012. FLAGMASK(HasAvailableTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1013. // update the label, otherwise when it is updated only on the first draw
  1014. // of the list, it is drawn "bold" for some reason
  1015. FTransferListHoverIndex = TransferList->ItemIndex;
  1016. UpdateTransferLabel();
  1017. }
  1018. __finally
  1019. {
  1020. TransferList->Strings->EndUpdate();
  1021. }
  1022. }
  1023. //---------------------------------------------------------------------------
  1024. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1025. {
  1026. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1027. DebugAssert(Toolbar != NULL);
  1028. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1029. }
  1030. //---------------------------------------------------------------------------
  1031. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1032. {
  1033. TForm::UpdateActions();
  1034. if (ComponentVisible[fcCustomCommandsBand])
  1035. {
  1036. UpdateCustomCommandsToolbar();
  1037. }
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1041. {
  1042. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1043. }
  1044. //---------------------------------------------------------------------------
  1045. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1046. {
  1047. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1048. {
  1049. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1050. // Without this, the panel turns gray and unused part of header turns black
  1051. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1052. }
  1053. }
  1054. //---------------------------------------------------------------------------
  1055. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1056. {
  1057. Color = GetBtnFaceColor();
  1058. DebugAssert(Configuration && RemoteDirView);
  1059. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1060. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1061. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1062. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1063. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1064. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1065. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1066. UpdateRowSelect(RemoteDirView);
  1067. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1068. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1069. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1070. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1071. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1072. UpdateSessionsPageControlHeight();
  1073. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1074. UpdateToolbarDisplayMode();
  1075. UpdateTransferList();
  1076. if (Terminal != NULL)
  1077. {
  1078. TransferPresetAutoSelect();
  1079. }
  1080. UpdateQueueView();
  1081. UpdateControls();
  1082. // this can be called even before constuctor finishes.
  1083. if (FEditorManager != NULL)
  1084. {
  1085. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1086. }
  1087. // this can be called even before constuctor finishes.
  1088. if (FLocalEditors != NULL)
  1089. {
  1090. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1091. {
  1092. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1093. }
  1094. }
  1095. if (ComponentVisible[fcCustomCommandsBand])
  1096. {
  1097. UpdateCustomCommandsToolbar();
  1098. }
  1099. // show only when keeping queue items forever,
  1100. // otherwise, it's enough to have it in the context menu
  1101. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1102. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1103. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1104. {
  1105. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1106. FFileColorsCurrent = WinConfiguration->FileColors;
  1107. FileColorsChanged();
  1108. }
  1109. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1110. (FSessionColors != NULL))
  1111. {
  1112. SessionListChanged();
  1113. }
  1114. if (GlyphsModule->LargerToolbar != WinConfiguration->LargerToolbar)
  1115. {
  1116. GlyphsModule->LargerToolbar = WinConfiguration->LargerToolbar;
  1117. if (FSessionColors != NULL)
  1118. {
  1119. RegenerateSessionColorsImageList();
  1120. UpdateSessionsPageControlHeight();
  1121. }
  1122. }
  1123. }
  1124. //---------------------------------------------------------------------------
  1125. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1126. {
  1127. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1128. DirView->Invalidate();
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1132. {
  1133. DoFileColorsChanged(RemoteDirView);
  1134. }
  1135. //---------------------------------------------------------------------------
  1136. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1137. const UnicodeString DebugUsedArg(FileName), TEditedFileData * /*Data*/, TObject * Token,
  1138. void * /*Arg*/)
  1139. {
  1140. if (Token != NULL)
  1141. {
  1142. TForm * Editor = dynamic_cast<TForm*>(Token);
  1143. DebugAssert(Editor != NULL);
  1144. ReconfigureEditorForm(Editor);
  1145. }
  1146. }
  1147. //---------------------------------------------------------------------------
  1148. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1149. {
  1150. WinConfiguration->DDTransferConfirmation = asOn;
  1151. }
  1152. //---------------------------------------------------------------------------
  1153. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1154. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1155. {
  1156. // noop
  1157. }
  1158. //---------------------------------------------------------------------------
  1159. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1160. {
  1161. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1162. }
  1163. //---------------------------------------------------------------------------
  1164. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1165. {
  1166. if (DoNotShowAgain)
  1167. {
  1168. if (DragDrop)
  1169. {
  1170. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1171. {
  1172. PopupTrayBalloon(
  1173. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1174. }
  1175. WinConfiguration->DDTransferConfirmation = asOff;
  1176. }
  1177. else
  1178. {
  1179. WinConfiguration->ConfirmTransferring = false;
  1180. }
  1181. }
  1182. else
  1183. {
  1184. // User explicitly unchecked "do not show again",
  1185. // so show him the dialog the next time
  1186. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1187. {
  1188. WinConfiguration->DDTransferConfirmation = asOn;
  1189. }
  1190. }
  1191. }
  1192. //---------------------------------------------------------------------------
  1193. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1194. TTransferDirection Direction, TTransferType Type, bool Temp,
  1195. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1196. bool Confirm, bool DragDrop, int Options)
  1197. {
  1198. bool Result = true;
  1199. DebugAssert(HasAvailableTerminal());
  1200. // these parameters are known in advance
  1201. int Params =
  1202. FLAGMASK(Type == ttMove, cpDelete);
  1203. bool ToTemp = (Temp && (Direction == tdToLocal));
  1204. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1205. {
  1206. bool DisableNewerOnly =
  1207. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1208. ToTemp;
  1209. Options |=
  1210. FLAGMASK(ToTemp, coTemp) |
  1211. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1212. coDoNotShowAgain;
  1213. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1214. int CopyParamAttrs = (Direction == tdToRemote ?
  1215. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1216. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1217. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1218. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1219. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1220. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1221. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1222. if (Result)
  1223. {
  1224. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1225. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1226. }
  1227. }
  1228. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1229. {
  1230. Configuration->Usage->Inc(L"TransfersOnBackground");
  1231. // these parameter are known only after transfer dialog
  1232. Params |=
  1233. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1234. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1235. Result = false;
  1236. ClearTransferSourceSelection(Direction);
  1237. }
  1238. return Result;
  1239. }
  1240. //---------------------------------------------------------------------------
  1241. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1242. {
  1243. if (FOnFileOperationFinished != NULL)
  1244. {
  1245. FOnFileOperationFinished(Side, UnicodeString(), true, true);
  1246. }
  1247. else
  1248. {
  1249. if (HasDirView[Side])
  1250. {
  1251. DirView(Side)->SelectAll(smNone);
  1252. }
  1253. }
  1254. }
  1255. //---------------------------------------------------------------------------
  1256. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1257. {
  1258. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1259. ClearOperationSelection(Side);
  1260. }
  1261. //---------------------------------------------------------------------------
  1262. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1263. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1264. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1265. int Params)
  1266. {
  1267. DebugAssert(Queue != NULL);
  1268. TQueueItem * QueueItem;
  1269. if (Direction == tdToRemote)
  1270. {
  1271. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1272. QueueItem =
  1273. new TUploadQueueItem(
  1274. Terminal, FileList, TargetDirectory, &CopyParam, Params, CopyParam.QueueParallel);
  1275. }
  1276. else
  1277. {
  1278. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1279. QueueItem =
  1280. new TDownloadQueueItem(
  1281. Terminal, FileList, TargetDirectory, &CopyParam, Params, CopyParam.QueueParallel);
  1282. }
  1283. AddQueueItem(Queue, QueueItem, Terminal);
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1287. {
  1288. if (Queue->IsEmpty)
  1289. {
  1290. Terminal->QueueOperationStart = Now();
  1291. }
  1292. Queue->AddItem(QueueItem);
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1296. {
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. void __fastcall TCustomScpExplorerForm::InitControls()
  1300. {
  1301. DebugAssert(FDocks != NULL);
  1302. for (int Index = 0; Index < ComponentCount; Index++)
  1303. {
  1304. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1305. if ((Dock != NULL) && (Dock->Tag == 0))
  1306. {
  1307. FDocks->Add(Dock);
  1308. }
  1309. }
  1310. CollectItemsWithTextDisplayMode(this);
  1311. }
  1312. //---------------------------------------------------------------------------
  1313. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1314. {
  1315. ConfigurationChanged();
  1316. QueuePanel->Height =
  1317. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1318. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1319. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1320. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1321. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1322. QueueFileList->Height =
  1323. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1324. if (QueueFileList->Visible)
  1325. {
  1326. AdjustQueueLayout();
  1327. }
  1328. UpdateCustomCommandsToolbar();
  1329. }
  1330. //---------------------------------------------------------------------------
  1331. void __fastcall TCustomScpExplorerForm::StoreParams()
  1332. {
  1333. int APixelsPerInch = GetControlPixelsPerInch(this);
  1334. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1335. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1336. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1337. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1338. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1339. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1340. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1341. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. void __fastcall TCustomScpExplorerForm::Loaded()
  1345. {
  1346. // Loaded is called in more deterministic moment than previously used CreateParams
  1347. if (!FFormRestored)
  1348. {
  1349. FFormRestored = true;
  1350. RestoreFormParams();
  1351. }
  1352. TForm::Loaded();
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1356. {
  1357. DebugAssert(FDocks != NULL);
  1358. for (int Index = 0; Index < FDocks->Count; Index++)
  1359. {
  1360. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1361. }
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1365. {
  1366. SetDockAllowDrag(true);
  1367. while (!ButtonsStr.IsEmpty())
  1368. {
  1369. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1370. UnicodeString Name = CutToChar(S, L'=', true);
  1371. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1372. {
  1373. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1374. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1375. {
  1376. while (!S.IsEmpty())
  1377. {
  1378. UnicodeString S2 = CutToChar(S, L',', true);
  1379. UnicodeString Name = CutToChar(S2, L':', true);
  1380. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1381. {
  1382. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1383. if (SameText(GetToolbarItemName(Item), Name))
  1384. {
  1385. // forward compatibility
  1386. UnicodeString S3 = CutToChar(S2, L':', true);
  1387. bool Visible = StrToIntDef(S3, 0);
  1388. Item->Visible = Visible;
  1389. }
  1390. }
  1391. }
  1392. }
  1393. }
  1394. }
  1395. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1396. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1397. }
  1398. //---------------------------------------------------------------------------
  1399. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1400. {
  1401. UnicodeString Result;
  1402. SetDockAllowDrag(true);
  1403. Result = ::GetToolbarsLayoutStr(this);
  1404. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1405. return Result;
  1406. }
  1407. //---------------------------------------------------------------------------
  1408. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1409. {
  1410. UnicodeString Result;
  1411. if (Item->Action != NULL)
  1412. {
  1413. Result = Item->Action->Name;
  1414. Result = RemoveSuffix(Result, L"Action", true);
  1415. }
  1416. else
  1417. {
  1418. Result = Item->Name;
  1419. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1420. Result = RemoveSuffix(Result, L"Item", true);
  1421. }
  1422. return Result;
  1423. }
  1424. //---------------------------------------------------------------------------
  1425. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1426. {
  1427. UnicodeString Result;
  1428. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1429. {
  1430. UnicodeString ToolbarStr;
  1431. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1432. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1433. {
  1434. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1435. {
  1436. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1437. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1438. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1439. // and save the changes here only.
  1440. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1441. {
  1442. UnicodeString Name = GetToolbarItemName(Item);
  1443. DebugAssert(Name.Pos(L"TBX") == 0);
  1444. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1445. }
  1446. }
  1447. }
  1448. if (!ToolbarStr.IsEmpty())
  1449. {
  1450. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1451. }
  1452. }
  1453. return Result;
  1454. }
  1455. //---------------------------------------------------------------------------
  1456. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1457. {
  1458. DebugAssert(FProgressForm == NULL);
  1459. bool AllowSkip = HasAvailableTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1460. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1461. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1462. FProgressForm->DeleteLocalToRecycleBin =
  1463. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1464. FProgressForm->DeleteRemoteToRecycleBin =
  1465. HasAvailableTerminal() &&
  1466. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1467. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1468. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1469. LockWindow();
  1470. // Actually, do not know what hides the progress once the operation finishes
  1471. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1472. SetTaskbarListProgressState(TBPF_NORMAL);
  1473. }
  1474. //---------------------------------------------------------------------------
  1475. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1476. {
  1477. UnlockWindow();
  1478. SAFE_DESTROY(FProgressForm);
  1479. SetQueueProgress();
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1483. TFileOperationProgressType & ProgressData)
  1484. {
  1485. // Download to temporary local directory
  1486. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1487. {
  1488. bool Continue = true;
  1489. FPendingTempSpaceWarn = false;
  1490. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1491. if (!Continue)
  1492. {
  1493. Abort();
  1494. }
  1495. }
  1496. // operation is being executed and we still didn't show up progress form
  1497. if (ProgressData.InProgress && !FProgressForm)
  1498. {
  1499. CreateProgressForm(NULL);
  1500. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1501. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1502. }
  1503. // operation is finished (or terminated), so we hide progress form
  1504. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1505. {
  1506. DestroyProgressForm();
  1507. if (ProgressData.Operation == foCalculateSize)
  1508. {
  1509. // When calculating size before transfer, the abort caused by
  1510. // cancel flag set due to "MoveToQueue" below,
  1511. // is not propagated back to us in ExecuteFileOperation,
  1512. // as it is silently swallowed.
  1513. // So we explicitly (re)throw it here.
  1514. if (FMoveToQueue)
  1515. {
  1516. Abort();
  1517. }
  1518. }
  1519. else
  1520. {
  1521. if ((ProgressData.Cancel == csContinue) &&
  1522. !FAutoOperation)
  1523. {
  1524. OperationComplete(ProgressData.StartTime);
  1525. }
  1526. }
  1527. }
  1528. if (FProgressForm &&
  1529. // Can happen only during synchronization, when ending one of the operations
  1530. ProgressData.InProgress)
  1531. {
  1532. FProgressForm->SetProgressData(ProgressData);
  1533. DebugAssert(ProgressData.InProgress);
  1534. SetTaskbarListProgressValue(&ProgressData);
  1535. if (FProgressForm->Cancel > csContinue)
  1536. {
  1537. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1538. if (FProgressForm->Cancel == csCancelFile)
  1539. {
  1540. FProgressForm->ClearCancel();
  1541. }
  1542. // cancel cancels even the move
  1543. FMoveToQueue = false;
  1544. }
  1545. else if (FProgressForm->MoveToQueue)
  1546. {
  1547. FMoveToQueue = true;
  1548. ProgressData.SetCancelAtLeast(csCancel);
  1549. }
  1550. if ((FTransferResumeList != NULL) &&
  1551. ProgressData.InProgress &&
  1552. ProgressData.IsTransfer() &&
  1553. !ProgressData.FullFileName.IsEmpty())
  1554. {
  1555. if ((FTransferResumeList->Count == 0) ||
  1556. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1557. {
  1558. // note that we do not recognize directories from files here
  1559. FTransferResumeList->Add(ProgressData.FullFileName);
  1560. }
  1561. }
  1562. }
  1563. }
  1564. //---------------------------------------------------------------------------
  1565. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1566. const TDateTime & StartTime)
  1567. {
  1568. if (GUIConfiguration->BeepOnFinish &&
  1569. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1570. {
  1571. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1572. DWORD Sound;
  1573. if (!ExtractFileExt(BeepSound).IsEmpty())
  1574. {
  1575. Sound = SND_FILENAME;
  1576. }
  1577. else
  1578. {
  1579. Sound = SND_ALIAS;
  1580. }
  1581. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1582. }
  1583. }
  1584. //---------------------------------------------------------------------------
  1585. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1586. TFileOperationProgressType & ProgressData)
  1587. {
  1588. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1589. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1590. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1591. FileOperationProgress(ProgressData);
  1592. }
  1593. //---------------------------------------------------------------------------
  1594. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1595. {
  1596. UnicodeString Result;
  1597. if (FProgressForm != NULL)
  1598. {
  1599. Result = FProgressForm->ProgressStr();
  1600. }
  1601. return Result;
  1602. }
  1603. //---------------------------------------------------------------------------
  1604. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1605. bool DragDrop)
  1606. {
  1607. return (!DragDrop && (DropSourceControl == NULL)) ||
  1608. (DropSourceControl == DirView(osOther));
  1609. }
  1610. //---------------------------------------------------------------------------
  1611. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1612. {
  1613. TCustomDirView * ADirView = DirView(Side);
  1614. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1615. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1616. // this can happen when local drive is unplugged in the middle of the operation
  1617. if (Item != NULL)
  1618. {
  1619. if (Unselect)
  1620. {
  1621. Item->Selected = false;
  1622. }
  1623. ADirView->MakeProgressVisible(Item);
  1624. }
  1625. return Item;
  1626. }
  1627. //---------------------------------------------------------------------------
  1628. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1629. TFileOperation Operation, TOperationSide Side,
  1630. bool /*Temp*/, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1631. TOnceDoneOperation & OnceDoneOperation)
  1632. {
  1633. if (!FAutoOperation)
  1634. {
  1635. // no selection on "/upload", form serves only as event handler
  1636. // (it is not displayed)
  1637. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1638. ((Operation == FPrimaryOperation) ||
  1639. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1640. {
  1641. TOperationSide DViewSide;
  1642. if ((FProgressSide != osCurrent) &&
  1643. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1644. {
  1645. // assume the operation is over the focused panel
  1646. DViewSide = FProgressSide;
  1647. }
  1648. else
  1649. {
  1650. DViewSide = Side;
  1651. }
  1652. if (FOnFileOperationFinished != NULL)
  1653. {
  1654. FOnFileOperationFinished(DViewSide, FileName, Success, NotCancelled);
  1655. }
  1656. else
  1657. {
  1658. VisualiseOperationFinished(DViewSide, FileName, Success && NotCancelled);
  1659. }
  1660. }
  1661. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1662. {
  1663. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1664. {
  1665. if (Side == osLocal)
  1666. {
  1667. Configuration->Usage->Inc(L"UploadedFiles");
  1668. }
  1669. else
  1670. {
  1671. Configuration->Usage->Inc(L"DownloadedFiles");
  1672. }
  1673. }
  1674. }
  1675. }
  1676. if (Success && (FSynchronizeController != NULL))
  1677. {
  1678. DebugAssert(!IsSideLocalBrowser(osRemote));
  1679. if (Operation == foCopy)
  1680. {
  1681. DebugAssert(Side == osLocal);
  1682. FSynchronizeController->LogOperation(soUpload, FileName);
  1683. }
  1684. else if (Operation == foDelete)
  1685. {
  1686. DebugAssert(Side == osRemote);
  1687. FSynchronizeController->LogOperation(soDelete, FileName);
  1688. }
  1689. }
  1690. if (FProgressForm)
  1691. {
  1692. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1693. }
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1697. TFileOperation Operation, TOperationSide Side,
  1698. bool Temp, const UnicodeString & FileName, bool Success, bool NotCancelled,
  1699. TOnceDoneOperation & OnceDoneOperation)
  1700. {
  1701. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1702. DoOperationFinished(Operation, Side, Temp, FileName, Success, NotCancelled, OnceDoneOperation);
  1703. }
  1704. //---------------------------------------------------------------------------
  1705. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1706. {
  1707. return false;
  1708. }
  1709. //---------------------------------------------------------------------------
  1710. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1711. {
  1712. return false;
  1713. }
  1714. //---------------------------------------------------------------------------
  1715. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1716. {
  1717. return false;
  1718. }
  1719. //---------------------------------------------------------------------------
  1720. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1721. {
  1722. return NULL;
  1723. }
  1724. //---------------------------------------------------------------------------
  1725. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1726. {
  1727. DebugAssert(GetSide(Side) == osRemote);
  1728. DebugUsedParam(Side);
  1729. return RemoteDirView;
  1730. }
  1731. //---------------------------------------------------------------------------
  1732. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1733. {
  1734. DebugAssert(GetSide(Side) == osRemote);
  1735. DebugUsedParam(Side);
  1736. return RemoteDriveView;
  1737. }
  1738. //---------------------------------------------------------------------------
  1739. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1740. {
  1741. DebugAssert(GetSide(Side) == osRemote);
  1742. DebugUsedParam(Side);
  1743. return HasAvailableTerminal();
  1744. }
  1745. //---------------------------------------------------------------------------
  1746. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1747. TOperationSide Side, int FilesOnly)
  1748. {
  1749. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1750. }
  1751. //---------------------------------------------------------------------------
  1752. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1753. TOperationSide Side, int FilesOnly)
  1754. {
  1755. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1756. }
  1757. //---------------------------------------------------------------------------
  1758. struct THistoryItemData
  1759. {
  1760. short int Side;
  1761. short int Index;
  1762. };
  1763. //---------------------------------------------------------------------------
  1764. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1765. {
  1766. DirView(Side)->HistoryGo(Index);
  1767. }
  1768. //---------------------------------------------------------------------------
  1769. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1770. {
  1771. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1772. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1773. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1774. }
  1775. //---------------------------------------------------------------------------
  1776. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1777. bool Back)
  1778. {
  1779. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1780. {
  1781. TCustomDirView * DView = DirView(Side);
  1782. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1783. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1784. if (ICount > 10)
  1785. {
  1786. ICount = 10;
  1787. }
  1788. Menu->Items->Clear();
  1789. THistoryItemData Data;
  1790. Data.Side = Side;
  1791. for (short int i = 1; i <= ICount; i++)
  1792. {
  1793. TTBCustomItem * Item = new TTBXItem(Menu);
  1794. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1795. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1796. Item->Hint = DView->HistoryPath[Data.Index];
  1797. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1798. Item->Tag = *reinterpret_cast<int*>(&Data);
  1799. Item->OnClick = HistoryItemClick;
  1800. Menu->Items->Add(Item);
  1801. }
  1802. }
  1803. }
  1804. //---------------------------------------------------------------------------
  1805. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1806. TOperationSide Side, bool Back)
  1807. {
  1808. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1809. {
  1810. // workaround
  1811. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1812. // operator new allocates memory in Pascal code, but calls inline
  1813. // constructor in C++, leading in problems, the function does
  1814. // both in Pascal code
  1815. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1816. UpdateHistoryMenu(Side, Back);
  1817. }
  1818. return FHistoryMenu[Side == osLocal][Back];
  1819. }
  1820. //---------------------------------------------------------------------------
  1821. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1822. TCustomDirView *Sender)
  1823. {
  1824. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1825. UpdateHistoryMenu(Side, true);
  1826. UpdateHistoryMenu(Side, false);
  1827. }
  1828. //---------------------------------------------------------------------------
  1829. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1830. {
  1831. // remote custom commands can be executed only if the server supports shell commands
  1832. // or have secondary shell
  1833. return HasAvailableTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1834. }
  1835. //---------------------------------------------------------------------------
  1836. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1837. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1838. {
  1839. // -1 = hidden, 0 = disabled, 1 = enabled
  1840. int Result;
  1841. TFileCustomCommand RemoteCustomCommand;
  1842. TLocalCustomCommand LocalCustomCommand;
  1843. TFileCustomCommand * NonInteractiveCustomCommand =
  1844. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1845. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1846. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1847. if (FLAGCLEAR(Command.Params, ccLocal))
  1848. {
  1849. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1850. // custom command that does not operate with files can be executed anytime ...
  1851. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1852. {
  1853. // ... but do not show such command in remote file menu
  1854. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1855. {
  1856. Result = AllowedState;
  1857. }
  1858. else
  1859. {
  1860. Result = -1;
  1861. }
  1862. }
  1863. else
  1864. {
  1865. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1866. {
  1867. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1868. }
  1869. else
  1870. {
  1871. Result = -1;
  1872. }
  1873. }
  1874. }
  1875. else
  1876. {
  1877. // custom command that does not operate with files can be executed anytime
  1878. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1879. {
  1880. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1881. }
  1882. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1883. {
  1884. if ((ListType == ccltAll) || (ListType == ccltFile))
  1885. {
  1886. // special case is "diff"-style command that can be executed over any side,
  1887. // if we have both sides
  1888. Result =
  1889. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1890. // directly (instead of EnableSelectedOperation) to pass
  1891. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1892. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1893. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1894. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1895. }
  1896. else if (ListType == ccltBoth)
  1897. {
  1898. DebugAssert(!IsLocalBrowserMode());
  1899. Result = 1;
  1900. }
  1901. else
  1902. {
  1903. Result = -1;
  1904. }
  1905. }
  1906. else
  1907. {
  1908. if ((ListType == ccltAll) ||
  1909. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1910. {
  1911. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1912. }
  1913. else
  1914. {
  1915. Result = -1;
  1916. }
  1917. }
  1918. if ((Result > 0) &&
  1919. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1920. !HasAvailableTerminal())
  1921. {
  1922. Result = 0;
  1923. }
  1924. }
  1925. return Result;
  1926. }
  1927. //---------------------------------------------------------------------------
  1928. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1929. TStrings * FileList, const TCustomCommandType & ACommand,
  1930. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1931. {
  1932. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1933. {
  1934. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1935. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1936. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1937. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1938. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1939. bool Capture =
  1940. FLAGSET(ACommand.Params, ccShowResults) ||
  1941. FLAGSET(ACommand.Params, ccCopyResults) ||
  1942. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1943. TCaptureOutputEvent OutputEvent = NULL;
  1944. DebugAssert(FCapturedLog == NULL);
  1945. TObjectReleaser<TStrings> CapturedLogReleaser(FCapturedLog);
  1946. if (Capture)
  1947. {
  1948. CapturedLogReleaser.Set(new TStringList());
  1949. OutputEvent = TerminalCaptureLog;
  1950. }
  1951. if (!RemoteCustomCommand.IsFileCommand(Command))
  1952. {
  1953. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1954. OutputEvent);
  1955. }
  1956. else
  1957. {
  1958. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1959. }
  1960. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1961. {
  1962. if (FLAGSET(ACommand.Params, ccCopyResults))
  1963. {
  1964. CopyToClipboard(FCapturedLog);
  1965. }
  1966. if (FLAGSET(ACommand.Params, ccShowResults))
  1967. {
  1968. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1969. }
  1970. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1971. {
  1972. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1973. }
  1974. }
  1975. }
  1976. }
  1977. //---------------------------------------------------------------------------
  1978. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1979. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1980. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1981. {
  1982. DebugAssert(!IsLocalBrowserMode());
  1983. TStrings * LocalFileList = NULL;
  1984. TStrings * RemoteFileList = NULL;
  1985. TStrings * RemoteFileListFull = NULL;
  1986. try
  1987. {
  1988. if (LocalFileCommand)
  1989. {
  1990. if (ALocalFileList == NULL)
  1991. {
  1992. DebugAssert(HasDirView[osLocal]);
  1993. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1994. // directly (instead of EnableSelectedOperation) to pass
  1995. // false to FocusedFileOnlyWhenFocused
  1996. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1997. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1998. }
  1999. else
  2000. {
  2001. LocalFileList = ALocalFileList;
  2002. }
  2003. if (FileListCommand)
  2004. {
  2005. if (LocalFileList->Count != 1)
  2006. {
  2007. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2008. }
  2009. }
  2010. else
  2011. {
  2012. if ((LocalFileList->Count != 1) &&
  2013. (FileList->Count != 1) &&
  2014. (LocalFileList->Count != FileList->Count))
  2015. {
  2016. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2017. }
  2018. }
  2019. }
  2020. UnicodeString RootTempDir;
  2021. UnicodeString TempDir;
  2022. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2023. if (!RemoteFiles)
  2024. {
  2025. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, true, true);
  2026. DebugAssert(RootTempDir == TempDir);
  2027. }
  2028. try
  2029. {
  2030. TDateTimes RemoteFileTimes;
  2031. if (RemoteFiles)
  2032. {
  2033. RemoteFileList = FileList;
  2034. }
  2035. else
  2036. {
  2037. RemoteFileList = new TStringList();
  2038. TMakeLocalFileListParams MakeFileListParam;
  2039. MakeFileListParam.FileList = RemoteFileList;
  2040. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2041. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2042. MakeFileListParam.Recursive =
  2043. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2044. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2045. if (!MakeFileListParam.Recursive)
  2046. {
  2047. RemoteFileTimes.clear();
  2048. RemoteFileListFull = new TStringList();
  2049. MakeFileListParam.FileList = RemoteFileListFull;
  2050. MakeFileListParam.Recursive = true;
  2051. MakeFileListParam.IncludeDirs = false;
  2052. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2053. }
  2054. else
  2055. {
  2056. RemoteFileListFull = RemoteFileList;
  2057. }
  2058. }
  2059. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2060. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2061. if (!NonBlocking)
  2062. {
  2063. int Count;
  2064. if (FileListCommand)
  2065. {
  2066. Count = 1;
  2067. }
  2068. else if (LocalFileCommand)
  2069. {
  2070. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2071. }
  2072. else
  2073. {
  2074. Count = RemoteFileList->Count;
  2075. }
  2076. Progress.Start(foCustomCommand, osRemote, Count);
  2077. DebugAssert(FProgressForm != NULL);
  2078. FProgressForm->ReadOnly = true;
  2079. }
  2080. try
  2081. {
  2082. if (FileListCommand)
  2083. {
  2084. UnicodeString LocalFile;
  2085. // MakeFileList does not delimit filenames
  2086. UnicodeString FileList = MakeFileList(RemoteFileList);
  2087. if (LocalFileCommand)
  2088. {
  2089. DebugAssert(LocalFileList->Count == 1);
  2090. LocalFile = LocalFileList->Strings[0];
  2091. }
  2092. TLocalCustomCommand CustomCommand(Data,
  2093. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2094. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2095. if (NonBlocking)
  2096. {
  2097. DebugAssert(!POutput);
  2098. ExecuteShellChecked(ShellCommand);
  2099. }
  2100. else
  2101. {
  2102. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2103. }
  2104. }
  2105. else if (LocalFileCommand)
  2106. {
  2107. if (LocalFileList->Count == 1)
  2108. {
  2109. UnicodeString LocalFile = LocalFileList->Strings[0];
  2110. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2111. {
  2112. UnicodeString FileName = RemoteFileList->Strings[Index];
  2113. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2114. Progress.SetFile(FileNameForProgress);
  2115. TLocalCustomCommand CustomCommand(Data,
  2116. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2117. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2118. TOnceDoneOperation OnceDoneOperation;
  2119. // Do not unselect anything, as it won't work with two panels anyway
  2120. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2121. }
  2122. }
  2123. else if (RemoteFileList->Count == 1)
  2124. {
  2125. UnicodeString FileName = RemoteFileList->Strings[0];
  2126. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2127. {
  2128. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2129. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2130. Progress.SetFile(LocalFileNameOnly);
  2131. TLocalCustomCommand CustomCommand(
  2132. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2133. FileName, LocalFileName, L"");
  2134. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2135. TOnceDoneOperation OnceDoneOperation;
  2136. // Do not unselect anything, as it won't work with two panels anyway
  2137. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2138. }
  2139. }
  2140. else
  2141. {
  2142. if (LocalFileList->Count != RemoteFileList->Count)
  2143. {
  2144. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2145. }
  2146. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2147. {
  2148. UnicodeString FileName = RemoteFileList->Strings[Index];
  2149. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2150. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2151. Progress.SetFile(LocalFileNameOnly); // sic
  2152. TLocalCustomCommand CustomCommand(
  2153. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2154. FileName, LocalFileName, L"");
  2155. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2156. TOnceDoneOperation OnceDoneOperation;
  2157. // Do not unselect anything, as it won't work with two panels anyway
  2158. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2159. }
  2160. }
  2161. }
  2162. else
  2163. {
  2164. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2165. {
  2166. UnicodeString FileName = RemoteFileList->Strings[Index];
  2167. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2168. Progress.SetFile(FileNameForProgress);
  2169. TLocalCustomCommand CustomCommand(Data,
  2170. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2171. FileName, L"", L"");
  2172. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2173. TOnceDoneOperation OnceDoneOperation;
  2174. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2175. }
  2176. }
  2177. }
  2178. __finally
  2179. {
  2180. if (!NonBlocking)
  2181. {
  2182. Progress.Stop();
  2183. }
  2184. }
  2185. DebugAssert(!FAutoOperation);
  2186. if (!RemoteFiles)
  2187. {
  2188. TempDir = IncludeTrailingBackslash(TempDir);
  2189. typedef std::map<UnicodeString, UnicodeString> TTempNameMap;
  2190. TTempNameMap TempNameMap;
  2191. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2192. {
  2193. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2194. TSearchRecSmart SearchRec;
  2195. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2196. FileSearchRec(FileName, SearchRec) &&
  2197. // Skip directories, process only nested files.
  2198. !SearchRec.IsDirectory() &&
  2199. (SearchRec.GetLastWriteTime() != RemoteFileTimes[Index]))
  2200. {
  2201. if (TempNameMap.empty()) // optimization (create map only once it is really needed)
  2202. {
  2203. TCopyParamType CopyParam = TemporaryFileCopyParam();
  2204. for (int Index2 = 0; Index2 < FileList->Count; Index2++)
  2205. {
  2206. UnicodeString RemotePath = FileList->Strings[Index2];
  2207. UnicodeString TempName = GetTempLocalName(RemotePath, CopyParam);
  2208. TempNameMap.insert(std::make_pair(TempName.UpperCase(), RemotePath));
  2209. }
  2210. }
  2211. UnicodeString RelPath = MidStr(FileName, TempDir.Length() + 1);
  2212. UnicodeString TempName = CutToChar(RelPath, L'\\', false).UpperCase();
  2213. TTempNameMap::const_iterator TempNameI = TempNameMap.find(TempName);
  2214. if (DebugAlwaysTrue(TempNameI != TempNameMap.end()))
  2215. {
  2216. TCopyParamType CopyParam = TemporaryFileCopyParam();
  2217. CopyParam.FileMask = L"";
  2218. FAutoOperation = true;
  2219. FMoveToQueue = false;
  2220. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2221. TemporaryFilesList->Add(FileName);
  2222. UnicodeString RemoteDir = UnixExtractFileDir(UnixCombinePathsSmart(TempNameI->second, ToUnixPath(RelPath)));
  2223. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2224. }
  2225. }
  2226. }
  2227. }
  2228. }
  2229. __finally
  2230. {
  2231. FAutoOperation = false;
  2232. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2233. {
  2234. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2235. }
  2236. }
  2237. }
  2238. __finally
  2239. {
  2240. if (RemoteFileList != FileList)
  2241. {
  2242. delete RemoteFileList;
  2243. }
  2244. if (LocalFileList != ALocalFileList)
  2245. {
  2246. delete LocalFileList;
  2247. }
  2248. if (RemoteFileListFull != RemoteFileList)
  2249. {
  2250. delete RemoteFileListFull;
  2251. }
  2252. }
  2253. }
  2254. //---------------------------------------------------------------------------
  2255. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2256. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2257. bool FileListCommand, UnicodeString * POutput)
  2258. {
  2259. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2260. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2261. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2262. {
  2263. UnicodeString FileName = SelectedFileList->Strings[Index];
  2264. if (DirectoryExists(FileName))
  2265. {
  2266. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2267. {
  2268. LocalFileList->Add(FileName);
  2269. }
  2270. if (FLAGSET(ACommand.Params, ccRecursive))
  2271. {
  2272. TMakeLocalFileListParams MakeFileListParam;
  2273. MakeFileListParam.FileList = LocalFileList.get();
  2274. MakeFileListParam.FileTimes = NULL;
  2275. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2276. MakeFileListParam.Recursive = true;
  2277. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2278. }
  2279. }
  2280. else
  2281. {
  2282. LocalFileList->Add(FileName);
  2283. }
  2284. }
  2285. UnicodeString RemotePath;
  2286. if (Terminal != NULL)
  2287. {
  2288. RemotePath = Terminal->CurrentDirectory;
  2289. }
  2290. if (FileListCommand)
  2291. {
  2292. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2293. TLocalCustomCommand CustomCommand(
  2294. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2295. L"", L"", FileList);
  2296. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2297. }
  2298. else
  2299. {
  2300. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2301. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2302. DebugAssert(FProgressForm != NULL);
  2303. FProgressForm->ReadOnly = true;
  2304. try
  2305. {
  2306. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2307. {
  2308. UnicodeString FileName = LocalFileList->Strings[Index];
  2309. Progress.SetFile(FileName);
  2310. TLocalCustomCommand CustomCommand(
  2311. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2312. FileName, L"", L"");
  2313. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2314. TOnceDoneOperation OnceDoneOperation;
  2315. Progress.Finish(FileName, true, OnceDoneOperation);
  2316. }
  2317. }
  2318. __finally
  2319. {
  2320. Progress.Stop();
  2321. }
  2322. }
  2323. }
  2324. //---------------------------------------------------------------------------
  2325. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2326. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2327. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2328. {
  2329. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2330. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2331. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2332. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2333. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2334. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2335. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2336. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2337. std::unique_ptr<UnicodeString> POutput;
  2338. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2339. FLAGSET(ACommand.Params, ccCopyResults))
  2340. {
  2341. POutput.reset(new UnicodeString());
  2342. }
  2343. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  2344. if (!LocalCustomCommand.IsFileCommand(Command))
  2345. {
  2346. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2347. }
  2348. // remote files?
  2349. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2350. {
  2351. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2352. }
  2353. // local files
  2354. else
  2355. {
  2356. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2357. }
  2358. if (POutput.get() != NULL)
  2359. {
  2360. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2361. int P = POutput->Pos(sLineBreak);
  2362. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2363. {
  2364. POutput->SetLength(P - 1);
  2365. }
  2366. // Copy even empty output to clipboard
  2367. if (FLAGSET(ACommand.Params, ccCopyResults))
  2368. {
  2369. CopyToClipboard(*POutput);
  2370. }
  2371. // But do not show an empty message box.
  2372. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2373. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2374. !POutput->IsEmpty())
  2375. {
  2376. TClipboardHandler ClipboardHandler;
  2377. ClipboardHandler.Text = *POutput;
  2378. TMessageParams Params;
  2379. TQueryButtonAlias Aliases[1];
  2380. Aliases[0].Button = qaRetry;
  2381. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2382. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2383. Params.Aliases = Aliases;
  2384. Params.AliasesCount = LENOF(Aliases);
  2385. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2386. }
  2387. }
  2388. }
  2389. //---------------------------------------------------------------------------
  2390. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2391. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2392. {
  2393. TCustomCommandData Data;
  2394. UnicodeString Site;
  2395. UnicodeString RemotePath;
  2396. if (HasAvailableTerminal())
  2397. {
  2398. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2399. Data = TCustomCommandData(SessionData.get());
  2400. Site = Terminal->SessionData->SessionKey;
  2401. RemotePath = Terminal->CurrentDirectory;
  2402. }
  2403. UnicodeString HelpKeyword = ACommand.HomePage;
  2404. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2405. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2406. {
  2407. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2408. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2409. {
  2410. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2411. }
  2412. else
  2413. {
  2414. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2415. }
  2416. if (!DoCustomCommandOptionsDialog(
  2417. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2418. {
  2419. Abort();
  2420. }
  2421. }
  2422. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2423. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2424. {
  2425. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2426. }
  2427. else
  2428. {
  2429. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2430. }
  2431. }
  2432. //---------------------------------------------------------------------------
  2433. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2434. const TCustomCommandType & Command)
  2435. {
  2436. DebugAssert(FCustomCommandLocalFileList != NULL);
  2437. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2438. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2439. TStrings * LocalFileList = new TStringList();
  2440. TStrings * RemoteFileList = new TStringList();
  2441. try
  2442. {
  2443. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2444. {
  2445. LocalFileList->Clear();
  2446. LocalFileList->AddObject(
  2447. FCustomCommandLocalFileList->Strings[Index],
  2448. FCustomCommandLocalFileList->Objects[Index]);
  2449. RemoteFileList->Clear();
  2450. RemoteFileList->AddObject(
  2451. FCustomCommandRemoteFileList->Strings[Index],
  2452. FCustomCommandRemoteFileList->Objects[Index]);
  2453. CustomCommand(RemoteFileList, Command, LocalFileList);
  2454. }
  2455. }
  2456. __finally
  2457. {
  2458. delete LocalFileList;
  2459. delete RemoteFileList;
  2460. }
  2461. }
  2462. //---------------------------------------------------------------------------
  2463. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2464. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2465. {
  2466. delete FCustomCommandLocalFileList;
  2467. delete FCustomCommandRemoteFileList;
  2468. // takeover ownership,
  2469. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2470. FCustomCommandLocalFileList = LocalFileList;
  2471. FCustomCommandRemoteFileList = RemoteFileList;
  2472. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2473. if (Button != NULL)
  2474. {
  2475. FCustomCommandMenu->Items->Clear();
  2476. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2477. MenuPopup(FCustomCommandMenu, Button);
  2478. }
  2479. else
  2480. {
  2481. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2482. }
  2483. }
  2484. //---------------------------------------------------------------------------
  2485. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2486. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2487. {
  2488. DebugAssert(FCapturedLog != NULL);
  2489. if ((OutputType == cotOutput) || (OutputType == cotError))
  2490. {
  2491. FCapturedLog->Add(AddedLine);
  2492. }
  2493. }
  2494. //---------------------------------------------------------------------------
  2495. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2496. TOperationSide Side)
  2497. {
  2498. return
  2499. (Side == osOther) &&
  2500. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2501. }
  2502. //---------------------------------------------------------------------------
  2503. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2504. TOperationSide Side, TTBXCustomItem * Item,
  2505. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2506. {
  2507. TCustomDirView * DView = DirView(Side);
  2508. bool IsDefault = false;
  2509. if (DView->ItemFocused != NULL)
  2510. {
  2511. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2512. TResolvedDoubleClickAction DefaultAction =
  2513. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2514. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2515. }
  2516. TTBItemOptions O = Item->Options;
  2517. if (IsDefault)
  2518. {
  2519. Item->Options = O << tboDefault;
  2520. }
  2521. else
  2522. {
  2523. Item->Options = O >> tboDefault;
  2524. }
  2525. }
  2526. //---------------------------------------------------------------------------
  2527. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2528. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2529. {
  2530. TCustomDirView * DView = DirView(Side);
  2531. TListItem * Item = DView->ItemFocused;
  2532. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2533. EnableFocusedOperation[Side])
  2534. {
  2535. TPoint ClientPoint;
  2536. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2537. TPoint(0, 0) : MousePos;
  2538. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2539. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2540. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2541. }
  2542. }
  2543. //---------------------------------------------------------------------------
  2544. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2545. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2546. {
  2547. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2548. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2549. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2550. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2551. Handled = true;
  2552. }
  2553. //---------------------------------------------------------------------------
  2554. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString DebugUsedArg(Directory))
  2555. {
  2556. }
  2557. //---------------------------------------------------------------------------
  2558. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2559. {
  2560. DebugAssert(FErrorList == NULL);
  2561. if (WinConfiguration->ContinueOnError)
  2562. {
  2563. FErrorList = new TStringList();
  2564. Configuration->Usage->Inc(L"ContinuationsOnError");
  2565. }
  2566. NonVisualDataModule->StartBusy();
  2567. }
  2568. //---------------------------------------------------------------------------
  2569. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2570. {
  2571. NonVisualDataModule->EndBusy();
  2572. if (FErrorList)
  2573. {
  2574. HandleErrorList(FErrorList);
  2575. }
  2576. }
  2577. //---------------------------------------------------------------------------
  2578. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2579. const TCopyParamType & CopyParam)
  2580. {
  2581. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2582. {
  2583. Configuration->Usage->Inc(L"FileMaskUses");
  2584. }
  2585. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2586. {
  2587. Configuration->Usage->Inc(L"OperationMaskUses");
  2588. }
  2589. }
  2590. //---------------------------------------------------------------------------
  2591. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2592. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2593. {
  2594. DebugAssert(!IsLocalBrowserMode());
  2595. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2596. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2597. TTransferOperationParam DefaultParam;
  2598. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2599. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2600. switch (Param.Queue)
  2601. {
  2602. case asOn:
  2603. CopyParam.Queue = true;
  2604. break;
  2605. case asOff:
  2606. CopyParam.Queue = false;
  2607. break;
  2608. case asAuto:
  2609. default:
  2610. // keep default
  2611. break;
  2612. }
  2613. bool Result =
  2614. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2615. if (Result)
  2616. {
  2617. DebugAssert(Terminal);
  2618. bool SelectionRestored = false;
  2619. TCustomDirView * DView = NULL;
  2620. if (HasDirView[Side])
  2621. {
  2622. DView = DirView(Side);
  2623. DView->SaveSelection();
  2624. DView->SaveSelectedNames();
  2625. }
  2626. UpdateCopyParamCounters(CopyParam);
  2627. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2628. DebugAssert(FTransferResumeList == NULL);
  2629. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2630. FMoveToQueue = false;
  2631. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2632. try
  2633. {
  2634. TStrings * PermanentFileList;
  2635. std::unique_ptr<TStrings> PermanentFileListOwner;
  2636. try
  2637. {
  2638. if (Side == osLocal)
  2639. {
  2640. PermanentFileList = FileList;
  2641. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2642. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2643. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2644. if (Operation == foMove)
  2645. {
  2646. ReloadLocalDirectory();
  2647. if (DView != NULL)
  2648. {
  2649. DView->RestoreSelection();
  2650. }
  2651. SelectionRestored = true;
  2652. }
  2653. }
  2654. else
  2655. {
  2656. // Clone the file list as it may refer to current directory files,
  2657. // which get destroyed, when the source directory is reloaded after foMove operation.
  2658. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2659. // But for a hotfix, we are not going to do such a big change.
  2660. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2661. PermanentFileList = PermanentFileListOwner.get();
  2662. try
  2663. {
  2664. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2665. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2666. }
  2667. __finally
  2668. {
  2669. if (Operation == foMove)
  2670. {
  2671. if (DView != NULL)
  2672. {
  2673. DView->RestoreSelection();
  2674. }
  2675. SelectionRestored = true;
  2676. }
  2677. ReloadLocalDirectory(Param.TargetDirectory);
  2678. }
  2679. }
  2680. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2681. if (FMoveToQueue)
  2682. {
  2683. Abort();
  2684. }
  2685. }
  2686. catch (EAbort &)
  2687. {
  2688. if (FMoveToQueue)
  2689. {
  2690. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2691. DebugAssert(CopyParam.TransferSkipList == NULL);
  2692. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2693. if (TransferResumeList->Count > 0)
  2694. {
  2695. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2696. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2697. }
  2698. CopyParam.TransferSkipList = TransferResumeList.release();
  2699. // not really needed, just to keep it consistent with TransferResumeList
  2700. FTransferResumeList = NULL;
  2701. FMoveToQueue = false;
  2702. Configuration->Usage->Inc("MovesToBackground");
  2703. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2704. ClearTransferSourceSelection(Direction);
  2705. }
  2706. throw;
  2707. }
  2708. }
  2709. __finally
  2710. {
  2711. if (!SelectionRestored && (DView != NULL))
  2712. {
  2713. DView->DiscardSavedSelection();
  2714. }
  2715. FTransferResumeList = NULL;
  2716. }
  2717. }
  2718. return Result;
  2719. }
  2720. //---------------------------------------------------------------------------
  2721. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2722. TOperationSide Side, TStrings * FileList, void * Param)
  2723. {
  2724. DebugAssert(FileList->Count);
  2725. // We deliberately do not toggle alternative flag (Param), but use OR,
  2726. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2727. // shortcut of CurrentDeleteAlternativeAction
  2728. bool Alternative =
  2729. bool(Param) || UseAlternativeFunction();
  2730. bool Recycle;
  2731. if (IsSideLocalBrowser(Side))
  2732. {
  2733. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2734. }
  2735. else
  2736. {
  2737. Recycle =
  2738. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2739. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2740. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2741. }
  2742. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2743. if (!Result)
  2744. {
  2745. UnicodeString Query;
  2746. if (FileList->Count == 1)
  2747. {
  2748. if (IsSideLocalBrowser(Side))
  2749. {
  2750. Query = ExtractFileName(FileList->Strings[0]);
  2751. }
  2752. else
  2753. {
  2754. Query = UnixExtractFileName(FileList->Strings[0]);
  2755. }
  2756. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2757. }
  2758. else
  2759. {
  2760. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2761. }
  2762. TMessageParams Params(mpNeverAskAgainCheck);
  2763. Params.ImageName = L"Delete file";
  2764. unsigned int Answer =
  2765. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2766. if (Answer == qaNeverAskAgain)
  2767. {
  2768. Result = true;
  2769. if (Recycle)
  2770. {
  2771. WinConfiguration->ConfirmRecycling = false;
  2772. }
  2773. else
  2774. {
  2775. WinConfiguration->ConfirmDeleting = false;
  2776. }
  2777. }
  2778. else
  2779. {
  2780. Result = (Answer == qaOK);
  2781. }
  2782. }
  2783. if (Result)
  2784. {
  2785. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2786. }
  2787. return Result;
  2788. }
  2789. //---------------------------------------------------------------------------
  2790. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2791. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2792. {
  2793. TAutoBatch AutoBatch(this);
  2794. bool Result;
  2795. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2796. {
  2797. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2798. }
  2799. else if (Operation == foRename)
  2800. {
  2801. DebugAssert(DirView(Side)->ItemFocused);
  2802. DirView(Side)->ItemFocused->EditCaption();
  2803. Result = true;
  2804. }
  2805. else if (Operation == foDelete)
  2806. {
  2807. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2808. }
  2809. else if (Operation == foSetProperties)
  2810. {
  2811. DirView(osRemote)->SaveSelectedNames();
  2812. Result = SetProperties(Side, FileList);
  2813. }
  2814. else if (Operation == foCustomCommand)
  2815. {
  2816. DebugAssert(Param);
  2817. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2818. DirView(osRemote)->SaveSelectedNames();
  2819. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2820. CustomCommand(FileList, *Command, NULL);
  2821. Result = true;
  2822. }
  2823. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2824. {
  2825. DebugAssert(!IsSideLocalBrowser(Side));
  2826. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2827. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2828. }
  2829. else if (Operation == foLock)
  2830. {
  2831. DebugAssert(!IsSideLocalBrowser(Side));
  2832. LockFiles(FileList, true);
  2833. Result = true;
  2834. }
  2835. else if (Operation == foUnlock)
  2836. {
  2837. DebugAssert(!IsSideLocalBrowser(Side));
  2838. LockFiles(FileList, false);
  2839. Result = true;
  2840. }
  2841. else
  2842. {
  2843. DebugFail();
  2844. Result = false; // shut up
  2845. }
  2846. return Result;
  2847. }
  2848. //---------------------------------------------------------------------------
  2849. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2850. {
  2851. if (Side == osCurrent)
  2852. {
  2853. Side = FCurrentSide;
  2854. }
  2855. return Side;
  2856. }
  2857. //---------------------------------------------------------------------------
  2858. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2859. {
  2860. TOperationSide Result;
  2861. switch (GetSide(Side))
  2862. {
  2863. case osLocal:
  2864. Result = osOther;
  2865. break;
  2866. case osOther:
  2867. Result = osLocal;
  2868. break;
  2869. default:
  2870. Result = osCurrent; // shut up
  2871. DebugFail();
  2872. Abort();
  2873. }
  2874. return Result;
  2875. }
  2876. //---------------------------------------------------------------------------
  2877. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2878. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2879. {
  2880. Side = GetSide(Side);
  2881. bool FullPath = IsSideLocalBrowser(Side);
  2882. TCustomDirView * ADirView = DirView(Side);
  2883. std::unique_ptr<TStringList> FileList(new TStringList());
  2884. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2885. bool ReloadProperties =
  2886. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2887. DebugAlwaysTrue(HasAvailableTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2888. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2889. if (Result && ReloadProperties)
  2890. {
  2891. std::unique_ptr<TStringList> FileList2(new TStringList());
  2892. FileList->CaseSensitive = true;
  2893. FileList->Sort();
  2894. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2895. {
  2896. TListItem * Item = ADirView->Items->Item[Index];
  2897. UnicodeString FileName = ADirView->ItemFileName(Item);
  2898. int Index2;
  2899. if (FileList->Find(FileName, Index2))
  2900. {
  2901. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2902. }
  2903. }
  2904. LoadFilesProperties(FileList2.get());
  2905. }
  2906. return Result;
  2907. }
  2908. //---------------------------------------------------------------------------
  2909. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2910. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2911. bool NoConfirmation, void * Param)
  2912. {
  2913. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2914. {
  2915. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2916. {
  2917. DebugAssert(!IsLocalBrowserMode());
  2918. if (GetSide(Side) == osLocal)
  2919. {
  2920. Configuration->Usage->Inc(L"UploadsCommand");
  2921. }
  2922. else
  2923. {
  2924. Configuration->Usage->Inc(L"DownloadsCommand");
  2925. }
  2926. }
  2927. }
  2928. }
  2929. //---------------------------------------------------------------------------
  2930. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2931. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2932. {
  2933. TTransferOperationParam Param;
  2934. if ((WinConfiguration->Interface != ifCommander) ||
  2935. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2936. {
  2937. Flags &= ~cocShortCutHint;
  2938. }
  2939. TCustomDirView * DView = DirView(Side);
  2940. Param.Options =
  2941. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2942. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2943. if (FLAGSET(Flags, cocQueue))
  2944. {
  2945. Param.Queue = asOn;
  2946. }
  2947. else if (FLAGSET(Flags, cocNonQueue))
  2948. {
  2949. Param.Queue = asOff;
  2950. }
  2951. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2952. }
  2953. //---------------------------------------------------------------------------
  2954. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2955. {
  2956. int Count = ErrorList->Count;
  2957. try
  2958. {
  2959. if (ErrorList->Count)
  2960. {
  2961. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2962. if (MessageDialog(Message, qtError,
  2963. qaOK | qaCancel, HELP_NONE) == qaOK)
  2964. {
  2965. unsigned int Answer;
  2966. int Index = 0;
  2967. do
  2968. {
  2969. DebugAssert(Index >= 0 && Index < Count);
  2970. TQueryButtonAlias Aliases[2];
  2971. Aliases[0].Button = qaYes;
  2972. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2973. Aliases[1].Button = qaNo;
  2974. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2975. TMessageParams Params;
  2976. Params.Aliases = Aliases;
  2977. Params.AliasesCount = LENOF(Aliases);
  2978. int No = Index + 1;
  2979. UnicodeString Message = ErrorList->Strings[Index];
  2980. UnicodeString AMainInstructions;
  2981. UnicodeString Details;
  2982. if (ExtractMainInstructions(Message, AMainInstructions))
  2983. {
  2984. Details = Message;
  2985. Message = AMainInstructions;
  2986. }
  2987. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2988. Answer = MoreMessageDialog(
  2989. Message,
  2990. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2991. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2992. qaOK, HELP_NONE, &Params);
  2993. if (Answer == qaNo)
  2994. {
  2995. Index++;
  2996. }
  2997. if (Answer == qaYes)
  2998. {
  2999. Index--;
  3000. }
  3001. }
  3002. while (Answer != qaOK);
  3003. }
  3004. }
  3005. }
  3006. __finally
  3007. {
  3008. TStrings * List = ErrorList;
  3009. ErrorList = NULL;
  3010. for (int i = 0; i < Count; i++)
  3011. {
  3012. delete List->Objects[i];
  3013. }
  3014. delete List;
  3015. }
  3016. }
  3017. //---------------------------------------------------------------------------
  3018. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3019. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3020. {
  3021. // needed for checking filemasks, as there's no directory object
  3022. // associated with the file object
  3023. File->FullFileName = FullFileName;
  3024. TFileMasks::TParams MaskParams;
  3025. MaskParams.Size = File->Size;
  3026. MaskParams.Modification = File->Modification;
  3027. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3028. }
  3029. //---------------------------------------------------------------------------
  3030. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3031. {
  3032. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3033. Side = GetSide(Side);
  3034. TCustomDirView * DView = DirView(Side);
  3035. TListItem * FocusedItem = DView->ItemFocused;
  3036. UnicodeString Name;
  3037. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3038. {
  3039. Name = DView->ItemFileName(FocusedItem);
  3040. }
  3041. else
  3042. {
  3043. Name = LoadStr(NEW_FILE);
  3044. }
  3045. UnicodeString Names = Name;
  3046. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3047. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3048. HELP_EDIT_NEW, History.get(), true, NULL, true, 444))
  3049. {
  3050. while (!Names.IsEmpty())
  3051. {
  3052. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3053. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3054. UnicodeString TargetFileName;
  3055. UnicodeString LocalFileName;
  3056. UnicodeString RootTempDir;
  3057. UnicodeString TempDir;
  3058. UnicodeString RemoteDirectory;
  3059. bool ExistingFile = false;
  3060. if (!IsSideLocalBrowser(Side))
  3061. {
  3062. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3063. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3064. if ((File.get() != NULL) &&
  3065. !File->IsDirectory)
  3066. {
  3067. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3068. ExistingFile = true;
  3069. }
  3070. File.reset(NULL);
  3071. if (!ExistingFile)
  3072. {
  3073. RemoteDirectory = UnixExtractFilePath(Name);
  3074. TemporaryDirectoryForRemoteFiles(
  3075. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3076. TargetFileName = UnixExtractFileName(Name);
  3077. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3078. LocalFileName = TempDir +
  3079. // We probably do not want to trim the VMS version here
  3080. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3081. }
  3082. }
  3083. else
  3084. {
  3085. if (ExtractFilePath(Name).IsEmpty())
  3086. {
  3087. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3088. }
  3089. else
  3090. {
  3091. LocalFileName = ExpandFileName(Name);
  3092. }
  3093. TargetFileName = ExtractFileName(Name);
  3094. }
  3095. if (!ExistingFile)
  3096. {
  3097. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3098. if (NewFile)
  3099. {
  3100. int File = FileCreate(ApiPath(LocalFileName));
  3101. if (File < 0)
  3102. {
  3103. if (!RootTempDir.IsEmpty())
  3104. {
  3105. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3106. }
  3107. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3108. }
  3109. else
  3110. {
  3111. FileClose(File);
  3112. }
  3113. }
  3114. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3115. const TEditorData * ExternalEditor = NULL;
  3116. TFileMasks::TParams MaskParams; // size not known
  3117. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3118. false, MaskParams);
  3119. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3120. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3121. }
  3122. }
  3123. }
  3124. }
  3125. //---------------------------------------------------------------------------
  3126. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3127. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3128. {
  3129. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3130. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3131. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3132. return
  3133. ((ExecuteFileBy == efInternalEditor)) ||
  3134. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3135. }
  3136. //---------------------------------------------------------------------------
  3137. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3138. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3139. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3140. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3141. {
  3142. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3143. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3144. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3145. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3146. Side = GetSide(Side);
  3147. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3148. if (!IsSideLocalBrowser(Side))
  3149. {
  3150. Data->Terminal = Terminal;
  3151. Data->SessionData = CloneCurrentSessionData();
  3152. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3153. Data->RemoteDirectory = RemoteDirectory;
  3154. Data->SessionName = Terminal->SessionData->SessionName;
  3155. Data->LocalRootDirectory = LocalRootDirectory;
  3156. Data->OriginalFileName = OriginalFileName;
  3157. Data->Command = L""; // will be changed later for external editor
  3158. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3159. if (WinConfiguration->EditorCheckNotModified)
  3160. {
  3161. Data->SourceTimestamp = SourceTimestamp;
  3162. }
  3163. }
  3164. if (ExecuteFileBy == efInternalEditor)
  3165. {
  3166. if (!IsSideLocalBrowser(Side))
  3167. {
  3168. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3169. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3170. TForm * Editor;
  3171. try
  3172. {
  3173. Editor =
  3174. ShowEditorForm(
  3175. FileName, this,
  3176. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3177. SaveAllInternalEditors, AnyInternalEditorModified,
  3178. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3179. }
  3180. catch(...)
  3181. {
  3182. if (!LocalRootDirectory.IsEmpty())
  3183. {
  3184. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3185. }
  3186. throw;
  3187. }
  3188. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3189. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3190. }
  3191. else
  3192. {
  3193. DebugAssert(!StandaloneOperation);
  3194. TForm * Editor =
  3195. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3196. SaveAllInternalEditors, AnyInternalEditorModified,
  3197. L"", false, SessionColor, -1, NewFile);
  3198. FLocalEditors->Add(Editor);
  3199. }
  3200. }
  3201. else
  3202. {
  3203. HANDLE Process;
  3204. if (ExecuteFileBy == efExternalEditor)
  3205. {
  3206. UnicodeString Program, Params, Dir;
  3207. Data->Command = ExternalEditor->ExternalEditor;
  3208. ReformatFileNameCommand(Data->Command);
  3209. SplitCommand(Data->Command, Program, Params, Dir);
  3210. Params = ExpandFileNameCommand(Params, FileName);
  3211. Program = ExpandEnvironmentVariables(Program);
  3212. if (!ExecuteShell(Program, Params, Process))
  3213. {
  3214. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3215. }
  3216. }
  3217. else
  3218. {
  3219. DebugAssert(!IsSideLocalBrowser(Side));
  3220. if (!ExecuteShell(FileName, L"", Process))
  3221. {
  3222. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3223. }
  3224. }
  3225. if (IsSideLocalBrowser(Side) ||
  3226. ((ExecuteFileBy == efShell) &&
  3227. !WinConfiguration->Editor.SDIShellEditor) ||
  3228. ((ExecuteFileBy == efExternalEditor) &&
  3229. !ExternalEditor->SDIExternalEditor))
  3230. {
  3231. // no need for handle
  3232. if (Process != NULL)
  3233. {
  3234. DebugCheck(CloseHandle(Process));
  3235. }
  3236. Process = INVALID_HANDLE_VALUE;
  3237. }
  3238. else
  3239. {
  3240. if (Process == NULL)
  3241. {
  3242. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3243. }
  3244. }
  3245. if (!IsSideLocalBrowser(Side))
  3246. {
  3247. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3248. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3249. }
  3250. }
  3251. }
  3252. //---------------------------------------------------------------------------
  3253. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3254. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3255. void * /*Arg*/)
  3256. {
  3257. if (Token != NULL)
  3258. {
  3259. EditorFormFileSave(static_cast<TForm *>(Token));
  3260. }
  3261. }
  3262. //---------------------------------------------------------------------------
  3263. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3264. {
  3265. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3266. {
  3267. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3268. }
  3269. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3270. }
  3271. //---------------------------------------------------------------------------
  3272. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3273. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3274. void * Arg)
  3275. {
  3276. if ((Token != NULL) &&
  3277. IsEditorFormModified(static_cast<TForm *>(Token)))
  3278. {
  3279. *static_cast<bool *>(Arg) = true;
  3280. }
  3281. }
  3282. //---------------------------------------------------------------------------
  3283. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3284. TObject * /*Sender*/, bool & Modified)
  3285. {
  3286. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3287. {
  3288. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3289. {
  3290. Modified = true;
  3291. }
  3292. }
  3293. if (!Modified)
  3294. {
  3295. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3296. }
  3297. }
  3298. //---------------------------------------------------------------------------
  3299. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3300. {
  3301. DebugCheckNotEqual(FLocalEditors->Extract(Sender), NULL);
  3302. }
  3303. //---------------------------------------------------------------------------
  3304. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3305. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3306. UnicodeString & Result, UnicodeString & RootDirectory)
  3307. {
  3308. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3309. {
  3310. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3311. Result = RootDirectory;
  3312. }
  3313. else
  3314. {
  3315. RootDirectory = L"";
  3316. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3317. Result = IncludeTrailingBackslash(Result);
  3318. }
  3319. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3320. {
  3321. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3322. }
  3323. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3324. {
  3325. UnicodeString ARemoteDirectory = RemoteDirectory;
  3326. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3327. {
  3328. ARemoteDirectory.Delete(1, 1);
  3329. }
  3330. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3331. }
  3332. if (!ForceDirectories(ApiPath(Result)))
  3333. {
  3334. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3335. }
  3336. }
  3337. //---------------------------------------------------------------------------
  3338. UnicodeString TCustomScpExplorerForm::GetTempLocalName(const UnicodeString & Path, const TCopyParamType & CopyParam)
  3339. {
  3340. return Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(Path), osRemote, false);
  3341. }
  3342. //---------------------------------------------------------------------------
  3343. void TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3344. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3345. bool AutoOperation, bool SimpleTempDir)
  3346. {
  3347. DebugAssert(!IsLocalBrowserMode());
  3348. TCopyParamType CopyParam = TemporaryFileCopyParam(ForceText);
  3349. if (TempDir.IsEmpty())
  3350. {
  3351. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3352. }
  3353. DebugAssert(!FAutoOperation);
  3354. FAutoOperation = AutoOperation;
  3355. FMoveToQueue = false;
  3356. Terminal->ExceptionOnFail = true;
  3357. try
  3358. {
  3359. try
  3360. {
  3361. // turn off confirmations, as for MDI editors we may possibly download
  3362. // the same file over
  3363. Terminal->CopyToLocal(
  3364. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3365. }
  3366. catch(...)
  3367. {
  3368. if (!RootTempDir.IsEmpty())
  3369. {
  3370. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3371. }
  3372. throw;
  3373. }
  3374. }
  3375. __finally
  3376. {
  3377. FAutoOperation = false;
  3378. Terminal->ExceptionOnFail = false;
  3379. }
  3380. }
  3381. //---------------------------------------------------------------------------
  3382. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3383. {
  3384. // Do not waste time checking for default editor list the next time,
  3385. // or testing if default editor is not notepad.
  3386. bool TryNextTime = false;
  3387. UnicodeString UsageState;
  3388. if (!WinConfiguration->EditorList->IsDefaultList())
  3389. {
  3390. UsageState = "H";
  3391. }
  3392. else
  3393. {
  3394. UnicodeString Executable;
  3395. UnicodeString ExecutableDescription;
  3396. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3397. {
  3398. UnicodeString Message =
  3399. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3400. unsigned int Answer =
  3401. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3402. if (Answer != qaOK)
  3403. {
  3404. UsageState = "R";
  3405. }
  3406. else
  3407. {
  3408. UsageState = "A";
  3409. TEditorData EditorData;
  3410. EditorData.Editor = edExternal;
  3411. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3412. EditorData.ExternalEditorOptionsAutodetect();
  3413. TEditorList EditorList;
  3414. EditorList = *WinConfiguration->EditorList;
  3415. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3416. WinConfiguration->EditorList = &EditorList;
  3417. }
  3418. }
  3419. }
  3420. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3421. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3422. }
  3423. //---------------------------------------------------------------------------
  3424. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3425. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3426. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3427. {
  3428. if (ExecuteFileBy == efDefaultEditor)
  3429. {
  3430. if (!WinConfiguration->OfferedEditorAutoConfig)
  3431. {
  3432. EditorAutoConfig();
  3433. }
  3434. const TEditorPreferences * Editor =
  3435. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3436. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3437. {
  3438. ExecuteFileBy = efInternalEditor;
  3439. ExternalEditor = NULL;
  3440. }
  3441. else if (Editor->Data->Editor == edOpen)
  3442. {
  3443. ExecuteFileBy = efShell;
  3444. ExternalEditor = NULL;
  3445. }
  3446. else
  3447. {
  3448. ExecuteFileBy = efExternalEditor;
  3449. ExternalEditor = Editor->Data;
  3450. }
  3451. }
  3452. }
  3453. //---------------------------------------------------------------------------
  3454. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3455. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3456. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3457. {
  3458. UnicodeString OriginalFileName;
  3459. UnicodeString LocalRootDirectory;
  3460. UnicodeString RemoteDirectory;
  3461. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3462. IsSideLocalBrowser(Side), MaskParams);
  3463. UnicodeString Counter;
  3464. UnicodeString LocalFileName;
  3465. bool Handled = false;
  3466. if (!IsSideLocalBrowser(Side))
  3467. {
  3468. // We need to trim VMS version here, so that we use name without version
  3469. // when uploading back to create a new version of the file
  3470. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3471. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3472. TObject * Token = NULL;
  3473. UnicodeString LocalDirectory;
  3474. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3475. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3476. LocalDirectory))
  3477. {
  3478. if (Token != NULL)
  3479. {
  3480. TForm * Form = dynamic_cast<TForm *>(Token);
  3481. if (Form->WindowState == wsMinimized)
  3482. {
  3483. ShowWindow(Form->Handle, SW_RESTORE);
  3484. }
  3485. else
  3486. {
  3487. Form->SetFocus();
  3488. }
  3489. Handled = true;
  3490. }
  3491. else
  3492. {
  3493. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3494. }
  3495. }
  3496. if (!Handled)
  3497. {
  3498. std::unique_ptr<TStrings> FileList1(new TStringList());
  3499. FileList1->AddObject(FullFileName, Object);
  3500. bool ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3501. TemporarilyDownloadFiles(FileList1.get(), ForceText, LocalRootDirectory, LocalDirectory, true, false);
  3502. LocalFileName = LocalDirectory + GetTempLocalName(FullFileName, TemporaryFileCopyParam(ForceText));
  3503. switch (ExecuteFileBy)
  3504. {
  3505. case efShell:
  3506. Counter = "RemoteFilesExecuted";
  3507. break;
  3508. case efInternalEditor:
  3509. Counter = "RemoteFilesOpenedInInternalEditor";
  3510. break;
  3511. case efExternalEditor:
  3512. Counter = "RemoteFilesOpenedInExternalEditor";
  3513. break;
  3514. default:
  3515. DebugFail();
  3516. }
  3517. }
  3518. }
  3519. else
  3520. {
  3521. LocalFileName = FullFileName;
  3522. OriginalFileName = ExtractFileName(FullFileName);
  3523. switch (ExecuteFileBy)
  3524. {
  3525. case efShell:
  3526. Counter = "LocalFilesExecuted";
  3527. break;
  3528. case efInternalEditor:
  3529. Counter = "LocalFilesOpenedInInternalEditor";
  3530. break;
  3531. case efExternalEditor:
  3532. Counter = "LocalFilesOpenedInExternalEditor";
  3533. break;
  3534. default:
  3535. DebugFail();
  3536. }
  3537. }
  3538. if (!Handled)
  3539. {
  3540. Configuration->Usage->Inc(Counter);
  3541. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3542. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3543. }
  3544. }
  3545. //---------------------------------------------------------------------------
  3546. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3547. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3548. bool AllSelected, bool OnFocused)
  3549. {
  3550. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3551. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3552. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3553. Side = GetSide(Side);
  3554. TCustomDirView * DView = DirView(Side);
  3555. TStrings * FileList =
  3556. AllSelected ?
  3557. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3558. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3559. try
  3560. {
  3561. DebugAssert(AllSelected || (FileList->Count == 1));
  3562. for (int i = 0; i < FileList->Count; i++)
  3563. {
  3564. UnicodeString ListFileName = FileList->Strings[i];
  3565. UnicodeString FileNameOnly =
  3566. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3567. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3568. if (!DView->ItemIsDirectory(Item))
  3569. {
  3570. UnicodeString FullFileName;
  3571. if (!IsSideLocalBrowser(Side))
  3572. {
  3573. FullFileName = DirView(Side)->Path + ListFileName;
  3574. }
  3575. else
  3576. {
  3577. FullFileName = ListFileName;
  3578. }
  3579. TObject * Object = FileList->Objects[i];
  3580. TFileMasks::TParams MaskParams;
  3581. MaskParams.Size = DView->ItemFileSize(Item);
  3582. TDateTimePrecision Precision;
  3583. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3584. std::unique_ptr<TRemoteFile> File;
  3585. if (!IsSideLocalBrowser(Side))
  3586. {
  3587. File.reset(Terminal->TryReadFile(FullFileName));
  3588. if (File.get() != NULL)
  3589. {
  3590. File->FullFileName = FullFileName;
  3591. Object = File.get();
  3592. MaskParams.Size = File->Size;
  3593. MaskParams.Modification = File->Modification;
  3594. }
  3595. }
  3596. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3597. }
  3598. }
  3599. }
  3600. __finally
  3601. {
  3602. delete FileList;
  3603. }
  3604. }
  3605. //---------------------------------------------------------------------------
  3606. TCopyParamType TCustomScpExplorerForm::TemporaryFileCopyParam(bool ForceText)
  3607. {
  3608. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3609. CopyParam.FileNameCase = ncNoChange;
  3610. CopyParam.PreserveRights = false;
  3611. CopyParam.PreserveReadOnly = false;
  3612. CopyParam.ReplaceInvalidChars = true;
  3613. CopyParam.IncludeFileMask = TFileMasks();
  3614. CopyParam.NewerOnly = false;
  3615. CopyParam.FileMask = L"";
  3616. if (ForceText)
  3617. {
  3618. CopyParam.TransferMode = tmAscii;
  3619. }
  3620. return CopyParam;
  3621. }
  3622. //---------------------------------------------------------------------------
  3623. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3624. {
  3625. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3626. }
  3627. //---------------------------------------------------------------------------
  3628. class TEditorUploadQueueItem : public TUploadQueueItem
  3629. {
  3630. public:
  3631. __fastcall TEditorUploadQueueItem(
  3632. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3633. const TCopyParamType * CopyParam, int Params) :
  3634. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, false)
  3635. {
  3636. }
  3637. protected:
  3638. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3639. {
  3640. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3641. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3642. }
  3643. };
  3644. //---------------------------------------------------------------------------
  3645. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3646. {
  3647. if (WinConfiguration->EditorCheckNotModified) // optimization
  3648. {
  3649. UnicodeString RemoteFilePath;
  3650. {
  3651. TGuard Guard(FEditorManager->Section);
  3652. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3653. if (DebugAlwaysTrue(Data != NULL) &&
  3654. EditorCheckNotModified(Data))
  3655. {
  3656. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3657. }
  3658. }
  3659. if (!RemoteFilePath.IsEmpty())
  3660. {
  3661. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3662. if (File.get() != NULL)
  3663. {
  3664. TGuard Guard(FEditorManager->Section);
  3665. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3666. if (DebugAlwaysTrue(Data != NULL))
  3667. {
  3668. Data->SourceTimestamp = File->Modification;
  3669. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3670. }
  3671. }
  3672. }
  3673. }
  3674. }
  3675. //---------------------------------------------------------------------------
  3676. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3677. const UnicodeString & FileName, const TDateTime & Timestamp, TEditedFileData * Data,
  3678. HANDLE UploadCompleteEvent, bool & Retry)
  3679. {
  3680. TTerminalManager * Manager = TTerminalManager::Instance();
  3681. bool IsInavailable = !IsAvailableTerminal(Data->Terminal);
  3682. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3683. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3684. {
  3685. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3686. Retry = true;
  3687. }
  3688. else if (Manager->IsReconnectingTerminal(Data->Terminal))
  3689. {
  3690. AppLog(L"Session is being reconnected, will retry the upload later");
  3691. Retry = true;
  3692. }
  3693. else if (IsInavailable &&
  3694. GUIConfiguration->SessionReopenAutoInactive &&
  3695. (Data->Terminal->NextInactiveReconnect != TDateTime()))
  3696. {
  3697. if (Data->Terminal->LastInactiveSave != Timestamp)
  3698. {
  3699. AppLog(L"Inactive session reconnect is pending, rescheduling it for as soon as possible to retry the upload");
  3700. Data->Terminal->NextInactiveReconnect = Now();
  3701. Data->Terminal->LastInactiveSave = Timestamp;
  3702. }
  3703. else
  3704. {
  3705. AppLog(L"Inactive session reconnect is pending, will retry the upload later");
  3706. }
  3707. Retry = true;
  3708. }
  3709. else if (IsInavailable)
  3710. {
  3711. if (!NonVisualDataModule->Busy)
  3712. {
  3713. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3714. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3715. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3716. if (Data->Terminal == NULL)
  3717. {
  3718. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3719. if (SameSiteTerminal != NULL)
  3720. {
  3721. UnicodeString Message =
  3722. FMTLOAD(EDIT_SESSION_REATTACH,
  3723. (FileNameOnly, Data->SessionName, FileNameOnly));
  3724. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3725. {
  3726. Data->Terminal = SameSiteTerminal;
  3727. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3728. // We might also overwrite session data
  3729. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3730. }
  3731. else
  3732. {
  3733. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3734. Abort();
  3735. }
  3736. }
  3737. }
  3738. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3739. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3740. {
  3741. UnicodeString Message =
  3742. MainInstructions(
  3743. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3744. TMessageParams Params(FLAGMASK(!GUIConfiguration->SessionReopenAutoInactive, mpNeverAskAgainCheck));
  3745. Params.NeverAskAgainTitle = LoadStr(ALWAYS_RECONNECT);
  3746. unsigned int Answer = MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_NONE, &Params);
  3747. if (Answer == qaNeverAskAgain)
  3748. {
  3749. GUIConfiguration->SessionReopenAutoInactive = true;
  3750. Answer = qaOK;
  3751. }
  3752. if (Answer == qaOK)
  3753. {
  3754. if (Terminal->Disconnected)
  3755. {
  3756. Manager->ActiveSession = Terminal;
  3757. ReconnectSession();
  3758. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3759. if (!IsAvailableTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3760. {
  3761. Abort();
  3762. }
  3763. }
  3764. else
  3765. {
  3766. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3767. }
  3768. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3769. }
  3770. else
  3771. {
  3772. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3773. Abort();
  3774. }
  3775. }
  3776. }
  3777. if (!IsAvailableTerminal(Data->Terminal))
  3778. {
  3779. Configuration->Usage->Inc(L"EditInactiveSession");
  3780. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3781. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3782. (ExtractFileName(FileName), Data->SessionName)));
  3783. }
  3784. }
  3785. if (!Retry && EditorCheckNotModified(Data))
  3786. {
  3787. if (NonVisualDataModule->Busy)
  3788. {
  3789. Retry = true;
  3790. }
  3791. else
  3792. {
  3793. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3794. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3795. if (File.get() != NULL)
  3796. {
  3797. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3798. if (File->Modification != Data->SourceTimestamp)
  3799. {
  3800. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3801. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3802. {
  3803. Abort();
  3804. }
  3805. }
  3806. }
  3807. }
  3808. }
  3809. if (!Retry)
  3810. {
  3811. TStrings * FileList = new TStringList();
  3812. try
  3813. {
  3814. FileList->Add(FileName);
  3815. // Consider using the same settings (preset) as when the file was downloaded.
  3816. // More over this does not reflect the actual session that will do the upload.
  3817. TCopyParamType CopyParam = TemporaryFileCopyParam(Data->ForceText);
  3818. // so i do not need to worry if masking algorithm works in all cases
  3819. // ("" means "copy file name", no masking is actually done)
  3820. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3821. {
  3822. CopyParam.FileMask = L"";
  3823. }
  3824. else
  3825. {
  3826. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3827. }
  3828. int Params = cpNoConfirmation | cpTemporary;
  3829. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3830. {
  3831. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3832. TQueueItem * QueueItem =
  3833. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3834. QueueItem->CompleteEvent = UploadCompleteEvent;
  3835. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3836. }
  3837. else
  3838. {
  3839. if (NonVisualDataModule->Busy)
  3840. {
  3841. Retry = true;
  3842. }
  3843. else
  3844. {
  3845. FMoveToQueue = false;
  3846. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3847. SetEvent(UploadCompleteEvent);
  3848. }
  3849. }
  3850. }
  3851. __finally
  3852. {
  3853. delete FileList;
  3854. }
  3855. }
  3856. }
  3857. //---------------------------------------------------------------------------
  3858. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3859. const UnicodeString & FileName, TEditedFileData * Data)
  3860. {
  3861. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3862. DebugAssert(!NonVisualDataModule->Busy);
  3863. if (!IsAvailableTerminal(Data->Terminal))
  3864. {
  3865. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3866. (ExtractFileName(FileName), Data->SessionName)));
  3867. }
  3868. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3869. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3870. NonVisualDataModule->StartBusy();
  3871. try
  3872. {
  3873. std::unique_ptr<TRemoteFile> File;
  3874. UnicodeString RemoteFileName =
  3875. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3876. Terminal->ExceptionOnFail = true;
  3877. try
  3878. {
  3879. File.reset(Terminal->ReadFile(RemoteFileName));
  3880. if (!File->HaveFullFileName)
  3881. {
  3882. File->FullFileName = RemoteFileName;
  3883. }
  3884. }
  3885. __finally
  3886. {
  3887. Terminal->ExceptionOnFail = false;
  3888. }
  3889. std::unique_ptr<TStrings> FileList(new TStringList());
  3890. FileList->AddObject(RemoteFileName, File.get());
  3891. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3892. UnicodeString TempDir = ExtractFilePath(FileName);
  3893. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, false);
  3894. if (EditorCheckNotModified(Data))
  3895. {
  3896. Data->SourceTimestamp = File->Modification;
  3897. }
  3898. }
  3899. __finally
  3900. {
  3901. NonVisualDataModule->EndBusy();
  3902. // it actually may not exist anymore...
  3903. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3904. }
  3905. }
  3906. //---------------------------------------------------------------------------
  3907. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3908. const TEditedFileData * Data, bool & KeepOpen)
  3909. {
  3910. // Command is set for external editors only (not for "shell" open).
  3911. if (!Data->Command.IsEmpty())
  3912. {
  3913. bool AnyFound = false;
  3914. bool AnyMDI = false;
  3915. bool AnyNonMDI = false;
  3916. bool AnyDetect = false;
  3917. TEditorList * EditorList = new TEditorList();
  3918. try
  3919. {
  3920. *EditorList = *WinConfiguration->EditorList;
  3921. for (int i = 0; i < EditorList->Count; i++)
  3922. {
  3923. const TEditorPreferences * Editor = EditorList->Editors[i];
  3924. if ((Editor->Data->Editor == edExternal) &&
  3925. (Editor->Data->ExternalEditor == Data->Command))
  3926. {
  3927. AnyFound = true;
  3928. if (Editor->Data->SDIExternalEditor)
  3929. {
  3930. AnyNonMDI = true;
  3931. if (Editor->Data->DetectMDIExternalEditor)
  3932. {
  3933. AnyDetect = true;
  3934. }
  3935. }
  3936. else
  3937. {
  3938. AnyMDI = true;
  3939. }
  3940. }
  3941. }
  3942. bool EnableMDI = false;
  3943. bool DisableDetect = false;
  3944. if (AnyMDI)
  3945. {
  3946. KeepOpen = true;
  3947. if (AnyNonMDI)
  3948. {
  3949. // there is at least one instance of the editor with MDI support enabled,
  3950. // and one with disabled, enable it for all instances
  3951. EnableMDI = true;
  3952. }
  3953. }
  3954. else if (AnyFound && !AnyDetect)
  3955. {
  3956. // at least once instance found but all have MDI autodetection disabled
  3957. // => close the file (default action)
  3958. }
  3959. else
  3960. {
  3961. // no instance of the editor has MDI support enabled
  3962. TMessageParams Params;
  3963. if (AnyFound)
  3964. {
  3965. // there is at least one instance of the editor
  3966. Params.Params |= mpNeverAskAgainCheck;
  3967. }
  3968. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3969. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3970. switch (Answer)
  3971. {
  3972. case qaNeverAskAgain:
  3973. DisableDetect = true;
  3974. break;
  3975. case qaNo:
  3976. EnableMDI = true;
  3977. KeepOpen = true;
  3978. break;
  3979. }
  3980. }
  3981. if (AnyFound && (EnableMDI || DisableDetect))
  3982. {
  3983. bool Changed = false;
  3984. for (int i = 0; i < EditorList->Count; i++)
  3985. {
  3986. const TEditorPreferences * Editor = EditorList->Editors[i];
  3987. if ((Editor->Data->Editor == edExternal) &&
  3988. (Editor->Data->ExternalEditor == Data->Command) &&
  3989. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3990. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3991. {
  3992. Changed = true;
  3993. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3994. if (EnableMDI)
  3995. {
  3996. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3997. }
  3998. if (DisableDetect)
  3999. {
  4000. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  4001. }
  4002. EditorList->Change(i, UpdatedEditor);
  4003. }
  4004. }
  4005. if (Changed)
  4006. {
  4007. WinConfiguration->EditorList = EditorList;
  4008. }
  4009. }
  4010. }
  4011. __finally
  4012. {
  4013. delete EditorList;
  4014. }
  4015. }
  4016. else
  4017. {
  4018. // "open" case
  4019. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4020. qaOK, HELP_APP_EARLY_CLOSED);
  4021. }
  4022. }
  4023. //---------------------------------------------------------------------------
  4024. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4025. {
  4026. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4027. }
  4028. //---------------------------------------------------------------------------
  4029. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4030. {
  4031. SideEnter(osRemote);
  4032. }
  4033. //---------------------------------------------------------------------------
  4034. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4035. {
  4036. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4037. SideEnter(osRemote);
  4038. }
  4039. //---------------------------------------------------------------------------
  4040. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4041. {
  4042. FCurrentSide = Side;
  4043. if (Visible)
  4044. {
  4045. UpdateControls();
  4046. }
  4047. }
  4048. //---------------------------------------------------------------------------
  4049. void __fastcall TCustomScpExplorerForm::FileDeleted(
  4050. TOperationSide Side, const UnicodeString & FileName, bool Success, bool NotCancelled)
  4051. {
  4052. VisualiseOperationFinished(Side, FileName, Success && NotCancelled);
  4053. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4054. {
  4055. FDeletedFiles->Add(FileName);
  4056. }
  4057. }
  4058. //---------------------------------------------------------------------------
  4059. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4060. TStrings * FileList, bool Alternative)
  4061. {
  4062. TCustomDirView * DView = DirView(Side);
  4063. DView->SaveSelection();
  4064. DView->SaveSelectedNames();
  4065. DebugAssert(!FAlternativeDelete);
  4066. FAlternativeDelete = Alternative;
  4067. try
  4068. {
  4069. int Params = FLAGMASK(Alternative, dfAlternative);
  4070. bool Remote = !IsSideLocalBrowser(Side);
  4071. std::unique_ptr<TStringList> DeletedFiles;
  4072. std::unique_ptr<TStrings> PermanentFileList;
  4073. bool AllowMoveToQueue = (Terminal != NULL);
  4074. if (AllowMoveToQueue)
  4075. {
  4076. DeletedFiles.reset(new TStringList());
  4077. DeletedFiles->CaseSensitive = Remote;
  4078. }
  4079. try
  4080. {
  4081. DebugAssert(FDeletedFiles == NULL);
  4082. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles, DeletedFiles.get());
  4083. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4084. if (AllowMoveToQueue)
  4085. {
  4086. FOnFileOperationFinished = FileDeleted;
  4087. }
  4088. FMoveToQueue = false;
  4089. if (Remote)
  4090. {
  4091. DebugAssert(AllowMoveToQueue);
  4092. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4093. PermanentFileList.reset(TRemoteFileList::CloneStrings(FileList));
  4094. DebugAssert(Terminal != NULL);
  4095. Terminal->DeleteFiles(FileList, Params);
  4096. }
  4097. else
  4098. {
  4099. if (AllowMoveToQueue) // optimization)
  4100. {
  4101. PermanentFileList.reset(CloneStrings(FileList));
  4102. }
  4103. if (IsLocalBrowserMode())
  4104. {
  4105. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4106. }
  4107. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  4108. try
  4109. {
  4110. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, Params);
  4111. }
  4112. __finally
  4113. {
  4114. ReloadLocalDirectory();
  4115. }
  4116. }
  4117. // Probably not needed for deleting, just for consistency with transfer code
  4118. if (FMoveToQueue)
  4119. {
  4120. Abort();
  4121. }
  4122. }
  4123. catch (EAbort &)
  4124. {
  4125. if (FMoveToQueue && DebugAlwaysTrue(AllowMoveToQueue) && DebugAlwaysTrue(Terminal != NULL))
  4126. {
  4127. FMoveToQueue = false;
  4128. DeletedFiles->Sorted = true;
  4129. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4130. {
  4131. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4132. {
  4133. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4134. DebugAssert(Index == 0);
  4135. PermanentFileList->Delete(Index);
  4136. Index--;
  4137. }
  4138. }
  4139. if (Remote)
  4140. {
  4141. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4142. TQueueItem * QueueItem = new TRemoteDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4143. AddQueueItem(Queue, QueueItem, Terminal);
  4144. }
  4145. else
  4146. {
  4147. Configuration->Usage->Inc("MovesToBackgroundDeleteLocal");
  4148. TQueueItem * QueueItem = new TLocalDeleteQueueItem(PermanentFileList.get(), Params);
  4149. AddQueueItem(Queue, QueueItem, Terminal);
  4150. }
  4151. ClearOperationSelection(Side);
  4152. }
  4153. }
  4154. FAlternativeDelete = false;
  4155. }
  4156. catch(...)
  4157. {
  4158. FAlternativeDelete = false;
  4159. DView->DiscardSavedSelection();
  4160. throw;
  4161. }
  4162. DView->RestoreSelection();
  4163. }
  4164. //---------------------------------------------------------------------------
  4165. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4166. {
  4167. DebugAssert(Terminal);
  4168. DebugAssert(!IsLocalBrowserMode());
  4169. RemoteDirView->SaveSelection();
  4170. RemoteDirView->SaveSelectedNames();
  4171. try
  4172. {
  4173. if (Lock)
  4174. {
  4175. Terminal->LockFiles(FileList);
  4176. }
  4177. else
  4178. {
  4179. Terminal->UnlockFiles(FileList);
  4180. }
  4181. }
  4182. catch(...)
  4183. {
  4184. RemoteDirView->DiscardSavedSelection();
  4185. throw;
  4186. }
  4187. RemoteDirView->RestoreSelection();
  4188. }
  4189. //---------------------------------------------------------------------------
  4190. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4191. {
  4192. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4193. bool Result =
  4194. IsAvailableTerminal(ATerminal) &&
  4195. ATerminal->DirectoryExists(Directory);
  4196. return Result;
  4197. }
  4198. //---------------------------------------------------------------------------
  4199. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4200. {
  4201. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4202. return
  4203. !Terminal->IsCapable[fcRemoteCopy] ||
  4204. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4205. }
  4206. //---------------------------------------------------------------------------
  4207. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4208. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4209. bool NoConfirmation, bool Move)
  4210. {
  4211. DebugAssert(Terminal != NULL);
  4212. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4213. DebugAssert(!IsLocalBrowserMode());
  4214. if (Session == NULL)
  4215. {
  4216. Session = Terminal;
  4217. }
  4218. bool TargetConfirmed = false;
  4219. if (Session == Terminal)
  4220. {
  4221. if (RemoteDriveView->DropTarget != NULL)
  4222. {
  4223. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4224. TargetConfirmed = true;
  4225. }
  4226. else if (RemoteDirView->DropTarget != NULL)
  4227. {
  4228. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4229. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4230. TargetConfirmed = true;
  4231. }
  4232. else
  4233. {
  4234. Target = RemoteDirView->Path;
  4235. }
  4236. }
  4237. else
  4238. {
  4239. Target = GetSessionPath(Session, osRemote);
  4240. }
  4241. Target = UnixIncludeTrailingBackslash(Target);
  4242. if (FileList->Count == 1)
  4243. {
  4244. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4245. }
  4246. else
  4247. {
  4248. FileMask = AnyMask;
  4249. }
  4250. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4251. bool Result = true;
  4252. if (!NoConfirmation)
  4253. {
  4254. bool Multi = (FileList->Count > 1);
  4255. if (Move)
  4256. {
  4257. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4258. }
  4259. else
  4260. {
  4261. std::unique_ptr<TStrings> Sessions(new TStringList);
  4262. std::unique_ptr<TStrings> Directories(new TStringList);
  4263. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4264. for (int Index = 0; Index < SessionList->Count; Index++)
  4265. {
  4266. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4267. if (IsAvailableTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4268. {
  4269. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4270. Directories->Add(GetSessionPath(ASession, osRemote));
  4271. }
  4272. }
  4273. bool AnyDirectory = false;
  4274. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4275. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4276. {
  4277. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4278. {
  4279. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4280. }
  4281. }
  4282. TDirectRemoteCopy AllowDirectCopy;
  4283. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4284. {
  4285. DebugAssert(DirectCopy);
  4286. AllowDirectCopy = drcAllow;
  4287. }
  4288. else if (Terminal->IsCapable[fcSecondaryShell])
  4289. {
  4290. DebugAssert(DirectCopy);
  4291. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4292. }
  4293. else
  4294. {
  4295. DebugAssert(!DirectCopy);
  4296. AllowDirectCopy = drcDisallow;
  4297. }
  4298. void * ASession = Session;
  4299. Result = DoRemoteCopyDialog(
  4300. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4301. DoDirectoryExists, TargetConfirmed);
  4302. Session = static_cast<TManagedTerminal *>(ASession);
  4303. }
  4304. }
  4305. return Result;
  4306. }
  4307. //---------------------------------------------------------------------------
  4308. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4309. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4310. {
  4311. DebugAssert(!IsLocalBrowserMode());
  4312. bool DirectCopy;
  4313. UnicodeString Target, FileMask;
  4314. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4315. if (Result)
  4316. {
  4317. if (!Move && !DirectCopy)
  4318. {
  4319. Configuration->Usage->Inc("RemoteCopyTemp");
  4320. UnicodeString RootTempDir;
  4321. UnicodeString TempDir;
  4322. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true);
  4323. TStrings * TemporaryFilesList = new TStringList();
  4324. try
  4325. {
  4326. TMakeLocalFileListParams MakeFileListParam;
  4327. MakeFileListParam.FileList = TemporaryFilesList;
  4328. MakeFileListParam.FileTimes = NULL;
  4329. MakeFileListParam.IncludeDirs = true;
  4330. MakeFileListParam.Recursive = false;
  4331. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4332. TTerminalManager::Instance()->ActiveSession = Session;
  4333. if (TemporaryFilesList->Count > 0)
  4334. {
  4335. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4336. CopyParam.FileMask = FileMask;
  4337. DebugAssert(!FAutoOperation);
  4338. FAutoOperation = true;
  4339. FMoveToQueue = false;
  4340. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4341. }
  4342. }
  4343. __finally
  4344. {
  4345. delete TemporaryFilesList;
  4346. FAutoOperation = false;
  4347. if (!RootTempDir.IsEmpty())
  4348. {
  4349. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4350. }
  4351. }
  4352. }
  4353. else
  4354. {
  4355. RemoteDirView->SaveSelection();
  4356. RemoteDirView->SaveSelectedNames();
  4357. try
  4358. {
  4359. if (Move)
  4360. {
  4361. Configuration->Usage->Inc("RemoteMove");
  4362. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4363. }
  4364. else
  4365. {
  4366. Configuration->Usage->Inc("RemoteCopyDirect");
  4367. DebugAssert(DirectCopy);
  4368. DebugAssert(Session == Terminal);
  4369. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4370. Terminal->CommandSessionOpened ||
  4371. CommandSessionFallback())
  4372. {
  4373. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4374. }
  4375. }
  4376. }
  4377. catch(...)
  4378. {
  4379. RemoteDirView->DiscardSavedSelection();
  4380. throw;
  4381. }
  4382. RemoteDirView->RestoreSelection();
  4383. }
  4384. }
  4385. return Result;
  4386. }
  4387. //---------------------------------------------------------------------------
  4388. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4389. const UnicodeString & Path, TRemoteProperties & Properties)
  4390. {
  4391. DebugAssert(!IsLocalBrowserMode());
  4392. Properties.Valid = Properties.Valid << vpEncrypt;
  4393. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4394. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4395. }
  4396. //---------------------------------------------------------------------------
  4397. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4398. {
  4399. Side = GetSide(Side);
  4400. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4401. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4402. UnicodeString Name = LoadStr(NEW_FOLDER);
  4403. int AllowedChanges =
  4404. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4405. bool SaveSettings = false;
  4406. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4407. {
  4408. TWindowLock Lock(this);
  4409. if (!IsSideLocalBrowser(Side))
  4410. {
  4411. if (SaveSettings)
  4412. {
  4413. GUIConfiguration->NewDirectoryProperties = Properties;
  4414. }
  4415. CreateRemoteDirectory(Name, Properties);
  4416. }
  4417. else
  4418. {
  4419. DirView(Side)->CreateDirectory(Name);
  4420. }
  4421. }
  4422. }
  4423. //---------------------------------------------------------------------------
  4424. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4425. {
  4426. TWindowLock Lock(this);
  4427. DirView(Side)->ExecuteHomeDirectory();
  4428. }
  4429. //---------------------------------------------------------------------------
  4430. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4431. {
  4432. DoOpenDirectoryDialog(odBrowse, Side);
  4433. }
  4434. //---------------------------------------------------------------------------
  4435. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4436. {
  4437. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4438. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4439. bool Result = !Path.IsEmpty();
  4440. if (Result)
  4441. {
  4442. TryOpenDirectory(Side, Path);
  4443. }
  4444. return Result;
  4445. }
  4446. //---------------------------------------------------------------------------
  4447. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4448. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4449. bool & Close)
  4450. {
  4451. // terminal can be already closed (e.g. dropped connection)
  4452. if (Terminal != NULL)
  4453. {
  4454. try
  4455. {
  4456. TCalculateSizeParams Params;
  4457. Params.Stats = &Stats;
  4458. Terminal->CalculateFilesSize(FileList, Size, Params);
  4459. }
  4460. catch(...)
  4461. {
  4462. if (!Terminal->Active)
  4463. {
  4464. Close = true;
  4465. }
  4466. throw;
  4467. }
  4468. }
  4469. }
  4470. //---------------------------------------------------------------------------
  4471. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4472. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4473. bool & Close)
  4474. {
  4475. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4476. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4477. {
  4478. Configuration->Usage->Inc(L"ChecksumCalculated");
  4479. try
  4480. {
  4481. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4482. }
  4483. catch(...)
  4484. {
  4485. if (!Terminal->Active)
  4486. {
  4487. Close = true;
  4488. }
  4489. throw;
  4490. }
  4491. }
  4492. }
  4493. //---------------------------------------------------------------------------
  4494. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4495. {
  4496. if (Terminal->LoadFilesProperties(FileList))
  4497. {
  4498. RemoteDirView->Invalidate();
  4499. }
  4500. }
  4501. //---------------------------------------------------------------------------
  4502. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4503. {
  4504. return
  4505. Terminal->IsCapable[fcCalculatingChecksum] ||
  4506. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4507. }
  4508. //---------------------------------------------------------------------------
  4509. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4510. {
  4511. bool Result;
  4512. if (!IsSideLocalBrowser(Side))
  4513. {
  4514. TRemoteTokenList * GroupList = NULL;
  4515. TRemoteTokenList * UserList = NULL;
  4516. try
  4517. {
  4518. TRemoteProperties CurrentProperties;
  4519. LoadFilesProperties(FileList);
  4520. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4521. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4522. if (CapableGroupChanging || CapableOwnerChanging)
  4523. {
  4524. if (CapableGroupChanging)
  4525. {
  4526. GroupList = Terminal->Groups->Duplicate();
  4527. }
  4528. if (CapableOwnerChanging)
  4529. {
  4530. UserList = Terminal->Users->Duplicate();
  4531. }
  4532. TRemoteDirectory * Files = Terminal->Files;
  4533. int Count = Files->Count;
  4534. if (Count > 100)
  4535. {
  4536. Count = 100;
  4537. }
  4538. for (int Index = 0; Index < Count; Index++)
  4539. {
  4540. TRemoteFile * File = Files->Files[Index];
  4541. if (CapableGroupChanging)
  4542. {
  4543. GroupList->AddUnique(File->Group);
  4544. }
  4545. if (CapableOwnerChanging)
  4546. {
  4547. UserList->AddUnique(File->Owner);
  4548. }
  4549. }
  4550. // if we haven't collected tokens for all files in current directory,
  4551. // make sure we collect them at least for all selected files.
  4552. // (note that so far the files in FileList has to be from current direcotry)
  4553. if (Count < Files->Count)
  4554. {
  4555. for (int Index = 0; Index < FileList->Count; Index++)
  4556. {
  4557. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4558. if (CapableGroupChanging)
  4559. {
  4560. GroupList->AddUnique(File->Group);
  4561. }
  4562. if (CapableOwnerChanging)
  4563. {
  4564. UserList->AddUnique(File->Owner);
  4565. }
  4566. }
  4567. }
  4568. }
  4569. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4570. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4571. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4572. {
  4573. CapableAclChanging = false;
  4574. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4575. }
  4576. int Flags = 0;
  4577. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4578. if (CapableAclChanging) Flags |= cpAcl;
  4579. if (CapableOwnerChanging) Flags |= cpOwner;
  4580. if (CapableGroupChanging) Flags |= cpGroup;
  4581. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4582. if (CanCalculateChecksum())
  4583. {
  4584. CalculateChecksumEvent = CalculateChecksum;
  4585. }
  4586. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4587. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4588. int Options =
  4589. FLAGMASK(Terminal->IsCapable[fcGroupOwnerChangingByID], poUserGroupByID) |
  4590. FLAGMASK(Terminal->IsCapable[fcTags], poTags);
  4591. TRemoteProperties NewProperties = CurrentProperties;
  4592. Result =
  4593. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4594. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags, Options,
  4595. CalculateSize, CalculateChecksumEvent);
  4596. if (Result)
  4597. {
  4598. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4599. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4600. }
  4601. }
  4602. __finally
  4603. {
  4604. delete GroupList;
  4605. delete UserList;
  4606. }
  4607. }
  4608. else
  4609. {
  4610. DirView(Side)->DisplayPropertiesMenu();
  4611. Result = true;
  4612. }
  4613. return Result;
  4614. }
  4615. //---------------------------------------------------------------------------
  4616. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4617. {
  4618. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4619. {
  4620. FIgnoreNextDialogChar = Key;
  4621. }
  4622. Key = 0;
  4623. }
  4624. //---------------------------------------------------------------------------
  4625. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4626. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4627. {
  4628. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4629. if (Command != NULL)
  4630. {
  4631. KeyProcessed(Key, Shift);
  4632. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4633. {
  4634. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4635. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4636. false, false, const_cast<TCustomCommandType *>(Command));
  4637. }
  4638. }
  4639. }
  4640. //---------------------------------------------------------------------------
  4641. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4642. {
  4643. if (!NonVisualDataModule->Busy)
  4644. {
  4645. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4646. {
  4647. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4648. }
  4649. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4650. {
  4651. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4652. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4653. {
  4654. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4655. // But so far it's not a problem, as it does what we want.
  4656. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4657. if (((Action->ShortCut == KeyShortCut) ||
  4658. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4659. AllowedAction(Action, aaShortCut))
  4660. {
  4661. // Has to be called before the action as the dialog char is already in queue.
  4662. // So when the action consumes message queue, we already need to have the
  4663. // FIgnoreNextDialogChar set
  4664. KeyProcessed(Key, Shift);
  4665. // Reset reference to previous component (when menu/toolbar was clicked).
  4666. // Needed to detect that action was invoked by keyboard shortcut
  4667. // in TNonVisualDataModule::ExplorerActionsExecute
  4668. Action->ActionComponent = NULL;
  4669. Action->Execute();
  4670. return;
  4671. }
  4672. }
  4673. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4674. {
  4675. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4676. {
  4677. KeyProcessed(Key, Shift);
  4678. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4679. return;
  4680. }
  4681. }
  4682. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4683. {
  4684. KeyProcessed(Key, Shift);
  4685. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4686. }
  4687. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4688. if (IsCustomShortCut(CustomShortCut))
  4689. {
  4690. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4691. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4692. if (WinConfiguration->SharedBookmarks != NULL)
  4693. {
  4694. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4695. if ((Bookmark != NULL) &&
  4696. OpenBookmark(FCurrentSide, Bookmark))
  4697. {
  4698. KeyProcessed(Key, Shift);
  4699. }
  4700. }
  4701. }
  4702. }
  4703. }
  4704. TForm::KeyDown(Key, Shift);
  4705. }
  4706. //---------------------------------------------------------------------------
  4707. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4708. {
  4709. bool OpenedTerminal = false;
  4710. UnicodeString ProtocolName;
  4711. UnicodeString ProtocolNameHint;
  4712. UnicodeString SecurityProtocolName;
  4713. UnicodeString DurationHint;
  4714. // See the comment in TScpCommanderForm::UpdateControls()
  4715. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4716. if (ActiveTerminal != NULL)
  4717. {
  4718. // Active is not enough here
  4719. if (ActiveTerminal->Status == ssOpened)
  4720. {
  4721. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4722. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4723. if (FileSystemInfo.ProtocolName.IsEmpty())
  4724. {
  4725. ProtocolName = SessionInfo.ProtocolName;
  4726. }
  4727. else
  4728. {
  4729. ProtocolName = FileSystemInfo.ProtocolName;
  4730. }
  4731. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4732. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4733. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4734. OpenedTerminal = true;
  4735. }
  4736. else if (ActiveTerminal->Status > ssClosed)
  4737. {
  4738. ProtocolName = LoadStr(STATUS_CONNECTING);
  4739. }
  4740. else
  4741. {
  4742. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4743. }
  4744. }
  4745. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4746. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4747. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4748. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4749. if (ProtocolStatusPanel->Caption != ProtocolName)
  4750. {
  4751. ProtocolStatusPanel->Caption = ProtocolName;
  4752. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4753. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4754. }
  4755. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4756. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4757. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4758. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4759. SecurityStatusPanel->Enabled = SecurityEnabled;
  4760. UnicodeString SecurityProtocolHint;
  4761. if (SecurityEnabled)
  4762. {
  4763. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4764. }
  4765. else
  4766. {
  4767. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4768. }
  4769. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4770. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4771. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4772. DurationStatusPanel->Hint = DurationHint;
  4773. UpdateStatusBar();
  4774. }
  4775. //---------------------------------------------------------------------------
  4776. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4777. {
  4778. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4779. DebugAssert(SessionStatusBar != NULL);
  4780. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4781. if (!FNote.IsEmpty())
  4782. {
  4783. NoteStatusPanel->Caption = FNote;
  4784. }
  4785. else
  4786. {
  4787. UpdateStatusPanelText(NoteStatusPanel);
  4788. }
  4789. NoteStatusPanel->Hint = FNoteHints;
  4790. UnicodeString LoginTime;
  4791. // See the comment in TScpCommanderForm::UpdateControls()
  4792. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4793. // Active is not enough here
  4794. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4795. {
  4796. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4797. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4798. }
  4799. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4800. DurationStatusPanel->Caption = LoginTime;
  4801. }
  4802. //---------------------------------------------------------------------------
  4803. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4804. {
  4805. Panel->Caption = L"";
  4806. }
  4807. //---------------------------------------------------------------------------
  4808. void __fastcall TCustomScpExplorerForm::Idle()
  4809. {
  4810. if (FShowing ||
  4811. // Particularly for
  4812. // - Standalone editing
  4813. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4814. // while "keeping remote directory up to date".
  4815. StandaloneOperation)
  4816. {
  4817. FEditorManager->Check();
  4818. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4819. // that needs to know if queue view is visible (and it may be closed after queue update)
  4820. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4821. }
  4822. if (FShowing)
  4823. {
  4824. if (!NonVisualDataModule->Busy &&
  4825. // Menu is opened or drag&drop is going on
  4826. (Mouse->Capture == NULL))
  4827. {
  4828. if (FRefreshRemoteDirectory)
  4829. {
  4830. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4831. {
  4832. Terminal->RefreshDirectory();
  4833. }
  4834. FRefreshRemoteDirectory = false;
  4835. }
  4836. if (FRefreshLocalDirectory)
  4837. {
  4838. ReloadLocalDirectory();
  4839. FRefreshLocalDirectory = false;
  4840. }
  4841. if (WinConfiguration->RefreshRemotePanel)
  4842. {
  4843. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4844. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4845. {
  4846. RemoteDirView->ReloadDirectory();
  4847. }
  4848. }
  4849. }
  4850. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4851. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4852. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4853. // 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.
  4854. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4855. MenuToolbar->Idle();
  4856. }
  4857. if (FShowing || StandaloneOperation)
  4858. {
  4859. if (FQueueStatusInvalidated)
  4860. {
  4861. UpdateQueueStatus(false);
  4862. }
  4863. RefreshQueueItems();
  4864. }
  4865. if (FShowing)
  4866. {
  4867. UpdateStatusBar();
  4868. }
  4869. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4870. {
  4871. FClipboardFakeMonitorsPendingReset = false;
  4872. FClipboardFakeMonitors.reset(NULL);
  4873. }
  4874. FIgnoreNextDialogChar = 0;
  4875. }
  4876. //---------------------------------------------------------------------------
  4877. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4878. {
  4879. try
  4880. {
  4881. FUserActionTimer->Enabled = false;
  4882. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4883. {
  4884. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4885. {
  4886. FPendingQueueActionItem->ProcessUserAction();
  4887. }
  4888. }
  4889. }
  4890. __finally
  4891. {
  4892. FPendingQueueActionItem = NULL;
  4893. }
  4894. }
  4895. //---------------------------------------------------------------------------
  4896. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4897. {
  4898. if (WinConfiguration->MinimizeToTray)
  4899. {
  4900. UpdateTrayIcon();
  4901. FTrayIcon->Visible = true;
  4902. if (Visible)
  4903. {
  4904. ShowWindow(Handle, SW_HIDE);
  4905. }
  4906. }
  4907. }
  4908. //---------------------------------------------------------------------------
  4909. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4910. {
  4911. // WORKAROUND
  4912. // When restoring maximized window from minimization,
  4913. // rarely some controls do not align properly.
  4914. // Two instances seen (both for Commander):
  4915. // - When restoring, window is temporarily narrower (not maximized),
  4916. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4917. // Once maximized already, top dock shinks back, but the session PageControl,
  4918. // do not align up, leaving space between TopDock and PageControl.
  4919. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4920. for (int Index = 0; Index < ControlCount; Index++)
  4921. {
  4922. RealignControl(Controls[Index]);
  4923. }
  4924. if (FTrayIcon->Visible)
  4925. {
  4926. FTrayIcon->Visible = false;
  4927. if (Visible)
  4928. {
  4929. ShowWindow(Handle, SW_SHOW);
  4930. }
  4931. }
  4932. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4933. {
  4934. FNeedSession = false;
  4935. NonVisualDataModule->StartBusy();
  4936. try
  4937. {
  4938. NeedSession(true);
  4939. }
  4940. __finally
  4941. {
  4942. NonVisualDataModule->EndBusy();
  4943. }
  4944. }
  4945. }
  4946. //---------------------------------------------------------------------------
  4947. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4948. {
  4949. FTrayIcon->Hint = GetMainForm()->Caption;
  4950. }
  4951. //---------------------------------------------------------------------------
  4952. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4953. {
  4954. UpdateTrayIcon();
  4955. }
  4956. //---------------------------------------------------------------------------
  4957. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4958. {
  4959. // workaround
  4960. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4961. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4962. // But WM_ACTIVATEAPP message can be received even when
  4963. // the main window is minimized to the tray and internal editor window is focused
  4964. // (after another application was previously active)
  4965. if (::IsIconic(Handle))
  4966. {
  4967. if (!IsAppIconic())
  4968. {
  4969. SetAppIconic(true);
  4970. }
  4971. }
  4972. ::ApplicationRestore();
  4973. Application->BringToFront();
  4974. }
  4975. //---------------------------------------------------------------------------
  4976. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4977. {
  4978. RestoreApp();
  4979. }
  4980. //---------------------------------------------------------------------------
  4981. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4982. {
  4983. if (OpenInNewWindow())
  4984. {
  4985. ExecuteNewInstance(SessionUrl);
  4986. }
  4987. else
  4988. {
  4989. TTerminalManager::Instance()->NewSession(SessionUrl);
  4990. }
  4991. }
  4992. //---------------------------------------------------------------------------
  4993. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4994. {
  4995. NewSession();
  4996. }
  4997. //---------------------------------------------------------------------------
  4998. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4999. {
  5000. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  5001. StoredSessions->NewSession(SessionName, SessionData);
  5002. // modified only, explicit
  5003. StoredSessions->Save(false, true);
  5004. // encode session name because of slashes in hierarchical sessions
  5005. return EncodeUrlString(SessionName);
  5006. }
  5007. //---------------------------------------------------------------------------
  5008. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  5009. {
  5010. // current working directories become defaults here, what is not right
  5011. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5012. return SaveHiddenDuplicateSession(SessionData.get());
  5013. }
  5014. //---------------------------------------------------------------------------
  5015. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  5016. {
  5017. if (OpenInNewWindow())
  5018. {
  5019. ExecuteNewInstance(CreateHiddenDuplicateSession());
  5020. }
  5021. else
  5022. {
  5023. // current working directories become defaults here, what is not right
  5024. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  5025. TTerminalManager * Manager = TTerminalManager::Instance();
  5026. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  5027. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  5028. // We definitely want these
  5029. ASession->Disconnected = ManagedSession->Disconnected;
  5030. // Not sure about these two
  5031. ASession->Permanent = ManagedSession->Permanent;
  5032. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  5033. Manager->ActiveSession = ASession;
  5034. }
  5035. }
  5036. //---------------------------------------------------------------------------
  5037. void __fastcall TCustomScpExplorerForm::RenameTab()
  5038. {
  5039. UnicodeString Name = ManagedSession->SessionData->SessionName;
  5040. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  5041. // When submitting the default name, do not fix it
  5042. (Name != ManagedSession->SessionData->SessionName))
  5043. {
  5044. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5045. TSessionData::ValidateName(Name);
  5046. // This is inconsistent with how color (for example) is handled.
  5047. ManagedSession->SessionData->Name = Name;
  5048. UpdateControls();
  5049. // Add/Remove distinguishing paths from sessions of the same name.
  5050. SessionListChanged();
  5051. }
  5052. }
  5053. //---------------------------------------------------------------------------
  5054. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5055. {
  5056. DebugAssert(Queue != NULL);
  5057. bool Result = Queue->IsEmpty;
  5058. if (!Result)
  5059. {
  5060. SetFocus();
  5061. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5062. }
  5063. return Result;
  5064. }
  5065. //---------------------------------------------------------------------------
  5066. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5067. {
  5068. return CanCloseQueue(FQueue);
  5069. }
  5070. //---------------------------------------------------------------------------
  5071. void __fastcall TCustomScpExplorerForm::CloseTab()
  5072. {
  5073. if (CanCloseQueue())
  5074. {
  5075. TTerminalManager::Instance()->FreeActiveTerminal();
  5076. }
  5077. }
  5078. //---------------------------------------------------------------------------
  5079. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5080. {
  5081. if (CanCloseQueue())
  5082. {
  5083. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5084. }
  5085. }
  5086. //---------------------------------------------------------------------------
  5087. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5088. {
  5089. DetachTerminal(Terminal);
  5090. RemoteDirView->Terminal = Terminal;
  5091. UpdateRemotePathComboBox(false);
  5092. InitStatusBar();
  5093. UpdateControls();
  5094. }
  5095. //---------------------------------------------------------------------------
  5096. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5097. {
  5098. InitStatusBar();
  5099. }
  5100. //---------------------------------------------------------------------------
  5101. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5102. {
  5103. if (DebugAlwaysTrue(!Terminal->Active))
  5104. {
  5105. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5106. }
  5107. }
  5108. //---------------------------------------------------------------------------
  5109. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5110. {
  5111. if (OpenInNewWindow())
  5112. {
  5113. // encode session name because of slashes in hierarchical sessions
  5114. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5115. }
  5116. else
  5117. {
  5118. TTerminalManager * Manager = TTerminalManager::Instance();
  5119. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5120. Manager->ActiveSession = Terminal;
  5121. }
  5122. }
  5123. //---------------------------------------------------------------------------
  5124. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5125. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5126. {
  5127. TTerminalManager * Manager = TTerminalManager::Instance();
  5128. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5129. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5130. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5131. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5132. {
  5133. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5134. // FirstSession can be null, if none of the workspace sites exist anymore
  5135. // or if all workspace sessions are not suported by the interface
  5136. // (when trying to open all local-local workspace in "explorer" interface)
  5137. if (FirstSession != NULL)
  5138. {
  5139. if (!ConnectFirstTerminal)
  5140. {
  5141. FirstSession->Disconnected = true;
  5142. FirstSession->DisconnectedTemporarily = true;
  5143. }
  5144. Manager->ActiveSession = FirstSession;
  5145. }
  5146. }
  5147. }
  5148. //---------------------------------------------------------------------------
  5149. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5150. {
  5151. if (OpenInNewWindow())
  5152. {
  5153. ExecuteNewInstance(Name);
  5154. }
  5155. else
  5156. {
  5157. DoOpenFolderOrWorkspace(Name, true, false);
  5158. }
  5159. }
  5160. //---------------------------------------------------------------------------
  5161. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5162. bool &CanClose)
  5163. {
  5164. AppLog(L"Windows close query");
  5165. // See the comment in CloseApp()
  5166. if (NonVisualDataModule->Busy)
  5167. {
  5168. CanClose = false;
  5169. }
  5170. else
  5171. {
  5172. TTerminalManager * Manager = TTerminalManager::Instance();
  5173. int ActiveSessions = 0;
  5174. for (int Index = 0; Index < Manager->Count; Index++)
  5175. {
  5176. if (Manager->Sessions[Index]->Active)
  5177. {
  5178. ActiveSessions++;
  5179. }
  5180. }
  5181. // Confirm, when there's at least one active remote session or
  5182. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5183. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5184. WinConfiguration->ConfirmClosingSession)
  5185. {
  5186. unsigned int Result;
  5187. TMessageParams Params(mpNeverAskAgainCheck);
  5188. UnicodeString Message;
  5189. int Answers = qaOK | qaCancel;
  5190. // The current session is the only active session
  5191. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5192. {
  5193. if (!WinConfiguration->AutoSaveWorkspace)
  5194. {
  5195. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5196. }
  5197. else
  5198. {
  5199. Message = LoadStr(CLOSE_SESSION);
  5200. }
  5201. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5202. }
  5203. // Multiple active sessions or one active session, but it's not the current one
  5204. else if (ActiveSessions > 0)
  5205. {
  5206. if (!WinConfiguration->AutoSaveWorkspace)
  5207. {
  5208. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5209. }
  5210. else
  5211. {
  5212. Message = LoadStr(CLOSE_SESSIONS);
  5213. }
  5214. }
  5215. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5216. else
  5217. {
  5218. DebugAssert(Manager->Count > 1);
  5219. DebugAssert(!WinConfiguration->AutoSaveWorkspace);
  5220. Message = LoadStr(CLOSE_WORKSPACE);
  5221. }
  5222. UnicodeString Note;
  5223. if (WinConfiguration->AutoSaveWorkspace)
  5224. {
  5225. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5226. }
  5227. else
  5228. {
  5229. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5230. Answers = qaYes | qaNo | qaCancel;
  5231. }
  5232. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5233. SetFocus();
  5234. Result = MessageDialog(Message, qtConfirmation,
  5235. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5236. if (Result == qaNeverAskAgain)
  5237. {
  5238. WinConfiguration->ConfirmClosingSession = false;
  5239. }
  5240. if (Result == qaNo)
  5241. {
  5242. CanClose = SaveWorkspace(true);
  5243. // note that the workspace will be saved redundatly again from FormClose
  5244. }
  5245. else
  5246. {
  5247. CanClose =
  5248. (Result == qaOK) ||
  5249. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5250. (Result == qaNeverAskAgain);
  5251. }
  5252. }
  5253. if (CanClose && HasAvailableTerminal())
  5254. {
  5255. CanClose = CanCloseQueue();
  5256. }
  5257. }
  5258. if (CanClose)
  5259. {
  5260. CanClose =
  5261. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5262. FEditorManager->CloseExternalFilesWithoutProcess();
  5263. if (CanClose)
  5264. {
  5265. while (CanClose && (FLocalEditors->Count > 0))
  5266. {
  5267. int PrevCount = FLocalEditors->Count;
  5268. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5269. CanClose = (FLocalEditors->Count < PrevCount);
  5270. }
  5271. if (CanClose)
  5272. {
  5273. CanClose = FEditorManager->Empty(true);
  5274. if (!CanClose)
  5275. {
  5276. SetFocus();
  5277. CanClose =
  5278. (MessageDialog(
  5279. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5280. }
  5281. }
  5282. }
  5283. }
  5284. }
  5285. //---------------------------------------------------------------------------
  5286. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5287. {
  5288. TForm * Form = dynamic_cast<TForm *>(Sender);
  5289. DebugAssert(Form != NULL);
  5290. Form->Close();
  5291. }
  5292. //---------------------------------------------------------------------------
  5293. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5294. {
  5295. TForm * Form = dynamic_cast<TForm *>(Sender);
  5296. delete Form;
  5297. }
  5298. //---------------------------------------------------------------------------
  5299. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5300. {
  5301. while (FLocalEditors->Count > 0)
  5302. {
  5303. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5304. }
  5305. }
  5306. //---------------------------------------------------------------------------
  5307. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5308. TObject *Sender)
  5309. {
  5310. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5311. try
  5312. {
  5313. SetProperties(osRemote, FileList);
  5314. }
  5315. __finally
  5316. {
  5317. delete FileList;
  5318. }
  5319. }
  5320. //---------------------------------------------------------------------------
  5321. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5322. {
  5323. if (value)
  5324. {
  5325. if (Component == fcCustomCommandsBand)
  5326. {
  5327. UpdateCustomCommandsToolbar();
  5328. }
  5329. if (Component == fcQueueFileList)
  5330. {
  5331. DebugAssert(!QueueFileListSplitter->Visible);
  5332. AdjustQueueLayout();
  5333. UpdateQueueFileList();
  5334. }
  5335. }
  5336. }
  5337. //---------------------------------------------------------------------------
  5338. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5339. {
  5340. int MinHeightLimit =
  5341. GetStaticQueuePanelComponentsHeight() +
  5342. QueueFileListSplitter->Height +
  5343. QueueFileList->Height +
  5344. GetMinQueueViewHeight();
  5345. if (QueuePanel->ClientHeight < MinHeightLimit)
  5346. {
  5347. QueuePanel->ClientHeight = MinHeightLimit;
  5348. }
  5349. }
  5350. //---------------------------------------------------------------------------
  5351. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5352. {
  5353. TControl * Control = GetComponent(Component);
  5354. DebugAssert(Control);
  5355. bool Changed = (Control->Visible != value);
  5356. if (Changed)
  5357. {
  5358. ComponentShowing(Component, value);
  5359. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5360. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5361. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5362. if (value)
  5363. {
  5364. int RemainingHeight = Control->Parent->ClientHeight;
  5365. int RemainingWidth = Control->Parent->ClientWidth;
  5366. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5367. {
  5368. TControl * ChildControl = Control->Parent->Controls[i];
  5369. if (ChildControl->Visible)
  5370. {
  5371. switch (ChildControl->Align)
  5372. {
  5373. case alTop:
  5374. case alBottom:
  5375. RemainingHeight -= ChildControl->Height;
  5376. break;
  5377. case alLeft:
  5378. case alRight:
  5379. RemainingWidth -= ChildControl->Width;
  5380. break;
  5381. }
  5382. }
  5383. }
  5384. int Reserve = ScaleByTextHeight(this, 32);
  5385. // queue in explorer, trees in commander
  5386. if (Control->Height > RemainingHeight - Reserve)
  5387. {
  5388. Control->Height = RemainingHeight / 2;
  5389. }
  5390. if (Control->Width > RemainingWidth - Reserve)
  5391. {
  5392. Control->Width = RemainingWidth / 2;
  5393. }
  5394. }
  5395. Control->Visible = value;
  5396. if (WasFocused && Visible)
  5397. {
  5398. DirView(osCurrent)->SetFocus();
  5399. }
  5400. FixControlsPlacement();
  5401. }
  5402. }
  5403. //---------------------------------------------------------------------------
  5404. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5405. {
  5406. TControl * Control = GetComponent(Component);
  5407. if (Control == NULL)
  5408. {
  5409. return false;
  5410. }
  5411. else
  5412. {
  5413. return Control->Visible;
  5414. }
  5415. }
  5416. //---------------------------------------------------------------------------
  5417. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5418. {
  5419. bool Result;
  5420. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5421. {
  5422. Result = !IsUWP();
  5423. }
  5424. else
  5425. {
  5426. Result = true;
  5427. }
  5428. return Result;
  5429. }
  5430. //---------------------------------------------------------------------------
  5431. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5432. {
  5433. if (DirView->ItemFocused != NULL)
  5434. {
  5435. DirView->ItemFocused->MakeVisible(false);
  5436. }
  5437. }
  5438. //---------------------------------------------------------------------------
  5439. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5440. {
  5441. MakeFocusedItemVisible(RemoteDirView);
  5442. QueueSplitter->Visible = QueuePanel->Visible;
  5443. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5444. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5445. TControl * TopControlsOrder[] =
  5446. { TopDock, MessageDock, SessionsPageControl };
  5447. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5448. TControl * QueueControlsOrder[] =
  5449. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5450. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5451. }
  5452. //---------------------------------------------------------------------------
  5453. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5454. {
  5455. switch (Component) {
  5456. case fcStatusBar: return RemoteStatusBar;
  5457. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5458. case fcQueueView: return QueuePanel;
  5459. case fcQueueToolbar: return QueueDock;
  5460. case fcRemoteTree: return RemoteDrivePanel;
  5461. case fcSessionsTabs: return SessionsPageControl;
  5462. case fcQueueFileList: return QueueFileList;
  5463. default: return NULL;
  5464. }
  5465. }
  5466. //---------------------------------------------------------------------------
  5467. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5468. TObject *Sender, TListColumn *Column, TPoint &Point)
  5469. {
  5470. DebugAssert(NonVisualDataModule && Column && Sender);
  5471. NonVisualDataModule->ListColumn = Column;
  5472. TPopupMenu * DirViewColumnMenu;
  5473. if (Sender == DirView(osOther))
  5474. {
  5475. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5476. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5477. bool SizeColumn = (Column->Index == uvSize);
  5478. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5479. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5480. }
  5481. else
  5482. {
  5483. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5484. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5485. bool SizeColumn = (Column->Index == dvSize);
  5486. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5487. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5488. }
  5489. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5490. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5491. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5492. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5493. }
  5494. //---------------------------------------------------------------------------
  5495. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5496. TObject *Sender, TListItem *Item, bool &AllowExec)
  5497. {
  5498. DoDirViewExecFile(Sender, Item, AllowExec);
  5499. }
  5500. //---------------------------------------------------------------------------
  5501. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5502. TListItem * Item, bool & AllowExec)
  5503. {
  5504. DebugAssert(Sender && Item && Configuration);
  5505. DebugAssert(AllowExec);
  5506. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5507. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5508. bool Remote = !IsSideLocalBrowser(Side);
  5509. DebugAssert(Item == ADirView->ItemFocused);
  5510. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5511. TResolvedDoubleClickAction Action;
  5512. if (FForceExecution)
  5513. {
  5514. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5515. }
  5516. else
  5517. {
  5518. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5519. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5520. }
  5521. if (Action == rdcaCopy)
  5522. {
  5523. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5524. UnlockWindow();
  5525. try
  5526. {
  5527. if (IsLocalBrowserMode())
  5528. {
  5529. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5530. }
  5531. else
  5532. {
  5533. if (HasAvailableTerminal())
  5534. {
  5535. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5536. }
  5537. }
  5538. }
  5539. __finally
  5540. {
  5541. LockWindow();
  5542. }
  5543. AllowExec = false;
  5544. }
  5545. else if (Action == rdcaEdit)
  5546. {
  5547. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5548. {
  5549. ExecuteFile(Side, efDefaultEditor);
  5550. AllowExec = false;
  5551. }
  5552. }
  5553. else if (Action == rdcaOpen)
  5554. {
  5555. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5556. {
  5557. ExecuteFile(osRemote, efShell);
  5558. AllowExec = false;
  5559. }
  5560. }
  5561. }
  5562. //---------------------------------------------------------------------------
  5563. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5564. {
  5565. return ((Side == osRemote) || (Side == osCurrent));
  5566. }
  5567. //---------------------------------------------------------------------------
  5568. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5569. {
  5570. DebugFail();
  5571. }
  5572. //---------------------------------------------------------------------------
  5573. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5574. {
  5575. DebugFail();
  5576. }
  5577. //---------------------------------------------------------------------------
  5578. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5579. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5580. {
  5581. TSynchronizeParamType Params;
  5582. Params.LocalDirectory = LocalDirectory;
  5583. Params.RemoteDirectory = RemoteDirectory;
  5584. int UnusedParams =
  5585. (GUIConfiguration->SynchronizeParams &
  5586. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5587. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5588. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5589. Params.Options = GUIConfiguration->SynchronizeOptions;
  5590. bool SaveSettings = false;
  5591. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5592. &DoSynchronizeTooManyDirectories);
  5593. DebugAssert(FSynchronizeController == NULL);
  5594. FSynchronizeController = &Controller;
  5595. bool Result;
  5596. try
  5597. {
  5598. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5599. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5600. int Options =
  5601. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5602. DebugAssert(FOnFeedSynchronizeError == NULL);
  5603. DebugAssert(FOnSynchronizeAbort == NULL);
  5604. DebugAssert(FSynchronizeTerminal == NULL);
  5605. FSynchronizeTerminal = Terminal;
  5606. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5607. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5608. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5609. if (Result)
  5610. {
  5611. if (SaveSettings)
  5612. {
  5613. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5614. GUIConfiguration->SynchronizeOptions = Params.Options;
  5615. }
  5616. else
  5617. {
  5618. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5619. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5620. FLAGSET(Params.Options, soSynchronize))
  5621. {
  5622. GUIConfiguration->SynchronizeOptions =
  5623. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5624. soSynchronize;
  5625. }
  5626. }
  5627. LocalDirectory = Params.LocalDirectory;
  5628. RemoteDirectory = Params.RemoteDirectory;
  5629. }
  5630. }
  5631. __finally
  5632. {
  5633. FSynchronizeController = NULL;
  5634. DebugAssert(FOnFeedSynchronizeError == NULL);
  5635. FOnFeedSynchronizeError = NULL;
  5636. DebugAssert(FOnSynchronizeAbort == NULL);
  5637. FOnSynchronizeAbort = NULL;
  5638. FSynchronizeTerminal = NULL;
  5639. }
  5640. return Result;
  5641. }
  5642. //---------------------------------------------------------------------------
  5643. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5644. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5645. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5646. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5647. TSynchronizeOptions * Options, bool Full)
  5648. {
  5649. // Keep-up-to-date mode
  5650. if (Terminal->Status == ssOpened)
  5651. {
  5652. try
  5653. {
  5654. int PParams = Params.Params;
  5655. if (!Full)
  5656. {
  5657. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5658. if (FLAGSET(Params.Options, soRecurse))
  5659. {
  5660. PParams |= TTerminal::spSubDirs;
  5661. }
  5662. }
  5663. else
  5664. {
  5665. // if keepuptodate is non-recursive,
  5666. // full sync before has to be non-recursive as well
  5667. if (FLAGCLEAR(Params.Options, soRecurse))
  5668. {
  5669. PParams |= TTerminal::spNoRecurse;
  5670. }
  5671. }
  5672. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5673. PParams, Checklist, Options);
  5674. }
  5675. catch (Exception & E)
  5676. {
  5677. if (!Terminal->Active)
  5678. {
  5679. ShowExtendedExceptionEx(Terminal, &E);
  5680. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5681. if (!Terminal->Active)
  5682. {
  5683. throw;
  5684. }
  5685. }
  5686. else
  5687. {
  5688. if (FLAGSET(Params.Options, soContinueOnError) &&
  5689. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5690. {
  5691. // noop, already logged in MoreMessageDialog
  5692. }
  5693. else
  5694. {
  5695. // We get mostly EAbort here, so this is noop.
  5696. // Exception is an error when listing directories while looking for differences.
  5697. ShowExtendedExceptionEx(Terminal, &E);
  5698. throw;
  5699. }
  5700. }
  5701. }
  5702. }
  5703. }
  5704. //---------------------------------------------------------------------------
  5705. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5706. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5707. const UnicodeString ErrorStr)
  5708. {
  5709. if (!Directory.IsEmpty())
  5710. {
  5711. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5712. }
  5713. else
  5714. {
  5715. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5716. }
  5717. }
  5718. //---------------------------------------------------------------------------
  5719. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5720. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5721. {
  5722. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5723. {
  5724. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5725. }
  5726. else
  5727. {
  5728. TMessageParams Params(mpNeverAskAgainCheck);
  5729. unsigned int Result = MessageDialog(
  5730. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5731. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5732. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5733. {
  5734. MaxDirectories *= 2;
  5735. if (Result == qaNeverAskAgain)
  5736. {
  5737. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5738. }
  5739. }
  5740. else
  5741. {
  5742. Abort();
  5743. }
  5744. }
  5745. }
  5746. //---------------------------------------------------------------------------
  5747. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5748. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5749. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5750. TSynchronizeOptions * Options)
  5751. {
  5752. // Keep-up-to-date mode
  5753. DebugAssert(!FAutoOperation);
  5754. void * BatchStorage;
  5755. BatchStart(BatchStorage);
  5756. FAutoOperation = true;
  5757. bool AnyOperation = false;
  5758. TDateTime StartTime = Now();
  5759. TSynchronizeChecklist * AChecklist = NULL;
  5760. TObjectReleaser<TSynchronizeProgressForm> SynchronizeProgressFormReleaser(FSynchronizeProgressForm, new TSynchronizeProgressForm(Application, true, -1));
  5761. try
  5762. {
  5763. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5764. {
  5765. FSynchronizeProgressForm->Start();
  5766. }
  5767. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5768. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5769. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5770. Options);
  5771. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5772. SAFE_DESTROY(FSynchronizeProgressForm);
  5773. AnyOperation = (AChecklist->CheckedCount > 0);
  5774. if (AnyOperation)
  5775. {
  5776. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5777. CreateProgressForm(&SynchronizeProgress);
  5778. try
  5779. {
  5780. Terminal->SynchronizeApply(
  5781. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5782. SynchronizeProcessedItem, NULL, NULL, NULL);
  5783. }
  5784. __finally
  5785. {
  5786. DestroyProgressForm();
  5787. }
  5788. }
  5789. }
  5790. __finally
  5791. {
  5792. if (Checklist == NULL)
  5793. {
  5794. delete AChecklist;
  5795. }
  5796. else
  5797. {
  5798. *Checklist = AChecklist;
  5799. }
  5800. FAutoOperation = false;
  5801. SynchronizeProgressFormReleaser.Reset();
  5802. BatchEnd(BatchStorage);
  5803. ReloadLocalDirectory();
  5804. if (AnyOperation)
  5805. {
  5806. OperationComplete(StartTime);
  5807. }
  5808. }
  5809. }
  5810. //---------------------------------------------------------------------------
  5811. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5812. {
  5813. // can be called from command line
  5814. return Visible &&
  5815. ((DirView(osRemote)->SelCount > 0) ||
  5816. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5817. }
  5818. //---------------------------------------------------------------------------
  5819. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5820. {
  5821. LogSynchronizeEvent(Terminal, Message);
  5822. }
  5823. //---------------------------------------------------------------------------
  5824. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5825. int Params, TSynchronizeOptions & Options)
  5826. {
  5827. DebugAssert(!IsLocalBrowserMode());
  5828. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5829. {
  5830. Options.Filter = new TStringList();
  5831. Options.Filter->CaseSensitive = false;
  5832. Options.Filter->Duplicates = Types::dupAccept;
  5833. if (DirView(osRemote)->SelCount > 0)
  5834. {
  5835. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5836. }
  5837. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5838. {
  5839. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5840. }
  5841. Options.Filter->Sort();
  5842. }
  5843. }
  5844. //---------------------------------------------------------------------------
  5845. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5846. {
  5847. TCopyParamType Defaults;
  5848. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5849. ConfigStorage->AccessMode = smRead;
  5850. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5851. {
  5852. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5853. }
  5854. ConfigStorage.reset(NULL);
  5855. std::unique_ptr<TStringList> Options(new TStringList());
  5856. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5857. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5858. UnicodeString Result;
  5859. if (Options->Count > 0)
  5860. {
  5861. Result =
  5862. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5863. }
  5864. return Result;
  5865. }
  5866. //---------------------------------------------------------------------------
  5867. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5868. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5869. {
  5870. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5871. UnicodeString AdditionalParams =
  5872. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5873. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5874. SerializeCopyParamForCommandLine(CopyParams),
  5875. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5876. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5877. ExecuteNewInstance(SessionName, AdditionalParams);
  5878. }
  5879. //---------------------------------------------------------------------------
  5880. struct TSynchronizeParams
  5881. {
  5882. TSynchronizeMode Mode;
  5883. TSynchronizeChecklist * Checklist;
  5884. int Params;
  5885. TCopyParamType * CopyParam;
  5886. TDateTime CollectElapsed;
  5887. TDateTime * StartTime;
  5888. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5889. };
  5890. //---------------------------------------------------------------------------
  5891. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5892. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5893. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5894. {
  5895. DebugAssert(!FAutoOperation);
  5896. void * BatchStorage;
  5897. BatchStart(BatchStorage);
  5898. FAutoOperation = true;
  5899. TFileOperationStatistics Statistics;
  5900. TDateTime Start = Now();
  5901. try
  5902. {
  5903. Params.OnProcessedItem = OnProcessedItem;
  5904. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5905. CreateProgressForm(&SynchronizeProgress);
  5906. Terminal->SynchronizeApply(
  5907. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5908. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5909. &Statistics);
  5910. }
  5911. __finally
  5912. {
  5913. Params.OnProcessedItem = NULL;
  5914. FAutoOperation = false;
  5915. DestroyProgressForm();
  5916. BatchEnd(BatchStorage);
  5917. ReloadLocalDirectory();
  5918. }
  5919. if (WinConfiguration->SynchronizeSummary)
  5920. {
  5921. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5922. // The statistics should be 0 anyway in this case
  5923. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5924. {
  5925. Message += L"\n";
  5926. if (Statistics.FilesUploaded > 0)
  5927. {
  5928. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5929. }
  5930. if (Statistics.FilesDownloaded > 0)
  5931. {
  5932. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5933. }
  5934. if (Statistics.FilesDeletedLocal > 0)
  5935. {
  5936. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5937. }
  5938. if (Statistics.FilesDeletedRemote > 0)
  5939. {
  5940. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5941. }
  5942. }
  5943. TDateTime Elapsed = (Now() - Start);
  5944. Message +=
  5945. L"\n" +
  5946. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5947. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5948. TMessageParams Params(mpNeverAskAgainCheck);
  5949. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5950. if (Result == qaNeverAskAgain)
  5951. {
  5952. WinConfiguration->SynchronizeSummary = false;
  5953. }
  5954. }
  5955. }
  5956. //---------------------------------------------------------------------------
  5957. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5958. {
  5959. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5960. {
  5961. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5962. }
  5963. // Not set in keep-up-to-date mode - Synchronize() method
  5964. if (Token != NULL)
  5965. {
  5966. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5967. if (Params.OnProcessedItem != NULL)
  5968. {
  5969. Params.OnProcessedItem(NULL, ChecklistItem);
  5970. }
  5971. }
  5972. }
  5973. //---------------------------------------------------------------------------
  5974. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5975. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5976. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5977. {
  5978. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5979. *Params.StartTime = Now();
  5980. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5981. }
  5982. //---------------------------------------------------------------------------
  5983. void TCustomScpExplorerForm::DoQueueSynchronize(void * Token)
  5984. {
  5985. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5986. int CopyParams = TTerminal::GetSynchronizeCopyParams(Params.Params);
  5987. TCopyParamType SyncCopyParam = TTerminal::GetSynchronizeCopyParam(Params.CopyParam, Params.Params);
  5988. bool Parallel = GUIConfiguration->CurrentCopyParam.QueueParallel;
  5989. int Index = 0;
  5990. const TSynchronizeChecklist::TItem * ChecklistItem;
  5991. while (Params.Checklist->GetNextChecked(Index, ChecklistItem))
  5992. {
  5993. TQueueItem * QueueItem = Terminal->SynchronizeToQueue(ChecklistItem, &SyncCopyParam, CopyParams, Parallel);
  5994. AddQueueItem(Queue, QueueItem, Terminal);
  5995. }
  5996. }
  5997. //---------------------------------------------------------------------------
  5998. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5999. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  6000. {
  6001. // terminal can be already closed (e.g. dropped connection)
  6002. if (Terminal != NULL)
  6003. {
  6004. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6005. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  6006. }
  6007. }
  6008. //---------------------------------------------------------------------------
  6009. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  6010. TOperationSide Side, TStrings * FileList, const UnicodeString & NewFileName, bool TargetIsDirectory, void * Token)
  6011. {
  6012. DebugAssert(!IsLocalBrowserMode());
  6013. TAutoBatch AutoBatch(this);
  6014. TAutoFlag AutoOperationFlag(FAutoOperation);
  6015. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  6016. if (Side == osRemote)
  6017. {
  6018. UnicodeString Target;
  6019. UnicodeString FileMask;
  6020. if (TargetIsDirectory)
  6021. {
  6022. Target = NewFileName;
  6023. Terminal->CreateTargetDirectory(Target, faDirectory, Params.CopyParam);
  6024. }
  6025. else
  6026. {
  6027. Target = UnixExtractFileDir(NewFileName);
  6028. FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  6029. }
  6030. RemoteDirView->SaveSelection();
  6031. RemoteDirView->SaveSelectedNames();
  6032. try
  6033. {
  6034. Terminal->MoveFiles(FileList, Target, FileMask, false);
  6035. }
  6036. catch(...)
  6037. {
  6038. RemoteDirView->DiscardSavedSelection();
  6039. throw;
  6040. }
  6041. RemoteDirView->RestoreSelection();
  6042. }
  6043. else if (DebugAlwaysTrue(Side == osLocal))
  6044. {
  6045. std::unique_ptr<TStrings> Directories(CreateSortedStringList());
  6046. if (TargetIsDirectory)
  6047. {
  6048. if (!ForceDirectories(ApiPath(NewFileName)))
  6049. {
  6050. throw EOSExtException(FMTLOAD(CREATE_DIR_ERROR, (NewFileName)));
  6051. }
  6052. Directories->Add(NewFileName);
  6053. }
  6054. else
  6055. {
  6056. Directories->Add(ExtractFileDir(NewFileName));
  6057. }
  6058. for (int Index = 0; Index < FileList->Count; Index++)
  6059. {
  6060. UnicodeString FileName = FileList->Strings[Index];
  6061. UnicodeString Directory = ExtractFileDir(FileName);
  6062. Directories->Add(Directory);
  6063. UnicodeString NewFilePath = NewFileName;
  6064. if (TargetIsDirectory)
  6065. {
  6066. NewFilePath = TPath::Combine(NewFilePath, ExtractFileName(FileName));
  6067. }
  6068. if (!MoveFile(ApiPath(FileName).c_str(), ApiPath(NewFilePath).c_str()))
  6069. {
  6070. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFilePath)));
  6071. }
  6072. }
  6073. for (int Index = 0; Index < Directories->Count; Index++)
  6074. {
  6075. ReloadLocalDirectory(Directories->Strings[Index]);
  6076. }
  6077. }
  6078. }
  6079. //---------------------------------------------------------------------------
  6080. void __fastcall TCustomScpExplorerForm::DoSynchronizeExplore(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  6081. {
  6082. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  6083. if (Side == osLocal)
  6084. {
  6085. if (Action == TSynchronizeChecklist::saDownloadNew)
  6086. {
  6087. OpenFolderInExplorer(LocalPath);
  6088. }
  6089. else
  6090. {
  6091. OpenFileInExplorer(Item->ForceGetLocalPath());
  6092. }
  6093. }
  6094. else if (DebugAlwaysTrue(Side == osRemote))
  6095. {
  6096. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6097. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6098. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6099. if (!LocalPath.IsEmpty())
  6100. {
  6101. SessionData->LocalDirectory = LocalPath;
  6102. }
  6103. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6104. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(EXPLORE_SWITCH), Item->GetFileName())));
  6105. }
  6106. }
  6107. //---------------------------------------------------------------------------
  6108. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6109. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6110. const TCopyParamType * CopyParams)
  6111. {
  6112. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6113. UnicodeString AdditionalParams =
  6114. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6115. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6116. SerializeCopyParamForCommandLine(CopyParams),
  6117. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6118. LocalDirectory, RemoteDirectory, Mode, Params));
  6119. ExecuteNewInstance(SessionName, AdditionalParams);
  6120. }
  6121. //---------------------------------------------------------------------------
  6122. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6123. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6124. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6125. {
  6126. int Result;
  6127. bool SaveSettings = false;
  6128. int Options =
  6129. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6130. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6131. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6132. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6133. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6134. bool Continue =
  6135. ((UseDefaults == 0) ||
  6136. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6137. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6138. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6139. if (Continue)
  6140. {
  6141. Configuration->Usage->Inc(L"Synchronizations");
  6142. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6143. UpdateCopyParamCounters(CopyParam);
  6144. TSynchronizeOptions SynchronizeOptions;
  6145. GetSynchronizeOptions(Params, SynchronizeOptions);
  6146. if (SaveSettings)
  6147. {
  6148. GUIConfiguration->SynchronizeParams = Params;
  6149. }
  6150. else
  6151. {
  6152. SaveMode = false;
  6153. }
  6154. TDateTime StartTime = Now();
  6155. TSynchronizeChecklist * Checklist = NULL;
  6156. try
  6157. {
  6158. DebugAssert(!FAutoOperation);
  6159. FAutoOperation = true;
  6160. try
  6161. {
  6162. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6163. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6164. int Files = -1;
  6165. if (DataList->Count >= 1)
  6166. {
  6167. Files = StrToIntDef(DataList->Strings[0], Files);
  6168. }
  6169. else
  6170. {
  6171. DataList->Add(UnicodeString());
  6172. }
  6173. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6174. FSynchronizeProgressForm->Start();
  6175. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6176. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6177. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6178. &SynchronizeOptions);
  6179. if (Terminal->SessionData->CacheDirectories)
  6180. {
  6181. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6182. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6183. }
  6184. }
  6185. __finally
  6186. {
  6187. FAutoOperation = false;
  6188. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6189. SAFE_DESTROY(FSynchronizeProgressForm);
  6190. }
  6191. TSynchronizeParams SynchronizeParams;
  6192. SynchronizeParams.Mode = Mode;
  6193. SynchronizeParams.CopyParam = &CopyParam;
  6194. SynchronizeParams.Params = Params;
  6195. SynchronizeParams.Checklist = Checklist;
  6196. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6197. SynchronizeParams.StartTime = &StartTime;
  6198. SynchronizeParams.OnProcessedItem = NULL;
  6199. Result = Checklist->Count;
  6200. if (Checklist->Count > 0)
  6201. {
  6202. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6203. {
  6204. TQueueSynchronizeEvent OnQueueSynchronize = NULL;
  6205. if (Visible && FLAGCLEAR(Params, TTerminal::spTimestamp))
  6206. {
  6207. OnQueueSynchronize = DoQueueSynchronize;
  6208. }
  6209. if (!DoSynchronizeChecklistDialog(
  6210. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6211. OnQueueSynchronize, DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeExplore,
  6212. &SynchronizeParams))
  6213. {
  6214. Result = -1;
  6215. }
  6216. }
  6217. else
  6218. {
  6219. FullSynchronize(SynchronizeParams, NULL, NULL);
  6220. }
  6221. }
  6222. else
  6223. {
  6224. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6225. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6226. }
  6227. }
  6228. __finally
  6229. {
  6230. delete Checklist;
  6231. }
  6232. OperationComplete(StartTime);
  6233. }
  6234. else
  6235. {
  6236. Result = -1;
  6237. }
  6238. return Result;
  6239. }
  6240. //---------------------------------------------------------------------------
  6241. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6242. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6243. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6244. {
  6245. if (Collect)
  6246. {
  6247. DebugAssert(FSynchronizeProgressForm != NULL);
  6248. if (!FSynchronizeProgressForm->Started)
  6249. {
  6250. FSynchronizeProgressForm->Start();
  6251. }
  6252. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6253. SetTaskbarListProgressValue(CompareProgress);
  6254. }
  6255. else
  6256. {
  6257. DebugAssert(FSynchronizeProgressForm == NULL);
  6258. DebugAssert(FProgressForm != NULL);
  6259. }
  6260. }
  6261. //---------------------------------------------------------------------------
  6262. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6263. {
  6264. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6265. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6266. if (File.get() != NULL)
  6267. {
  6268. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6269. Application->ShowMainForm = false;
  6270. Application->Run();
  6271. }
  6272. }
  6273. //---------------------------------------------------------------------------
  6274. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6275. {
  6276. DebugFail();
  6277. }
  6278. //---------------------------------------------------------------------------
  6279. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6280. {
  6281. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6282. SessionData->Assign(ManagedSession->SessionData);
  6283. UpdateSessionData(SessionData.get());
  6284. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6285. if (IsAvailableTerminal(ManagedSession))
  6286. {
  6287. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6288. }
  6289. if (!ManagedSession->SessionData->HasSessionName())
  6290. {
  6291. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6292. // once IsWorkspace is cleared
  6293. SessionData->Name = UnicodeString();
  6294. }
  6295. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6296. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6297. SessionData->IsWorkspace = false;
  6298. return SessionData.release();
  6299. }
  6300. //---------------------------------------------------------------------------
  6301. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6302. {
  6303. TSessionData * SessionData = CloneCurrentSessionData();
  6304. try
  6305. {
  6306. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6307. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6308. }
  6309. __finally
  6310. {
  6311. delete SessionData;
  6312. }
  6313. }
  6314. //---------------------------------------------------------------------------
  6315. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6316. {
  6317. TTerminalManager * Manager = TTerminalManager::Instance();
  6318. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6319. if (DebugAlwaysTrue(ManagedSession != NULL))
  6320. {
  6321. // Update ManagedSession->StateData
  6322. UpdateSession(ManagedSession);
  6323. }
  6324. Manager->SaveWorkspace(DataList.get());
  6325. return DataList.release();
  6326. }
  6327. //---------------------------------------------------------------------------
  6328. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6329. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6330. {
  6331. WinConfiguration->LastWorkspace = Name;
  6332. if (!SavePasswords)
  6333. {
  6334. for (int Index = 0; Index < DataList->Count; Index++)
  6335. {
  6336. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6337. if (SessionData->Link.IsEmpty())
  6338. {
  6339. SessionData->ClearSessionPasswords();
  6340. }
  6341. }
  6342. }
  6343. StoredSessions->NewWorkspace(Name, DataList);
  6344. // modified only
  6345. StoredSessions->Save(false, Explicit);
  6346. }
  6347. //---------------------------------------------------------------------------
  6348. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6349. {
  6350. return
  6351. DefaultStr(WinConfiguration->LastWorkspace,
  6352. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6353. }
  6354. //---------------------------------------------------------------------------
  6355. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6356. {
  6357. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6358. bool AnyNonStoredSessionWithPassword = false;
  6359. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6360. bool AllNonStoredSessionsAnonymous = true;
  6361. TTerminalManager * Manager = TTerminalManager::Instance();
  6362. for (int Index = 0; Index < DataList->Count; Index++)
  6363. {
  6364. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6365. if (SessionData->Link.IsEmpty())
  6366. {
  6367. if (SessionData->HasAnySessionPassword())
  6368. {
  6369. AnyNonStoredSessionWithPassword = true;
  6370. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6371. {
  6372. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6373. }
  6374. }
  6375. if (!SameText(SessionData->UserName, AnonymousUserName))
  6376. {
  6377. AllNonStoredSessionsAnonymous = false;
  6378. }
  6379. }
  6380. }
  6381. bool SavePasswords;
  6382. bool * PSavePasswords;
  6383. bool NotRecommendedSavingPasswords =
  6384. !CustomWinConfiguration->UseMasterPassword &&
  6385. !AllNonStoredSessionsAnonymous;
  6386. if (Configuration->DisablePasswordStoring ||
  6387. !AnyNonStoredSessionWithPassword)
  6388. {
  6389. PSavePasswords = NULL;
  6390. SavePasswords = false;
  6391. }
  6392. else
  6393. {
  6394. PSavePasswords = &SavePasswords;
  6395. SavePasswords =
  6396. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6397. !NotRecommendedSavingPasswords;
  6398. }
  6399. UnicodeString Name = WorkspaceName();
  6400. bool CreateShortcut = false;
  6401. bool Result =
  6402. DoSaveWorkspaceDialog(
  6403. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6404. EnableAutoSave);
  6405. if (Result)
  6406. {
  6407. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6408. if (CreateShortcut)
  6409. {
  6410. TOperationVisualizer Visualizer;
  6411. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6412. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6413. }
  6414. if (EnableAutoSave)
  6415. {
  6416. WinConfiguration->AutoSaveWorkspace = true;
  6417. WinConfiguration->AutoWorkspace = Name;
  6418. if (PSavePasswords != NULL)
  6419. {
  6420. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6421. }
  6422. }
  6423. }
  6424. return Result;
  6425. }
  6426. //---------------------------------------------------------------------------
  6427. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6428. {
  6429. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6430. DebugAssert(Session == ManagedSession);
  6431. if (!IsLocalBrowserMode())
  6432. {
  6433. SAFE_DESTROY(Session->RemoteExplorerState);
  6434. if (WinConfiguration->PreservePanelState)
  6435. {
  6436. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6437. }
  6438. }
  6439. UpdateSessionData(Session->StateData);
  6440. }
  6441. //---------------------------------------------------------------------------
  6442. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6443. {
  6444. // Keep in sync with TSessionData::CopyStateData
  6445. DebugAssert(Data != NULL);
  6446. // This is inconsistent with how color (for example) is handled.
  6447. Data->Name = ManagedSession->SessionData->Name;
  6448. if (!IsLocalBrowserMode())
  6449. {
  6450. // cannot use RemoteDirView->Path, because it is empty if connection
  6451. // was already closed
  6452. // also only peek, we may not be connected at all atm
  6453. // so make sure we do not try retrieving current directory from the server
  6454. // (particularly with FTP)
  6455. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6456. if (!ACurrentDirectory.IsEmpty())
  6457. {
  6458. Data->RemoteDirectory = ACurrentDirectory;
  6459. }
  6460. }
  6461. Data->Color = SessionColor;
  6462. }
  6463. //---------------------------------------------------------------------------
  6464. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6465. {
  6466. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6467. DebugAssert(Toolbar != NULL);
  6468. for (int i = 0; i < Toolbar->Items->Count; i++)
  6469. {
  6470. TTBXCustomDropDownItem * DropDownItem;
  6471. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6472. if (DropDownItem != NULL)
  6473. {
  6474. ToolbarItemResize(DropDownItem,
  6475. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6476. Toolbar->NonClientWidth);
  6477. break;
  6478. }
  6479. }
  6480. }
  6481. //---------------------------------------------------------------------------
  6482. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6483. {
  6484. Item->EditWidth = Width;
  6485. }
  6486. //---------------------------------------------------------------------------
  6487. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6488. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6489. {
  6490. for (int i = 0; i < Toolbar->Items->Count; i++)
  6491. {
  6492. TTBXCustomDropDownItem * DropDownItem;
  6493. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6494. if (DropDownItem != NULL)
  6495. {
  6496. ASize.x -= DropDownItem->EditWidth;
  6497. TControl * Control = this;
  6498. ASize.x += ScaleByTextHeight(Control, 50) /* minimal combo width */;
  6499. }
  6500. }
  6501. }
  6502. //---------------------------------------------------------------------------
  6503. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6504. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6505. {
  6506. if (WinConfiguration->DDWarnLackOfTempSpace)
  6507. {
  6508. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6509. if (!ADrive.IsEmpty())
  6510. {
  6511. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6512. DebugAssert(RequiredSpace >= 0);
  6513. __int64 RequiredWithReserve;
  6514. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6515. if (FreeSpace < RequiredWithReserve)
  6516. {
  6517. unsigned int Result;
  6518. TMessageParams Params(mpNeverAskAgainCheck);
  6519. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6520. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6521. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6522. if (Result == qaNeverAskAgain)
  6523. {
  6524. WinConfiguration->DDWarnLackOfTempSpace = false;
  6525. }
  6526. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6527. }
  6528. }
  6529. }
  6530. }
  6531. //---------------------------------------------------------------------------
  6532. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6533. {
  6534. DoOpenDirectoryDialog(odAddBookmark, Side);
  6535. }
  6536. //---------------------------------------------------------------------------
  6537. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6538. {
  6539. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6540. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6541. try
  6542. {
  6543. TCustomDirView * DView = DirView(Side);
  6544. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6545. {
  6546. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6547. }
  6548. }
  6549. catch (...)
  6550. {
  6551. delete VisitedDirectories;
  6552. throw;
  6553. }
  6554. return VisitedDirectories;
  6555. }
  6556. //---------------------------------------------------------------------------
  6557. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6558. TOpenDirectoryMode Mode, TOperationSide Side)
  6559. {
  6560. bool Continue = true;
  6561. if (Mode == odAddBookmark)
  6562. {
  6563. TMessageParams Params(mpNeverAskAgainCheck);
  6564. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6565. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6566. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6567. unsigned int Answer =
  6568. MessageDialog(Message,
  6569. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6570. if (Answer == qaNeverAskAgain)
  6571. {
  6572. Continue = true;
  6573. WinConfiguration->UseSharedBookmarks = true;
  6574. }
  6575. else if (Answer == qaOK)
  6576. {
  6577. Continue = true;
  6578. WinConfiguration->UseSharedBookmarks = false;
  6579. }
  6580. else
  6581. {
  6582. Continue = false;
  6583. }
  6584. }
  6585. if (Continue)
  6586. {
  6587. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6588. try
  6589. {
  6590. UnicodeString Name = DirView(Side)->PathName;
  6591. bool Repeat;
  6592. do
  6593. {
  6594. Repeat = false;
  6595. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6596. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6597. // do not allow switching to location profiles,
  6598. // if we are not connected
  6599. HasDirView[osLocal] && IsAvailableTerminal(Terminal)))
  6600. {
  6601. TWindowLock Lock(this);
  6602. if (!TryOpenDirectory(Side, Name))
  6603. {
  6604. Repeat = true;
  6605. Mode = odBrowse;
  6606. }
  6607. }
  6608. }
  6609. while (Repeat);
  6610. }
  6611. __finally
  6612. {
  6613. delete VisitedDirectories;
  6614. }
  6615. }
  6616. }
  6617. //---------------------------------------------------------------------------
  6618. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6619. {
  6620. DebugAssert(!Terminal->CommandSessionOpened);
  6621. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6622. }
  6623. //---------------------------------------------------------------------------
  6624. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6625. {
  6626. bool Result = Terminal->IsCapable[Capability] ||
  6627. Terminal->CommandSessionOpened;
  6628. if (!Result)
  6629. {
  6630. // We might get here for example when "checksum" synchronization is requested from command-line
  6631. // on server that supports neither checksum nor shell
  6632. if (!Terminal->IsCapable[fcSecondaryShell])
  6633. {
  6634. NotSupported();
  6635. }
  6636. else if (!GUIConfiguration->ConfirmCommandSession)
  6637. {
  6638. Result = true;
  6639. }
  6640. else
  6641. {
  6642. TMessageParams Params(mpNeverAskAgainCheck);
  6643. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6644. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6645. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6646. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6647. if (Answer == qaNeverAskAgain)
  6648. {
  6649. GUIConfiguration->ConfirmCommandSession = false;
  6650. Result = true;
  6651. }
  6652. else if (Answer == qaOK)
  6653. {
  6654. Result = true;
  6655. }
  6656. }
  6657. if (Result)
  6658. {
  6659. Result = CommandSessionFallback();
  6660. }
  6661. }
  6662. return Result;
  6663. }
  6664. //---------------------------------------------------------------------------
  6665. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6666. {
  6667. if (EnsureCommandSessionFallback(fcAnyCommand))
  6668. {
  6669. DoConsoleDialog(Terminal, Command);
  6670. }
  6671. }
  6672. //---------------------------------------------------------------------------
  6673. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6674. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6675. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6676. {
  6677. if (!IsSideLocalBrowser(osRemote) &&
  6678. IsFileControl(DropSourceControl, osRemote) &&
  6679. (FDDExtMapFile != NULL))
  6680. {
  6681. Accept = true;
  6682. }
  6683. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6684. DebugAssert(FDDTargetControl != NULL);
  6685. }
  6686. //---------------------------------------------------------------------------
  6687. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6688. _di_IDataObject DataObj, int KeyState,
  6689. const TPoint & Point, int & Effect, bool & Accept)
  6690. {
  6691. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6692. }
  6693. //---------------------------------------------------------------------------
  6694. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6695. _di_IDataObject DataObj, int KeyState,
  6696. const TPoint & Point, int & Effect, bool & Accept)
  6697. {
  6698. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6699. }
  6700. //---------------------------------------------------------------------------
  6701. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6702. TObject * Sender)
  6703. {
  6704. DebugUsedParam(Sender);
  6705. DebugAssert(FDDTargetControl == Sender);
  6706. FDDTargetControl = NULL;
  6707. }
  6708. //---------------------------------------------------------------------------
  6709. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave(int)
  6710. {
  6711. FileControlDDDragLeave(SessionsPageControl);
  6712. }
  6713. //---------------------------------------------------------------------------
  6714. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave(int)
  6715. {
  6716. FileControlDDDragLeave(QueueView3);
  6717. }
  6718. //---------------------------------------------------------------------------
  6719. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6720. {
  6721. DebugAssert(!IsSideLocalBrowser(Side));
  6722. DebugUsedParam(Side);
  6723. bool Edit = false;
  6724. TRemoteFile * File = NULL;
  6725. UnicodeString FileName;
  6726. UnicodeString PointTo;
  6727. bool SymbolicLink = true;
  6728. if (RemoteDirView->ItemFocused)
  6729. {
  6730. DebugAssert(RemoteDirView->ItemFocused->Data);
  6731. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6732. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6733. if (Edit)
  6734. {
  6735. FileName = File->FileName;
  6736. PointTo = File->LinkTo;
  6737. }
  6738. else if (!File->IsParentDirectory)
  6739. {
  6740. PointTo = File->FileName;
  6741. }
  6742. }
  6743. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6744. Terminal->IsCapable[fcHardLink]))
  6745. {
  6746. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6747. if (Edit)
  6748. {
  6749. DebugAssert(File->FileName == FileName);
  6750. int Params = dfNoRecursive;
  6751. Terminal->ExceptionOnFail = true;
  6752. try
  6753. {
  6754. Terminal->DeleteFile(L"", File, &Params);
  6755. }
  6756. __finally
  6757. {
  6758. Terminal->ExceptionOnFail = false;
  6759. }
  6760. }
  6761. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6762. }
  6763. }
  6764. //---------------------------------------------------------------------------
  6765. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6766. {
  6767. return
  6768. (IsSideLocalBrowser(Side) ||
  6769. (HasAvailableTerminal() &&
  6770. Terminal->ResolvingSymlinks &&
  6771. Terminal->IsCapable[fcSymbolicLink]));
  6772. }
  6773. //---------------------------------------------------------------------------
  6774. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6775. {
  6776. return
  6777. !IsSideLocalBrowser(FCurrentSide) &&
  6778. (RemoteDirView->ItemFocused != NULL) &&
  6779. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6780. Terminal->SessionData->ResolveSymlinks;
  6781. }
  6782. //---------------------------------------------------------------------------
  6783. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6784. {
  6785. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6786. FForceExecution = true;
  6787. try
  6788. {
  6789. DirView(osCurrent)->ExecuteCurrentFile();
  6790. }
  6791. __finally
  6792. {
  6793. FForceExecution = false;
  6794. }
  6795. }
  6796. //---------------------------------------------------------------------------
  6797. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6798. {
  6799. TEditorData ExternalEditor;
  6800. ExternalEditor.Editor = edExternal;
  6801. bool Remember = false;
  6802. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6803. {
  6804. if (Remember)
  6805. {
  6806. TEditorList * EditorList = new TEditorList;
  6807. try
  6808. {
  6809. *EditorList = *WinConfiguration->EditorList;
  6810. bool Found = false;
  6811. int i = 0;
  6812. while (!Found && (i < EditorList->Count))
  6813. {
  6814. const TEditorPreferences * Editor = EditorList->Editors[i];
  6815. if ((Editor->Data->Editor == edExternal) &&
  6816. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6817. {
  6818. Found = true;
  6819. }
  6820. i++;
  6821. }
  6822. if (!Found)
  6823. {
  6824. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6825. WinConfiguration->EditorList = EditorList;
  6826. }
  6827. }
  6828. __finally
  6829. {
  6830. delete EditorList;
  6831. }
  6832. }
  6833. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6834. }
  6835. }
  6836. //---------------------------------------------------------------------------
  6837. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6838. {
  6839. if (FFileFindTerminal == ATerminal)
  6840. {
  6841. FFileFindTerminal = NULL;
  6842. HideFileFindDialog();
  6843. }
  6844. if (FClipboardTerminal == ATerminal)
  6845. {
  6846. ClipboardClear(); // implies ClipboardStop
  6847. }
  6848. if ((FOnSynchronizeAbort != NULL) &&
  6849. (ATerminal == FManagedSession))
  6850. {
  6851. FOnSynchronizeAbort(NULL);
  6852. }
  6853. }
  6854. //---------------------------------------------------------------------------
  6855. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6856. {
  6857. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6858. DetachTerminal(Sender);
  6859. }
  6860. //---------------------------------------------------------------------------
  6861. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6862. const UnicodeString DebugUsedArg(FileName), TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6863. {
  6864. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6865. if (Data->Terminal == Terminal)
  6866. {
  6867. Data->Terminal = ATerminal;
  6868. }
  6869. }
  6870. //---------------------------------------------------------------------------
  6871. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6872. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6873. {
  6874. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6875. DebugUsedParam(FileName);
  6876. DebugAssert(Terminal != NULL);
  6877. if (Data->Terminal == Terminal)
  6878. {
  6879. Data->Terminal = NULL;
  6880. }
  6881. }
  6882. //---------------------------------------------------------------------------
  6883. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6884. {
  6885. return NULL;
  6886. }
  6887. //---------------------------------------------------------------------------
  6888. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6889. {
  6890. UpdateControls();
  6891. SessionColor = TColor(0);
  6892. UpdateRemotePathComboBox(false);
  6893. NeedSession(false);
  6894. }
  6895. //---------------------------------------------------------------------------
  6896. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6897. {
  6898. try
  6899. {
  6900. // Cache, as the login dialog can change its value.
  6901. // See also DoShow. Also see TTerminalManager::NewSession.
  6902. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6903. try
  6904. {
  6905. if (ShowLogin)
  6906. {
  6907. bool ReloadSessions = !Startup;
  6908. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6909. }
  6910. }
  6911. __finally
  6912. {
  6913. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6914. // (so there was no chance for the user to open any session yet)
  6915. if ((ShowLogin || !Startup) &&
  6916. !WinConfiguration->KeepOpenWhenNoSession &&
  6917. // this rules out the implicit Commander's local-local browser
  6918. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6919. {
  6920. TerminateApplication();
  6921. }
  6922. }
  6923. }
  6924. catch (EAbort &)
  6925. {
  6926. // swallow
  6927. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6928. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6929. }
  6930. }
  6931. //---------------------------------------------------------------------------
  6932. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6933. {
  6934. TTerminalManager * Manager = TTerminalManager::Instance();
  6935. DebugAssert(!Manager->Updating);
  6936. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6937. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6938. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6939. SessionsPageControl->LockDrawing();
  6940. try
  6941. {
  6942. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6943. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6944. {
  6945. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6946. }
  6947. for (int Index = 0; Index <= Manager->Count; Index++)
  6948. {
  6949. TThemeTabSheet * TabSheet;
  6950. if (Index >= SessionsPageControl->PageCount)
  6951. {
  6952. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6953. TabSheet->PageControl = SessionsPageControl;
  6954. }
  6955. else
  6956. {
  6957. TabSheet = SessionsPageControl->Pages[Index];
  6958. }
  6959. bool IsSessionTab = (Index < Manager->Count);
  6960. if (IsSessionTab)
  6961. {
  6962. TTerminal * Terminal = Manager->Sessions[Index];
  6963. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6964. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  6965. UpdateSessionTab(TabSheet);
  6966. }
  6967. else
  6968. {
  6969. TabSheet->Tag = 0; // not really needed
  6970. TabSheet->Shadowed = false;
  6971. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6972. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  6973. // We know that we are at the last page, otherwise we could not call this (it assumes that new session tab is the last one)
  6974. UpdateNewTabTab();
  6975. }
  6976. }
  6977. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6978. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6979. {
  6980. SessionsPageControl->UpdateTabsCaptionTruncation();
  6981. }
  6982. }
  6983. __finally
  6984. {
  6985. SessionsPageControl->UnlockDrawing();
  6986. }
  6987. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6988. }
  6989. //---------------------------------------------------------------------------
  6990. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  6991. {
  6992. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  6993. }
  6994. //---------------------------------------------------------------------------
  6995. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6996. {
  6997. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6998. }
  6999. //---------------------------------------------------------------------------
  7000. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  7001. {
  7002. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  7003. }
  7004. //---------------------------------------------------------------------------
  7005. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  7006. {
  7007. TThemeTabSheet * TabSheet = GetNewTabTab();
  7008. UnicodeString TabCaption;
  7009. if (WinConfiguration->SelectiveToolbarText)
  7010. {
  7011. TabCaption = GetNewTabTabCaption();
  7012. }
  7013. TabSheet->BaseCaption = TabCaption;
  7014. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  7015. }
  7016. //---------------------------------------------------------------------------
  7017. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  7018. {
  7019. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  7020. }
  7021. //---------------------------------------------------------------------------
  7022. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  7023. {
  7024. DebugFail();
  7025. return UnicodeString();
  7026. }
  7027. //---------------------------------------------------------------------------
  7028. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  7029. {
  7030. if (DebugAlwaysTrue(TabSheet != NULL))
  7031. {
  7032. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  7033. if (DebugAlwaysTrue(ASession != NULL))
  7034. {
  7035. TColor Color = (ASession == Terminal) ? FSessionColor : static_cast<TColor>(ASession->StateData->Color);
  7036. if (ASession->LocalBrowser)
  7037. {
  7038. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  7039. }
  7040. else
  7041. {
  7042. TabSheet->ImageIndex = AddSessionColor(Color);
  7043. }
  7044. TTerminalManager * Manager = TTerminalManager::Instance();
  7045. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  7046. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  7047. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  7048. }
  7049. }
  7050. }
  7051. //---------------------------------------------------------------------------
  7052. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  7053. {
  7054. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  7055. }
  7056. //---------------------------------------------------------------------------
  7057. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  7058. {
  7059. DebugAssert(SessionsPageControl->ActivePage != NULL);
  7060. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  7061. bool Result = (Session != NULL);
  7062. if (Result)
  7063. {
  7064. TTerminalManager::Instance()->ActiveSession = Session;
  7065. }
  7066. else
  7067. {
  7068. try
  7069. {
  7070. NewTab();
  7071. }
  7072. __finally
  7073. {
  7074. SessionListChanged();
  7075. }
  7076. FSessionsPageControlNewTabTime = Now();
  7077. }
  7078. return Result;
  7079. }
  7080. //---------------------------------------------------------------------------
  7081. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  7082. {
  7083. TWindowLock Lock(this);
  7084. SessionTabSwitched();
  7085. }
  7086. //---------------------------------------------------------------------------
  7087. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  7088. {
  7089. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  7090. DebugAssert(TransferList != NULL);
  7091. UnicodeString Name;
  7092. if (TransferList->ItemIndex <= 0)
  7093. {
  7094. Name = L"";
  7095. }
  7096. else
  7097. {
  7098. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7099. }
  7100. if (FCopyParamAutoSelected.IsEmpty())
  7101. {
  7102. // if previous preset was not autoselected, make new preset the "default"
  7103. FCopyParamDefault = Name;
  7104. }
  7105. GUIConfiguration->CopyParamCurrent = Name;
  7106. }
  7107. //---------------------------------------------------------------------------
  7108. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7109. {
  7110. // sanity check
  7111. bool ExistingPreset =
  7112. (FTransferListHoverIndex >= 0) &&
  7113. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7114. DebugAssert(ExistingPreset);
  7115. if (ExistingPreset)
  7116. {
  7117. HDC DC = GetDC(0);
  7118. TCanvas * Canvas = new TCanvas();
  7119. try
  7120. {
  7121. Canvas->Handle = DC;
  7122. Canvas->Font = GetToolbarFont(this);
  7123. UnicodeString Name;
  7124. if (FTransferListHoverIndex == 0)
  7125. {
  7126. Name = L"";
  7127. }
  7128. else
  7129. {
  7130. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7131. }
  7132. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7133. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7134. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7135. static_cast<TObject*>(GetComponent(fcTransferList)));
  7136. UnicodeString InfoStr =
  7137. GUIConfiguration->CopyParamPreset[Name].
  7138. GetInfoStr(L"; ",
  7139. FLAGMASK(HasAvailableTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7140. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7141. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7142. {
  7143. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7144. {
  7145. InfoStr.SetLength(InfoStr.Length() - 1);
  7146. }
  7147. InfoStr += Ellipsis;
  7148. }
  7149. // UpdateCaption does not cause invalidation of whole submenu, while
  7150. // setting Caption property does.
  7151. // also it probably does not resize the label, even if necessary
  7152. // (we do not want that anyway)
  7153. TransferLabel->UpdateCaption(InfoStr);
  7154. }
  7155. __finally
  7156. {
  7157. Canvas->Handle = NULL;
  7158. ReleaseDC(0, DC);
  7159. delete Canvas;
  7160. }
  7161. }
  7162. }
  7163. //---------------------------------------------------------------------------
  7164. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7165. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7166. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7167. {
  7168. if (FTransferListHoverIndex != AHoverIndex)
  7169. {
  7170. FTransferListHoverIndex = AHoverIndex;
  7171. UpdateTransferLabel();
  7172. }
  7173. }
  7174. //---------------------------------------------------------------------------
  7175. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7176. {
  7177. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7178. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7179. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7180. {
  7181. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7182. {
  7183. if (!NonVisualDataModule->Busy)
  7184. {
  7185. OpenDirectory(GetSide(osCurrent));
  7186. }
  7187. Message.Result = 1;
  7188. }
  7189. else
  7190. {
  7191. TForm::Dispatch(&Message);
  7192. }
  7193. }
  7194. else
  7195. {
  7196. TForm::Dispatch(&Message);
  7197. }
  7198. }
  7199. //---------------------------------------------------------------------------
  7200. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7201. {
  7202. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7203. if ((FIgnoreNextDialogChar != 0) &&
  7204. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7205. {
  7206. Message.Result = 1;
  7207. }
  7208. else
  7209. {
  7210. TForm::Dispatch(&Message);
  7211. }
  7212. FIgnoreNextDialogChar = 0;
  7213. }
  7214. //---------------------------------------------------------------------------
  7215. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7216. {
  7217. // The four low-order bits are used internally by Windows
  7218. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7219. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7220. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7221. // 61730 - restore thru double click - undocumented
  7222. // 61490 - maximize thru double click - undocumented
  7223. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7224. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7225. {
  7226. SysResizing(Cmd);
  7227. }
  7228. TForm::Dispatch(&Message);
  7229. }
  7230. //---------------------------------------------------------------------------
  7231. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7232. {
  7233. AppLog(L"Windows session end query");
  7234. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7235. // Also there no point returning TRUE as we are not able to
  7236. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7237. // Hence the process termination might be safer :)
  7238. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7239. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7240. {
  7241. Message.Result = FALSE;
  7242. }
  7243. else
  7244. {
  7245. Message.Result = TRUE;
  7246. }
  7247. // Do not call default handling as that triggers OnCloseQuery,
  7248. // where our implementation will popup confirmation dialogs, what we do not want,
  7249. // as per Vista guidelines:
  7250. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7251. }
  7252. //---------------------------------------------------------------------------
  7253. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7254. {
  7255. AppLog(L"Windows session end");
  7256. if (Message.EndSession && IsApplicationMinimized())
  7257. {
  7258. // WORKAROUND
  7259. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7260. // when it receives WM_ENDSESSION,
  7261. // but that sometimes (particularly when application is minimized) cause crashes.
  7262. // Crash popups message that blocks log off.
  7263. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7264. // so we call ExitProcess() immediately, not even trying to cleanup.
  7265. // It still causes beep, so there's likely some popup, but it does not block
  7266. // log off.
  7267. ExitProcess(0);
  7268. }
  7269. TForm::Dispatch(&Message);
  7270. }
  7271. //---------------------------------------------------------------------------
  7272. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7273. {
  7274. }
  7275. //---------------------------------------------------------------------------
  7276. void __fastcall TCustomScpExplorerForm::DoShow()
  7277. {
  7278. // Called from TCustomScpExplorerForm::CMShowingChanged
  7279. // only now are the controls resized finally, so the size constraints
  7280. // will not conflict with possibly very small window size
  7281. RestoreFormParams();
  7282. // This indicates that the form was rescaled after parameters were loaded and
  7283. // as most probably the parameters were actually saved with the current form scaling
  7284. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7285. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7286. // and no rounding problems will occur.
  7287. // See also RestoreForm.
  7288. // (we should be safe to call RestoreParams unconditionally)
  7289. if (PixelsPerInch != Screen->PixelsPerInch)
  7290. {
  7291. RestoreParams();
  7292. }
  7293. FixControlsPlacement();
  7294. if (Position == poDefaultPosOnly)
  7295. {
  7296. CutFormToDesktop(this);
  7297. }
  7298. TForm::DoShow();
  7299. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7300. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7301. // This was previously in NeedSession, where other related code is.
  7302. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7303. // unpleasantly shows briefly.
  7304. if ((ManagedSession == NULL) &&
  7305. !WinConfiguration->ShowLoginWhenNoSession &&
  7306. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7307. // This detects if workspace was saved the last time the main widow was closed
  7308. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7309. {
  7310. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7311. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7312. }
  7313. // Before main window displays
  7314. if (ManagedSession == NULL)
  7315. {
  7316. StartingWithoutSession();
  7317. }
  7318. UpdatePixelsPerInchMainWindowCounter();
  7319. FShowing = true;
  7320. }
  7321. //---------------------------------------------------------------------------
  7322. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7323. {
  7324. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7325. }
  7326. //---------------------------------------------------------------------------
  7327. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7328. {
  7329. SessionListChanged();
  7330. InitStatusBar();
  7331. UpdateControls();
  7332. }
  7333. //---------------------------------------------------------------------------
  7334. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7335. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7336. TNotifyEvent OnBalloonClick, TObject * UserData)
  7337. {
  7338. bool Do;
  7339. UnicodeString Message;
  7340. if (E == NULL)
  7341. {
  7342. Message = Str;
  7343. Do = true;
  7344. }
  7345. else
  7346. {
  7347. Do = ExceptionMessage(E, Message);
  7348. }
  7349. if (Do && WinConfiguration->BalloonNotifications)
  7350. {
  7351. UnicodeString Title;
  7352. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7353. {
  7354. Message = TrimLeft(Message);
  7355. }
  7356. else
  7357. {
  7358. Message = UnformatMessage(Message);
  7359. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7360. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7361. Title = LoadResourceString(Captions[Type]);
  7362. if (Terminal != NULL)
  7363. {
  7364. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7365. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7366. }
  7367. }
  7368. if (Seconds == 0)
  7369. {
  7370. Seconds = WinConfiguration->NotificationsTimeout;
  7371. }
  7372. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7373. }
  7374. }
  7375. //---------------------------------------------------------------------------
  7376. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7377. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7378. UnicodeString HelpKeyword, const TMessageParams * Params,
  7379. TTerminal * Terminal)
  7380. {
  7381. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7382. (FOnFeedSynchronizeError != NULL)) &&
  7383. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7384. {
  7385. if (FOnFeedSynchronizeError != NULL)
  7386. {
  7387. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7388. }
  7389. else
  7390. {
  7391. DebugAssert(FErrorList != NULL);
  7392. TStringList * MoreMessagesCopy = NULL;
  7393. if (MoreMessages)
  7394. {
  7395. MoreMessagesCopy = new TStringList();
  7396. MoreMessagesCopy->Assign(MoreMessages);
  7397. }
  7398. FErrorList->AddObject(Message, MoreMessagesCopy);
  7399. }
  7400. PopupTrayBalloon(Terminal, Message, Type);
  7401. return ContinueAnswer(Answers);
  7402. }
  7403. else
  7404. {
  7405. bool UseBalloon = FTrayIcon->Visible;
  7406. if (UseBalloon)
  7407. {
  7408. PopupTrayBalloon(Terminal, Message, Type);
  7409. }
  7410. unsigned int Result;
  7411. try
  7412. {
  7413. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7414. }
  7415. __finally
  7416. {
  7417. // cancel only balloon we popped up, otherwise we may cancel notification
  7418. // balloon that was there before the message dialog
  7419. // (such as "dd confirmation opt in balloon)
  7420. if (UseBalloon)
  7421. {
  7422. FTrayIcon->CancelBalloon();
  7423. }
  7424. }
  7425. return Result;
  7426. }
  7427. }
  7428. //---------------------------------------------------------------------------
  7429. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7430. TTerminal * Terminal, Exception * E)
  7431. {
  7432. if (FTrayIcon->Visible)
  7433. {
  7434. PopupTrayBalloon(Terminal, L"", qtError, E);
  7435. }
  7436. // particularly prevent opening new session from jump list,
  7437. // while exception is shown
  7438. NonVisualDataModule->StartBusy();
  7439. try
  7440. {
  7441. ShowExtendedExceptionEx(Terminal, E);
  7442. }
  7443. __finally
  7444. {
  7445. NonVisualDataModule->EndBusy();
  7446. FTrayIcon->CancelBalloon();
  7447. }
  7448. }
  7449. //---------------------------------------------------------------------------
  7450. void __fastcall TCustomScpExplorerForm::SessionReady()
  7451. {
  7452. InitStatusBar();
  7453. // cannot rely on active page being page for active terminal,
  7454. // as it can happen that active page is the "new session" page
  7455. // (e.g. when reconnecting active terminal, while login dialog
  7456. // invoked from "new session" page is modal)
  7457. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7458. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7459. }
  7460. //---------------------------------------------------------------------------
  7461. void TCustomScpExplorerForm::InactiveTerminalNotify(
  7462. TManagedTerminal * Terminal, const UnicodeString & Message, TQueryType Type, Exception * E)
  7463. {
  7464. Notify(Terminal, Message, Type, false, NULL, NULL, E);
  7465. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7466. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7467. {
  7468. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7469. }
  7470. }
  7471. //---------------------------------------------------------------------------
  7472. void TCustomScpExplorerForm::Notify(
  7473. TManagedTerminal * Terminal, const UnicodeString & AMessage, TQueryType Type,
  7474. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7475. {
  7476. UnicodeString Message = AMessage;
  7477. if ((E == NULL) ||
  7478. ExceptionMessage(E, Message))
  7479. {
  7480. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7481. if (Important)
  7482. {
  7483. Seconds *= 5;
  7484. }
  7485. UnicodeString NoteMessage(UnformatMessage(Message));
  7486. if (Terminal != NULL)
  7487. {
  7488. NoteMessage = TTerminalManager::Instance()->FormatTerminalNoteMessage(Terminal, NoteMessage);
  7489. }
  7490. if (WinConfiguration->BalloonNotifications)
  7491. {
  7492. AddNote(NoteMessage);
  7493. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7494. }
  7495. else
  7496. {
  7497. FlashOnBackground();
  7498. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7499. }
  7500. }
  7501. }
  7502. //---------------------------------------------------------------------------
  7503. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7504. {
  7505. RestoreApp();
  7506. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7507. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7508. !NonVisualDataModule->Busy)
  7509. {
  7510. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7511. TTerminalManager::Instance()->ActiveSession = Terminal;
  7512. if (!ComponentVisible[fcQueueView])
  7513. {
  7514. ToggleQueueVisibility();
  7515. GoToQueue();
  7516. }
  7517. }
  7518. }
  7519. //---------------------------------------------------------------------------
  7520. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7521. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7522. {
  7523. UnicodeString Message;
  7524. TNotifyEvent OnClick = NULL;
  7525. TObject * UserData = NULL;
  7526. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7527. switch (Event)
  7528. {
  7529. case qeEmptyButMonitored:
  7530. if ((ATerminal != Terminal) || QueueInvisible)
  7531. {
  7532. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7533. OnClick = QueueEmptyNoteClicked;
  7534. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7535. TerminalNoteData->Terminal = ATerminal;
  7536. UserData = TerminalNoteData;
  7537. }
  7538. break;
  7539. case qeEmpty:
  7540. OperationComplete(ATerminal->QueueOperationStart);
  7541. break;
  7542. case qePendingUserAction:
  7543. if ((ATerminal != Terminal) ||
  7544. (QueueInvisible && !IsQueueAutoPopup()))
  7545. {
  7546. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7547. }
  7548. break;
  7549. default:
  7550. DebugFail();
  7551. }
  7552. if (!Message.IsEmpty())
  7553. {
  7554. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7555. }
  7556. }
  7557. //---------------------------------------------------------------------------
  7558. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7559. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7560. {
  7561. if (FDDExtMapFile != NULL)
  7562. {
  7563. CloseHandle(FDDExtMapFile);
  7564. FDDExtMapFile = NULL;
  7565. }
  7566. if (WinConfiguration->DDFakeFile)
  7567. {
  7568. DDFakeFileInitDrag(FileList, Created);
  7569. }
  7570. }
  7571. //---------------------------------------------------------------------------
  7572. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7573. {
  7574. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7575. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7576. {
  7577. FFakeFileDropTarget = FileName;
  7578. }
  7579. }
  7580. //---------------------------------------------------------------------------
  7581. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7582. {
  7583. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7584. if (!ForceDirectories(ApiPath(Result)))
  7585. {
  7586. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7587. }
  7588. FileSetAttr(ApiPath(Result), faHidden);
  7589. return Result;
  7590. }
  7591. //---------------------------------------------------------------------------
  7592. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7593. bool & Created)
  7594. {
  7595. FFakeFileDropTarget = UnicodeString();
  7596. FDragFakeDirectory = CreateFakeTransferDirectory();
  7597. FileList->AddItem(NULL, FDragFakeDirectory);
  7598. Created = true;
  7599. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7600. {
  7601. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7602. }
  7603. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7604. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7605. {
  7606. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7607. TDragExtCommStruct* CommStruct;
  7608. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7609. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7610. DebugAssert(CommStruct != NULL);
  7611. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7612. CommStruct->Dragging = true;
  7613. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7614. LENOF(CommStruct->DropDest));
  7615. NULL_TERMINATE(CommStruct->DropDest);
  7616. UnmapViewOfFile(CommStruct);
  7617. }
  7618. }
  7619. //---------------------------------------------------------------------------
  7620. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7621. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7622. {
  7623. bool Result;
  7624. DebugAssert(!IsLocalBrowserMode());
  7625. if (Sender == RemoteDirView)
  7626. {
  7627. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7628. }
  7629. else
  7630. {
  7631. DebugAssert(Sender == RemoteDriveView);
  7632. TStrings * FileList = RemoteDriveView->DragFileList();
  7633. try
  7634. {
  7635. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7636. }
  7637. __finally
  7638. {
  7639. delete FileList;
  7640. }
  7641. }
  7642. if (FDDTargetControl == RemoteDriveView)
  7643. {
  7644. RemoteDriveView->UpdateDropTarget();
  7645. }
  7646. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7647. // or from tree view to dir view.
  7648. // foMove happens when file/dir is dragged from remote tree view outside of
  7649. // application via dragex
  7650. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7651. (DropSourceControl == RemoteDriveView))
  7652. {
  7653. RemoteDriveView->UpdateDropSource();
  7654. }
  7655. return Result;
  7656. }
  7657. //---------------------------------------------------------------------------
  7658. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7659. {
  7660. DebugAssert(!IsLocalBrowserMode());
  7661. // This also handles drops of remote files to queue.
  7662. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7663. SAFE_DESTROY(FDDFileList);
  7664. if (!FFakeFileDropTarget.IsEmpty())
  7665. {
  7666. RemoveDir(ApiPath(FFakeFileDropTarget));
  7667. }
  7668. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7669. {
  7670. try
  7671. {
  7672. TDragResult DDResult = (Sender == RemoteDirView) ?
  7673. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7674. // Focus is moved to the target application,
  7675. // but as we are going to present the UI, we need to steal the focus back.
  7676. // This most likely won't work though (windows does not allow application
  7677. // to steal focus most of the time)
  7678. Application->BringToFront();
  7679. // On older version of Windows we never got drMove here, see also comment below.
  7680. // On Windows 10, we get the "move".
  7681. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7682. {
  7683. UnicodeString TargetDirectory;
  7684. TFileOperation Operation;
  7685. // drInvalid may mean drMove, see comment below
  7686. switch (DDResult)
  7687. {
  7688. case drCopy:
  7689. Operation = foCopy;
  7690. break;
  7691. case drMove:
  7692. Operation = foMove;
  7693. break;
  7694. default:
  7695. DebugFail();
  7696. case drInvalid:
  7697. // prefer "copy" for safety
  7698. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7699. break;
  7700. }
  7701. TTransferOperationParam Param;
  7702. UnicodeString CounterName;
  7703. bool ForceQueue;
  7704. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7705. {
  7706. // we get drInvalid both if d&d was intercepted by ddext,
  7707. // and when users drops on no-drop location.
  7708. // we tell the difference by existence of response from ddext,
  7709. // so we ignore absence of response in this case
  7710. if (DDResult != drInvalid)
  7711. {
  7712. // here we know that the extension is installed,
  7713. // as it is checked as soon as drag&drop starts from
  7714. // RemoteFileControlDDCreateDragFileList
  7715. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7716. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7717. {
  7718. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7719. }
  7720. else
  7721. {
  7722. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7723. }
  7724. }
  7725. }
  7726. else
  7727. {
  7728. // download using fake file
  7729. Param.Temp = false;
  7730. Param.DragDrop = true;
  7731. if (ForceQueue)
  7732. {
  7733. Param.Queue = asOn;
  7734. }
  7735. if (Sender == RemoteDirView)
  7736. {
  7737. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7738. }
  7739. if (RemoteFileControlFileOperation(Sender, Operation,
  7740. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7741. {
  7742. Configuration->Usage->Inc(CounterName);
  7743. }
  7744. }
  7745. }
  7746. }
  7747. __finally
  7748. {
  7749. CloseHandle(FDDExtMapFile);
  7750. FDDExtMapFile = NULL;
  7751. delete FDragFakeMonitors;
  7752. FDragFakeMonitors = NULL;
  7753. RemoveDir(ApiPath(FDragFakeDirectory));
  7754. FDragFakeDirectory = L"";
  7755. FFakeFileDropTarget = UnicodeString();
  7756. }
  7757. }
  7758. if (FDragDropSshTerminate.get() != NULL)
  7759. {
  7760. FDragDropSshTerminate->Rethrow();
  7761. }
  7762. }
  7763. //---------------------------------------------------------------------------
  7764. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7765. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7766. {
  7767. // Remember drop effect so we know (when user drops files), if we copy or move
  7768. FLastDropEffect = dwEffect;
  7769. }
  7770. //---------------------------------------------------------------------------
  7771. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7772. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7773. {
  7774. bool Result;
  7775. if (FDDTargetControl == QueueView3)
  7776. {
  7777. Directory = DefaultDownloadTargetDirectory();
  7778. Result = true;
  7779. CounterName = L"DownloadsDragDropQueue";
  7780. ForceQueue = true;
  7781. }
  7782. else if (!FFakeFileDropTarget.IsEmpty())
  7783. {
  7784. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7785. Result = true;
  7786. ForceQueue = false;
  7787. CounterName = L"DownloadsDragDropFakeFile";
  7788. }
  7789. else
  7790. {
  7791. ForceQueue = false;
  7792. Enabled = false;
  7793. try
  7794. {
  7795. int Timer = 0;
  7796. Result = false;
  7797. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7798. {
  7799. {
  7800. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7801. TDragExtCommStruct* CommStruct;
  7802. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7803. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7804. DebugAssert(CommStruct != NULL);
  7805. Result = !CommStruct->Dragging;
  7806. if (Result)
  7807. {
  7808. Directory = ExtractFilePath(CommStruct->DropDest);
  7809. CounterName = L"DownloadsDragDropExternalExt";
  7810. }
  7811. UnmapViewOfFile(CommStruct);
  7812. }
  7813. if (!Result)
  7814. {
  7815. Sleep(50);
  7816. Timer += 50;
  7817. Application->ProcessMessages();
  7818. }
  7819. }
  7820. }
  7821. __finally
  7822. {
  7823. Enabled = true;
  7824. }
  7825. }
  7826. return Result;
  7827. }
  7828. //---------------------------------------------------------------------------
  7829. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7830. const UnicodeString TempDir, int SecDelay)
  7831. {
  7832. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7833. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7834. if (FDelayedDeletionTimer == NULL)
  7835. {
  7836. DebugAssert(HandleAllocated());
  7837. FDelayedDeletionTimer = new TTimer(this);
  7838. FDelayedDeletionTimer->Interval = 10000;
  7839. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7840. }
  7841. else
  7842. {
  7843. FDelayedDeletionTimer->Enabled = true;
  7844. }
  7845. }
  7846. //---------------------------------------------------------------------------
  7847. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7848. {
  7849. DebugAssert(FDelayedDeletionList != NULL);
  7850. TDateTime N = Now();
  7851. TDateTime Alert;
  7852. UnicodeString Directory;
  7853. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7854. {
  7855. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7856. if ((N >= Alert) || (Sender == NULL))
  7857. {
  7858. Directory = FDelayedDeletionList->Strings[Index];
  7859. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7860. {
  7861. FDelayedDeletionList->Delete(Index);
  7862. }
  7863. }
  7864. }
  7865. if (FDelayedDeletionList->Count == 0)
  7866. {
  7867. FDelayedDeletionTimer->Enabled = false;
  7868. }
  7869. }
  7870. //---------------------------------------------------------------------------
  7871. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7872. {
  7873. DebugAssert(!IsLocalBrowserMode());
  7874. if (IsFileControl(FDDTargetControl, osRemote) ||
  7875. (FDDTargetControl == SessionsPageControl))
  7876. {
  7877. TManagedTerminal * TargetTerminal = NULL;
  7878. TFileOperation Operation = foNone;
  7879. if (FDDTargetControl == SessionsPageControl)
  7880. {
  7881. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7882. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7883. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7884. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7885. if (IsAvailableTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7886. {
  7887. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7888. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7889. {
  7890. Operation = foRemoteMove;
  7891. }
  7892. else
  7893. {
  7894. Operation = foRemoteCopy;
  7895. }
  7896. }
  7897. }
  7898. else
  7899. {
  7900. if (FLastDropEffect == DROPEFFECT_MOVE)
  7901. {
  7902. Operation = foRemoteMove;
  7903. }
  7904. else if (FLastDropEffect == DROPEFFECT_COPY)
  7905. {
  7906. Operation = foRemoteCopy;
  7907. }
  7908. }
  7909. if (Operation != foNone)
  7910. {
  7911. RemoteFileControlFileOperation(DropSourceControl,
  7912. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7913. }
  7914. // abort drag&drop
  7915. Abort();
  7916. }
  7917. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7918. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7919. (FDDTargetControl != QueueView3))
  7920. {
  7921. DebugAssert(!FDragTempDir.IsEmpty());
  7922. TTransferType Type;
  7923. UnicodeString TempDir = FDragTempDir;
  7924. // We clear FDragTempDir before calling
  7925. // just in case it fail (raises exception)
  7926. FDragTempDir = L"";
  7927. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7928. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7929. // empty directory parameter means temp directory -> don't display it!
  7930. UnicodeString TargetDir = L"";
  7931. int Options = 0;
  7932. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7933. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7934. {
  7935. Abort();
  7936. }
  7937. // TargetDir is set when dropped on local file control
  7938. // (this was workaround for legacy dirview event handling, now it should be
  7939. // made prettier)
  7940. if (TargetDir.IsEmpty())
  7941. {
  7942. TargetDir = TempDir;
  7943. if (ForceDirectories(ApiPath(TargetDir)))
  7944. {
  7945. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7946. FPendingTempSpaceWarn = true;
  7947. try
  7948. {
  7949. FDragDropOperation = true;
  7950. int Params = cpTemporary |
  7951. (Type == ttMove ? cpDelete : 0);
  7952. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7953. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7954. }
  7955. __finally
  7956. {
  7957. FDragDropOperation = false;
  7958. FPendingTempSpaceWarn = false;
  7959. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7960. }
  7961. }
  7962. else
  7963. {
  7964. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7965. }
  7966. }
  7967. }
  7968. }
  7969. //---------------------------------------------------------------------------
  7970. void __fastcall TCustomScpExplorerForm::DDDownload(
  7971. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7972. {
  7973. DebugAssert(!IsLocalBrowserMode());
  7974. TAutoBatch AutoBatch(this);
  7975. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7976. UpdateCopyParamCounters(*CopyParam);
  7977. FMoveToQueue = false;
  7978. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7979. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7980. {
  7981. RemoteDriveView->UpdateDropSource();
  7982. }
  7983. }
  7984. //---------------------------------------------------------------------------
  7985. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7986. {
  7987. public:
  7988. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7989. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7990. {
  7991. }
  7992. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7993. {
  7994. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7995. TDataObjectFilesEx::AllowData(FormatEtc);
  7996. }
  7997. };
  7998. //---------------------------------------------------------------------------
  7999. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  8000. TObject * Sender, TDataObject *& DataObject)
  8001. {
  8002. if (FDDExtMapFile != NULL)
  8003. {
  8004. TFileList * FileList = DragDropFiles(Sender)->FileList;
  8005. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  8006. {
  8007. Abort();
  8008. }
  8009. if (FileList->Count > 0)
  8010. {
  8011. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  8012. if (!FilesObject->IsValid(true, true))
  8013. {
  8014. FilesObject->_Release();
  8015. }
  8016. else
  8017. {
  8018. DataObject = FilesObject;
  8019. }
  8020. }
  8021. }
  8022. }
  8023. //---------------------------------------------------------------------------
  8024. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  8025. {
  8026. DebugFail();
  8027. }
  8028. //---------------------------------------------------------------------------
  8029. void __fastcall TCustomScpExplorerForm::GoToTree()
  8030. {
  8031. ComponentVisible[fcRemoteTree] = true;
  8032. DriveView(osRemote)->SetFocus();
  8033. }
  8034. //---------------------------------------------------------------------------
  8035. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  8036. TPanelExport Export)
  8037. {
  8038. TCustomDirView * DirView = this->DirView(Side);
  8039. std::unique_ptr<TStrings> ExportData(new TStringList());
  8040. switch (Export)
  8041. {
  8042. case pePath:
  8043. ExportData->Add(DirView->PathName);
  8044. break;
  8045. case peFileList:
  8046. case peFullFileList:
  8047. {
  8048. bool FullPath = (Export == peFullFileList);
  8049. DirView->CreateFileList(false, FullPath, ExportData.get());
  8050. for (int Index = 0; Index < ExportData->Count; Index++)
  8051. {
  8052. if (ExportData->Strings[Index].Pos(L" ") > 0)
  8053. {
  8054. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  8055. }
  8056. }
  8057. }
  8058. break;
  8059. default:
  8060. DebugFail();
  8061. }
  8062. return ExportData.release();
  8063. }
  8064. //---------------------------------------------------------------------------
  8065. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  8066. TPanelExport Export, TPanelExportDestination Destination)
  8067. {
  8068. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  8069. PanelExportStore(Side, Export, Destination, ExportData.get());
  8070. }
  8071. //---------------------------------------------------------------------------
  8072. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  8073. TPanelExport /*Export*/, TPanelExportDestination Destination,
  8074. TStrings * ExportData)
  8075. {
  8076. if (Destination == pedClipboard)
  8077. {
  8078. TInstantOperationVisualizer Visualizer;
  8079. CopyToClipboard(ExportData);
  8080. }
  8081. else
  8082. {
  8083. DebugFail();
  8084. }
  8085. }
  8086. //---------------------------------------------------------------------------
  8087. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8088. {
  8089. TCustomDirView * DirView = this->DirView(Side);
  8090. UnicodeString Mask = DirView->Mask;
  8091. if (DoFilterMaskDialog(DirView, Mask))
  8092. {
  8093. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8094. Configuration->Usage->Inc(L"Filters");
  8095. }
  8096. }
  8097. //---------------------------------------------------------------------------
  8098. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8099. {
  8100. return FQueueController->DefaultOperation();
  8101. }
  8102. //---------------------------------------------------------------------------
  8103. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8104. TQueueOperation Operation, unsigned long * Param)
  8105. {
  8106. switch (Operation)
  8107. {
  8108. case qoPreferences:
  8109. return true;
  8110. case qoGoTo:
  8111. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8112. case qoOnceEmpty:
  8113. return IsAnythingQueued();
  8114. default:
  8115. return FQueueController->AllowOperation(Operation, Param);
  8116. }
  8117. }
  8118. //---------------------------------------------------------------------------
  8119. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8120. {
  8121. if (DebugAlwaysTrue(QueueView3->Visible))
  8122. {
  8123. QueueView3->SetFocus();
  8124. }
  8125. }
  8126. //---------------------------------------------------------------------------
  8127. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8128. TQueueOperation Operation, unsigned long Param)
  8129. {
  8130. if (Operation == qoGoTo)
  8131. {
  8132. GoToQueue();
  8133. }
  8134. else if (Operation == qoPreferences)
  8135. {
  8136. PreferencesDialog(pmQueue);
  8137. }
  8138. else
  8139. {
  8140. FQueueController->ExecuteOperation(Operation, Param);
  8141. }
  8142. }
  8143. //---------------------------------------------------------------------------
  8144. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8145. {
  8146. return (Queue != NULL) && Queue->Enabled;
  8147. }
  8148. //---------------------------------------------------------------------------
  8149. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8150. {
  8151. DebugAssert(Queue != NULL);
  8152. if (Queue != NULL)
  8153. {
  8154. Queue->Enabled = !Queue->Enabled;
  8155. }
  8156. }
  8157. //---------------------------------------------------------------------------
  8158. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8159. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8160. {
  8161. FQueueActedItem = QueueView3->ItemFocused;
  8162. }
  8163. //---------------------------------------------------------------------------
  8164. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8165. {
  8166. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8167. }
  8168. //---------------------------------------------------------------------------
  8169. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8170. {
  8171. return
  8172. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8173. (QueueDock->Visible ? QueueDock->Height : 0) +
  8174. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8175. }
  8176. //---------------------------------------------------------------------------
  8177. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8178. {
  8179. return ScaleByTextHeight(this, 48);
  8180. }
  8181. //---------------------------------------------------------------------------
  8182. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8183. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8184. {
  8185. // when queue is hidden by double-clicking splitter, stray attempt to
  8186. // resize the panel with strange value arrives, make sure it is ignored
  8187. if (ComponentVisible[fcQueueView])
  8188. {
  8189. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8190. if (NewSize > MaxHeightLimit)
  8191. {
  8192. NewSize = MaxHeightLimit;
  8193. }
  8194. int MinHeightLimit =
  8195. GetStaticQueuePanelComponentsHeight() +
  8196. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8197. GetMinQueueViewHeight();
  8198. if (NewSize < MinHeightLimit)
  8199. {
  8200. NewSize = MinHeightLimit;
  8201. }
  8202. }
  8203. else
  8204. {
  8205. Accept = false;
  8206. }
  8207. }
  8208. //---------------------------------------------------------------------------
  8209. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8210. {
  8211. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8212. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8213. if (QueueViewHeight < GetMinQueueViewHeight())
  8214. {
  8215. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8216. }
  8217. }
  8218. //---------------------------------------------------------------------------
  8219. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8220. TDragObject *& /*DragObject*/)
  8221. {
  8222. FQueueActedItem = QueueView3->ItemFocused;
  8223. FQueueScrollOnDragOver->StartDrag();
  8224. }
  8225. //---------------------------------------------------------------------------
  8226. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8227. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8228. {
  8229. FQueueScrollOnDragOver->EndDrag();
  8230. }
  8231. //---------------------------------------------------------------------------
  8232. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8233. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8234. {
  8235. Accept = true;
  8236. if (Source == QueueView3)
  8237. {
  8238. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8239. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8240. if (Accept)
  8241. {
  8242. TQueueItemProxy * QueueItem;
  8243. TQueueItemProxy * DestQueueItem;
  8244. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8245. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8246. Accept = (QueueItem != DestQueueItem) &&
  8247. (QueueItem->Status == TQueueItem::qsPending) &&
  8248. (DestQueueItem->Status == TQueueItem::qsPending);
  8249. }
  8250. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8251. }
  8252. }
  8253. //---------------------------------------------------------------------------
  8254. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8255. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8256. {
  8257. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8258. {
  8259. TQueueItemProxy * QueueItem;
  8260. TQueueItemProxy * DestQueueItem;
  8261. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8262. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8263. QueueItem->Move(DestQueueItem);
  8264. }
  8265. }
  8266. //---------------------------------------------------------------------------
  8267. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8268. {
  8269. if ((QueueView3->ItemFocused == NULL) &&
  8270. (QueueView3->Items->Count > 0))
  8271. {
  8272. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8273. }
  8274. QueueLabelUpdateStatus();
  8275. }
  8276. //---------------------------------------------------------------------------
  8277. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8278. {
  8279. QueueLabelUpdateStatus();
  8280. }
  8281. //---------------------------------------------------------------------------
  8282. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8283. {
  8284. QueueLabel->UpdateStatus();
  8285. }
  8286. //---------------------------------------------------------------------------
  8287. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8288. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8289. {
  8290. if (Selected)
  8291. {
  8292. NonVisualDataModule->UpdateNonVisibleActions();
  8293. }
  8294. }
  8295. //---------------------------------------------------------------------------
  8296. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8297. {
  8298. TDragDropFilesEx * Result = NULL;
  8299. if (Sender == SessionsPageControl)
  8300. {
  8301. Result = FSessionsDragDropFilesEx;
  8302. }
  8303. else if (Sender == QueueView3)
  8304. {
  8305. Result = FQueueDragDropFilesEx;
  8306. }
  8307. else
  8308. {
  8309. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8310. if (DirView != NULL)
  8311. {
  8312. Result = DirView->DragDropFilesEx;
  8313. }
  8314. else
  8315. {
  8316. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8317. if (DriveView != NULL)
  8318. {
  8319. Result = DriveView->DragDropFilesEx;
  8320. }
  8321. }
  8322. }
  8323. DebugAssert(Result != NULL);
  8324. return Result;
  8325. }
  8326. //---------------------------------------------------------------------------
  8327. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8328. {
  8329. return (DView->SelCount == DView->FilesCount);
  8330. }
  8331. //---------------------------------------------------------------------------
  8332. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8333. {
  8334. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8335. }
  8336. //---------------------------------------------------------------------------
  8337. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8338. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8339. {
  8340. DebugAssert(!IsLocalBrowserMode());
  8341. TFileOperation Operation;
  8342. switch (Effect)
  8343. {
  8344. case DROPEFFECT_MOVE:
  8345. Operation = foMove;
  8346. break;
  8347. case DROPEFFECT_COPY:
  8348. // occures on WinXP (reported by user)
  8349. default:
  8350. Operation = foCopy;
  8351. break;
  8352. };
  8353. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8354. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8355. if (DragDropFilesEx->FileList->Count > 0)
  8356. {
  8357. TStrings * FileList = new TStringList();
  8358. try
  8359. {
  8360. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8361. {
  8362. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8363. }
  8364. FDragDropOperation = true;
  8365. TTransferOperationParam Param;
  8366. Param.TargetDirectory = TargetPath;
  8367. // upload, no temp dirs
  8368. Param.Temp = false;
  8369. Param.DragDrop = DragDrop;
  8370. Param.Options =
  8371. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8372. if (ForceQueue)
  8373. {
  8374. Param.Queue = asOn;
  8375. }
  8376. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8377. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8378. {
  8379. if (IsFileControl(DropSourceControl, osLocal))
  8380. {
  8381. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8382. }
  8383. else
  8384. {
  8385. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8386. }
  8387. }
  8388. }
  8389. __finally
  8390. {
  8391. FDragDropOperation = false;
  8392. delete FileList;
  8393. }
  8394. }
  8395. }
  8396. //---------------------------------------------------------------------------
  8397. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8398. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8399. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8400. {
  8401. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8402. }
  8403. //---------------------------------------------------------------------------
  8404. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8405. TObject * Sender, int grfKeyState, int & dwEffect)
  8406. {
  8407. DebugAssert(!IsLocalBrowserMode());
  8408. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8409. if ((dwEffect != DROPEFFECT_NONE) &&
  8410. IsFileControl(DropSourceControl, osRemote))
  8411. {
  8412. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8413. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8414. (RemoteDirView->DropTarget == NULL))
  8415. {
  8416. dwEffect = DROPEFFECT_NONE;
  8417. }
  8418. else
  8419. {
  8420. if (dwEffect == DROPEFFECT_COPY)
  8421. {
  8422. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8423. // currently we support copying always (at least via temporary directory);
  8424. // remove associated checks once this all proves stable and working
  8425. bool CopyCapable = true;
  8426. // if we do not support neither of operations, there's no discussion
  8427. if (!MoveCapable && !CopyCapable)
  8428. {
  8429. dwEffect = DROPEFFECT_NONE;
  8430. }
  8431. else
  8432. {
  8433. // The default effect inside remote panel is move,
  8434. // unless we do not support it, but support copy
  8435. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8436. {
  8437. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8438. }
  8439. else
  8440. {
  8441. // with ctrl-down, we want copy unless it is not supported
  8442. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8443. }
  8444. }
  8445. }
  8446. }
  8447. }
  8448. }
  8449. //---------------------------------------------------------------------------
  8450. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8451. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8452. {
  8453. DebugAssert(!IsLocalBrowserMode());
  8454. if (FDDTotalSize >= 0)
  8455. {
  8456. if (File->IsDirectory)
  8457. {
  8458. FDDTotalSize = -1;
  8459. }
  8460. else
  8461. {
  8462. FDDTotalSize += File->Size;
  8463. }
  8464. }
  8465. DebugAssert(!FDragTempDir.IsEmpty());
  8466. // TODO: this is quite ineffective
  8467. // TODO: what if invalid character replacement is disabled?
  8468. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8469. UnicodeString TransferFileName;
  8470. if (Sender == RemoteDriveView)
  8471. {
  8472. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8473. }
  8474. else
  8475. {
  8476. TransferFileName = File->FileName;
  8477. }
  8478. FDDFileList->AddObject(TransferFileName, File);
  8479. }
  8480. //---------------------------------------------------------------------------
  8481. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8482. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8483. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8484. {
  8485. // sometimes we do not get DDEnd so the list is not released
  8486. SAFE_DESTROY(FDDFileList);
  8487. FDDFileList = new TStringList();
  8488. FDragTempDir = WinConfiguration->TemporaryDir();
  8489. FDDTotalSize = 0;
  8490. FDragDropSshTerminate.reset(NULL);
  8491. }
  8492. //---------------------------------------------------------------------------
  8493. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8494. TObject * /*Sender*/, LongBool /*FEscapePressed*/, int /*grfKeyState*/,
  8495. HRESULT & Result)
  8496. {
  8497. if (Result == DRAGDROP_S_DROP)
  8498. {
  8499. try
  8500. {
  8501. GlobalDragImageList->HideDragImage();
  8502. try
  8503. {
  8504. RemoteFileControlDDTargetDrop();
  8505. }
  8506. catch(ESshTerminate & E)
  8507. {
  8508. FDragDropSshTerminate.reset(E.Clone());
  8509. }
  8510. }
  8511. catch (Exception &E)
  8512. {
  8513. // If downloading fails we need to cancel drag&drop, otherwise
  8514. // Explorer shows error
  8515. // But by the way exception probably never reach this point as
  8516. // it's catched on way.
  8517. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8518. Result = DRAGDROP_S_CANCEL;
  8519. ShowExtendedException(Terminal, &E);
  8520. }
  8521. }
  8522. }
  8523. //---------------------------------------------------------------------------
  8524. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8525. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8526. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8527. {
  8528. TFileMasks::TParams MaskParams;
  8529. MaskParams.Size = Size;
  8530. MaskParams.Modification = Modification;
  8531. // this does not re-parse the mask if it is the same as the last time
  8532. FDirViewMatchMask = Masks;
  8533. bool ImplicitMatch;
  8534. Matches =
  8535. // Local and RecurseInclude parameters have no effect as there's no path.
  8536. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8537. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8538. (AllowImplicitMatches || !ImplicitMatch);
  8539. }
  8540. //---------------------------------------------------------------------------
  8541. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8542. TObject * Sender, TListItem * Item, WORD & Indexes)
  8543. {
  8544. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8545. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8546. {
  8547. Indexes |= oiPartial;
  8548. }
  8549. }
  8550. //---------------------------------------------------------------------------
  8551. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8552. {
  8553. return
  8554. DirViewEnabled(osCurrent) &&
  8555. DirView(osCurrent)->CanPasteFromClipBoard();
  8556. }
  8557. //---------------------------------------------------------------------------
  8558. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8559. {
  8560. bool Result = false;
  8561. if (CanPasteToDirViewFromClipBoard())
  8562. {
  8563. Result = true;
  8564. }
  8565. else
  8566. {
  8567. UnicodeString ClipboardText;
  8568. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8569. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8570. {
  8571. if (StoredSessions->IsUrl(ClipboardText))
  8572. {
  8573. Result = true;
  8574. }
  8575. else
  8576. {
  8577. Result = DirViewEnabled(osCurrent);
  8578. }
  8579. }
  8580. }
  8581. return Result;
  8582. }
  8583. //---------------------------------------------------------------------------
  8584. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8585. {
  8586. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8587. if (DoesClipboardContainOurFiles())
  8588. {
  8589. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8590. {
  8591. DebugAssert(!IsLocalBrowserMode());
  8592. TTerminalManager * Manager = TTerminalManager::Instance();
  8593. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8594. Manager->ActiveSession = FClipboardTerminal;
  8595. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8596. }
  8597. }
  8598. else if (CanPasteToDirViewFromClipBoard())
  8599. {
  8600. DirView(osCurrent)->PasteFromClipBoard();
  8601. }
  8602. else
  8603. {
  8604. UnicodeString ClipboardText;
  8605. if (NonEmptyTextFromClipboard(ClipboardText))
  8606. {
  8607. if (StoredSessions->IsUrl(ClipboardText))
  8608. {
  8609. NewSession(ClipboardText);
  8610. }
  8611. else
  8612. {
  8613. DirView(osCurrent)->Path = ClipboardText;
  8614. }
  8615. }
  8616. }
  8617. }
  8618. //---------------------------------------------------------------------------
  8619. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8620. {
  8621. // TBD
  8622. }
  8623. //---------------------------------------------------------------------------
  8624. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8625. {
  8626. TCustomDirView * ADirView = DirView(Side);
  8627. ADirView->SelectAll(Mode);
  8628. ADirView->SetFocus();
  8629. }
  8630. //---------------------------------------------------------------------------
  8631. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8632. {
  8633. TCustomDirView * ADirView = DirView(Side);
  8634. TFileFilter Filter;
  8635. DefaultFileFilter(Filter);
  8636. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8637. {
  8638. Configuration->Usage->Inc(L"MaskSelections");
  8639. ADirView->SelectFiles(Filter, Select);
  8640. ADirView->SetFocus();
  8641. }
  8642. }
  8643. //---------------------------------------------------------------------------
  8644. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8645. {
  8646. TCustomDirView * ADirView = DirView(Side);
  8647. ADirView->RestoreSelectedNames();
  8648. ADirView->SetFocus();
  8649. }
  8650. //---------------------------------------------------------------------------
  8651. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8652. {
  8653. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8654. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8655. {
  8656. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8657. UnicodeString Ext;
  8658. if (!IsSideLocalBrowser(osCurrent))
  8659. {
  8660. Ext = UnixExtractFileExt(FileName);
  8661. }
  8662. else
  8663. {
  8664. Ext = ExtractFileExt(FileName);
  8665. }
  8666. if (Ext.IsEmpty())
  8667. {
  8668. Ext = L".";
  8669. }
  8670. TFileFilter Filter;
  8671. Filter.Masks = FORMAT(L"*%s", (Ext));
  8672. Filter.Directories = false;
  8673. CurrentDirView->SelectFiles(Filter, Select);
  8674. }
  8675. }
  8676. //---------------------------------------------------------------------------
  8677. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8678. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8679. {
  8680. UnicodeString Result;
  8681. if (FIncrementalSearchState.Searching && (Side == GetSide(osCurrent)))
  8682. {
  8683. Result = FormatIncrementalSearchStatus(FIncrementalSearchState);
  8684. }
  8685. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8686. {
  8687. // noop
  8688. }
  8689. else
  8690. {
  8691. Result =
  8692. FMTLOAD(FILE_INFO_FORMAT,
  8693. (FormatBytes(FileInfo.SelectedSize),
  8694. FormatBytes(FileInfo.FilesSize),
  8695. FormatNumber(FileInfo.SelectedCount),
  8696. FormatNumber(FileInfo.FilesCount)));
  8697. }
  8698. return Result;
  8699. }
  8700. //---------------------------------------------------------------------------
  8701. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8702. TTBXStatusPanel * Panel, TOperationSide Side)
  8703. {
  8704. if (Panel->Index == 1)
  8705. {
  8706. ToggleShowHiddenFiles();
  8707. }
  8708. else if (Panel->Index == 2)
  8709. {
  8710. Filter(Side);
  8711. }
  8712. }
  8713. //---------------------------------------------------------------------------
  8714. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8715. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8716. {
  8717. DebugAssert(!StatusBar->SimplePanel);
  8718. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8719. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8720. }
  8721. //---------------------------------------------------------------------------
  8722. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8723. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8724. {
  8725. DebugAssert(StatusBar->Panels->Count >= 3);
  8726. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8727. if (FileInfo.HiddenCount > 0)
  8728. {
  8729. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8730. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8731. }
  8732. else
  8733. {
  8734. HiddenFilesPanel->ViewPriority = 0;
  8735. // not really necessary, just to cleanup no-longer-valid data
  8736. HiddenFilesPanel->Caption = L"";
  8737. }
  8738. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8739. if (FileInfo.FilteredCount > 0)
  8740. {
  8741. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8742. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8743. }
  8744. else
  8745. {
  8746. FilteredFilesPanel->ViewPriority = 0;
  8747. // not really necessary, just to cleanup no-longer-valid data
  8748. FilteredFilesPanel->Caption = L"";
  8749. }
  8750. }
  8751. //---------------------------------------------------------------------------
  8752. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8753. TObject * /*Sender*/)
  8754. {
  8755. if (DirView(osOther)->Enabled)
  8756. {
  8757. DirView(osOther)->SetFocus();
  8758. }
  8759. }
  8760. //---------------------------------------------------------------------------
  8761. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8762. {
  8763. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8764. switch (Config.Show)
  8765. {
  8766. case qvShow:
  8767. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8768. {
  8769. Config.Show = qvHide;
  8770. }
  8771. else
  8772. {
  8773. Config.Show = Config.LastHideShow;
  8774. }
  8775. break;
  8776. case qvHideWhenEmpty:
  8777. if (ComponentVisible[fcQueueView])
  8778. {
  8779. Config.Show = qvHide;
  8780. }
  8781. else
  8782. {
  8783. Config.LastHideShow = Config.Show;
  8784. Config.Show = qvShow;
  8785. }
  8786. break;
  8787. case qvHide:
  8788. Config.LastHideShow = Config.Show;
  8789. Config.Show = qvShow;
  8790. break;
  8791. }
  8792. WinConfiguration->QueueView = Config;
  8793. }
  8794. //---------------------------------------------------------------------------
  8795. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8796. {
  8797. UnicodeString Result;
  8798. if (Terminal != NULL)
  8799. {
  8800. switch (WinConfiguration->PathInCaption)
  8801. {
  8802. case picShort:
  8803. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8804. break;
  8805. case picFull:
  8806. Result = Terminal->CurrentDirectory;
  8807. break;
  8808. }
  8809. }
  8810. return Result;
  8811. }
  8812. //---------------------------------------------------------------------------
  8813. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8814. {
  8815. TColor Result = GetWindowColor(FSessionColor);
  8816. return Result;
  8817. }
  8818. //---------------------------------------------------------------------------
  8819. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8820. {
  8821. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8822. return Result;
  8823. }
  8824. //---------------------------------------------------------------------------
  8825. void TCustomScpExplorerForm::UpdatePanelControls(TCustomDirView * ADirView, TCustomDriveView * ADriveView)
  8826. {
  8827. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8828. ADirView->DarkMode = UseDarkTheme;
  8829. ADriveView->DarkMode = UseDarkTheme;
  8830. }
  8831. //---------------------------------------------------------------------------
  8832. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8833. {
  8834. if (!FSessionChanging)
  8835. {
  8836. TTerminalManager::Instance()->UpdateAppTitle();
  8837. }
  8838. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8839. // background to gray on Windows 7 (works on Windows 10).
  8840. // See also EnableControl
  8841. if (Showing)
  8842. {
  8843. if (ManagedSession != NULL)
  8844. {
  8845. // Update path when it changes
  8846. if ((SessionsPageControl->ActivePage != NULL) &&
  8847. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8848. {
  8849. UpdateSessionTab(SessionsPageControl->ActivePage);
  8850. }
  8851. }
  8852. NonVisualDataModule->ReconnectSessionAction->Update();
  8853. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8854. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8855. CenterReconnectToolbar();
  8856. // The only place, where we use IsOpenedTerminal and not IsAvailableTerminal
  8857. // (i.e. not checking for reconnecting status)
  8858. // Otherwise it causes flicker [particularly in dark mode] during the short time
  8859. // between the authentication window is closed and FOpeningTerminal is cleared.
  8860. // Should be solved smarter.
  8861. bool HasTerminal = TTerminalManager::Instance()->IsOpenedTerminal(Terminal);
  8862. RemoteDirView->Enabled = HasTerminal;
  8863. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8864. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8865. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8866. RemoteDriveView->Color = RemoteDirView->Color;
  8867. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8868. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8869. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8870. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8871. QueueFileList->Enabled = QueueView3->Enabled;
  8872. QueueFileList->Color = QueueView3->Color;
  8873. QueueFileList->Font->Color = QueueView3->Font->Color;
  8874. QueueLabelUpdateStatus();
  8875. UpdatePanelControls(RemoteDirView, RemoteDriveView);
  8876. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8877. if (FImmersiveDarkMode != UseDarkTheme)
  8878. {
  8879. UpdateDarkMode();
  8880. }
  8881. SessionsPageControl->TabTheme = UseDarkTheme ? CurrentTheme : NULL;
  8882. QueueView3->DarkMode = UseDarkTheme;
  8883. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8884. bool HiContrast = WinConfiguration->HiContrast;
  8885. UnicodeString NewHiContrastThemeName = HiContrast ? GetThemeName(!UseDarkTheme) : EmptyStr;
  8886. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8887. {
  8888. ReleaseHiContrastTheme();
  8889. if (!NewHiContrastThemeName.IsEmpty())
  8890. {
  8891. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8892. }
  8893. }
  8894. SessionsPageControl->ActiveTabTheme = HiContrast ? DebugNotNull(FHiContrastTheme) : NULL;
  8895. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8896. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8897. }
  8898. }
  8899. //---------------------------------------------------------------------------
  8900. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8901. {
  8902. UpdateControls();
  8903. }
  8904. //---------------------------------------------------------------------------
  8905. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8906. TObject * Sender)
  8907. {
  8908. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8909. DebugAssert(DirView != NULL);
  8910. DoDirViewLoaded(DirView);
  8911. TransferPresetAutoSelect();
  8912. TUnixDirView * UnixDirView = dynamic_cast<TUnixDirView *>(DirView);
  8913. if (UnixDirView != NULL)
  8914. {
  8915. TManagedTerminal * ATerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(UnixDirView->Terminal));
  8916. TTerminalManager::Instance()->TerminalLoadedDirectory(ATerminal);
  8917. }
  8918. }
  8919. //---------------------------------------------------------------------------
  8920. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8921. {
  8922. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8923. // first run after installation
  8924. if (double(Updates.LastCheck) == 0)
  8925. {
  8926. AppLog(L"First run, scheduling updates check for the next run");
  8927. // make sure next time there will be an update (if enabled)
  8928. Updates.LastCheck = TDateTime(1);
  8929. WinConfiguration->Updates = Updates;
  8930. }
  8931. else
  8932. {
  8933. TDateTime Period;
  8934. if (IsUWP() && !IsOfficialPackage())
  8935. {
  8936. Period = DefaultUpdatesPeriod;
  8937. AppLog(L"Thirdparty UWP package, using default updates check period");
  8938. }
  8939. else
  8940. {
  8941. Period = Updates.Period;
  8942. }
  8943. AppLogFmt(L"Updates check period: %.2f", (DateTimeToVariant(Period)));
  8944. if (double(Period) > 0)
  8945. {
  8946. TDateTime Interval = Now() - Updates.LastCheck;
  8947. AppLogFmt(L"Interval since the last updates check: %.2f", (DateTimeToVariant(Interval)));
  8948. if (Interval >= Period)
  8949. {
  8950. StartUpdateThread(UpdatesChecked);
  8951. }
  8952. }
  8953. }
  8954. }
  8955. //---------------------------------------------------------------------------
  8956. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8957. {
  8958. AppLog(L"Updates check done");
  8959. UnicodeString Message;
  8960. bool New;
  8961. TQueryType Type;
  8962. GetUpdatesMessage(Message, New, Type, false);
  8963. if (!Message.IsEmpty())
  8964. {
  8965. AppLogFmt(L"Updates check message: %s", (Message));
  8966. if (New)
  8967. {
  8968. AppLog(L"New version detected");
  8969. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8970. }
  8971. if (!New && (Type != qtWarning))
  8972. {
  8973. AppLog(L"Posting non-critical updates note");
  8974. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked);
  8975. }
  8976. else
  8977. {
  8978. AppLog(L"Posting new version or critical message notification");
  8979. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8980. }
  8981. if (New)
  8982. {
  8983. Configuration->Usage->Inc(L"UpdateNotifications");
  8984. }
  8985. }
  8986. }
  8987. //---------------------------------------------------------------------------
  8988. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8989. {
  8990. RestoreApp();
  8991. bool CanDisplay = !NonVisualDataModule->Busy;
  8992. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8993. {
  8994. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8995. }
  8996. if (CanDisplay)
  8997. {
  8998. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8999. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  9000. NonVisualDataModule->StartBusy();
  9001. try
  9002. {
  9003. CheckForUpdates(true);
  9004. }
  9005. __finally
  9006. {
  9007. NonVisualDataModule->EndBusy();
  9008. }
  9009. }
  9010. else
  9011. {
  9012. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  9013. }
  9014. }
  9015. //---------------------------------------------------------------------------
  9016. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  9017. TCopyParamRuleData & Data)
  9018. {
  9019. DebugAssert(Terminal != NULL);
  9020. Data.HostName = Terminal->SessionData->HostNameExpanded;
  9021. Data.UserName = Terminal->SessionData->UserNameExpanded;
  9022. Data.RemoteDirectory = RemoteDirView->PathName;
  9023. }
  9024. //---------------------------------------------------------------------------
  9025. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  9026. {
  9027. // Terminal can be null when we are changing local directory implicitly,
  9028. // because it has been deleted, while no session is connected
  9029. // (Login dialog is open)
  9030. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  9031. {
  9032. DebugAssert(!IsLocalBrowserMode());
  9033. TCopyParamRuleData Data;
  9034. GetTransferPresetAutoSelectData(Data);
  9035. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  9036. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  9037. if (CopyParamIndex < 0)
  9038. {
  9039. // there is no preset that matches autoselection
  9040. // set preset that we consider "default"
  9041. FCopyParamAutoSelected = L""; // forget last autoselected preset
  9042. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  9043. }
  9044. else
  9045. {
  9046. // there is preset matching autoselection
  9047. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  9048. if (CopyParamName == FCopyParamAutoSelected)
  9049. {
  9050. // autoselected the same preset as the last time
  9051. // make no change (i.e. preserve custom user preset, if any)
  9052. }
  9053. else
  9054. {
  9055. // autoselected the different preset then the last time (or there
  9056. // was default preset set)
  9057. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  9058. GUIConfiguration->CopyParamCurrent = CopyParamName;
  9059. }
  9060. }
  9061. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  9062. {
  9063. if (CopyParamIndex >= 0)
  9064. {
  9065. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  9066. }
  9067. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  9068. try
  9069. {
  9070. int Fmt =
  9071. (CopyParamIndex < 0) ?
  9072. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  9073. COPY_PARAM_AUTOSELECTED;
  9074. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  9075. Data->Message = MainInstructions(Message);
  9076. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  9077. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  9078. CopyParamAttrs);
  9079. if (CopyParamIndex >= 0)
  9080. {
  9081. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  9082. Info = FORMAT(L"%s\n \n%s", (Info,
  9083. FMTLOAD(COPY_PARAM_RULE,
  9084. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  9085. }
  9086. Data->Message += L"\n\n" + Info;
  9087. if (WinConfiguration->CopyParamAutoSelectNotice)
  9088. {
  9089. TransferPresetNoteMessage(Data, true);
  9090. }
  9091. else
  9092. {
  9093. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  9094. Data = NULL; // ownership passed
  9095. }
  9096. }
  9097. __finally
  9098. {
  9099. delete Data;
  9100. }
  9101. }
  9102. }
  9103. }
  9104. //---------------------------------------------------------------------------
  9105. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9106. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9107. {
  9108. DebugAssert(NoteData != NULL);
  9109. DebugAssert(!IsLocalBrowserMode());
  9110. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9111. TQueryButtonAlias Aliases[1];
  9112. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9113. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9114. Params.Aliases = Aliases;
  9115. Params.AliasesCount = LENOF(Aliases);
  9116. unsigned int Result =
  9117. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9118. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9119. switch (Result)
  9120. {
  9121. case qaNeverAskAgain:
  9122. DebugAssert(AllowNeverAskAgain);
  9123. WinConfiguration->CopyParamAutoSelectNotice = false;
  9124. break;
  9125. case qaIgnore:
  9126. PreferencesDialog(pmPresets);
  9127. break;
  9128. }
  9129. }
  9130. //---------------------------------------------------------------------------
  9131. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9132. {
  9133. // as of now useless, as this is used for notes only, never for balloons, ...
  9134. RestoreApp();
  9135. // .. and we should never be busy here
  9136. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9137. {
  9138. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9139. }
  9140. }
  9141. //---------------------------------------------------------------------------
  9142. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9143. TPreferencesMode APreferencesMode)
  9144. {
  9145. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9146. TCopyParamRuleData Data;
  9147. if (Terminal != NULL)
  9148. {
  9149. PreferencesData.reset(new TPreferencesDialogData());
  9150. GetTransferPresetAutoSelectData(Data);
  9151. PreferencesData->CopyParamRuleData = &Data;
  9152. }
  9153. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9154. }
  9155. //---------------------------------------------------------------------------
  9156. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9157. const TCustomCommandType & Command)
  9158. {
  9159. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9160. {
  9161. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9162. }
  9163. }
  9164. //---------------------------------------------------------------------------
  9165. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9166. {
  9167. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9168. TCustomCommandType Command;
  9169. // make sure we use local custom command when remote are not supported
  9170. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9171. {
  9172. Command = FLastCustomCommand;
  9173. }
  9174. else
  9175. {
  9176. Command.Params = Command.Params | ccLocal;
  9177. }
  9178. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9179. FEditingFocusedAdHocCommand = OnFocused;
  9180. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9181. int Options =
  9182. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9183. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9184. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9185. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9186. {
  9187. FLastCustomCommand = Command;
  9188. UpdateCustomCommandsToolbar();
  9189. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9190. }
  9191. }
  9192. //---------------------------------------------------------------------------
  9193. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9194. {
  9195. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9196. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9197. DebugAssert(State > 0);
  9198. if (State <= 0)
  9199. {
  9200. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9201. }
  9202. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9203. }
  9204. //---------------------------------------------------------------------------
  9205. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9206. TCustomCommandType & Command, int & State)
  9207. {
  9208. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9209. if (Result)
  9210. {
  9211. Command = FLastCustomCommand;
  9212. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9213. }
  9214. return Result;
  9215. }
  9216. //---------------------------------------------------------------------------
  9217. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9218. {
  9219. ResetIncrementalSearch();
  9220. }
  9221. //---------------------------------------------------------------------------
  9222. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9223. {
  9224. DebugAssert(ComponentVisible[Component]);
  9225. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9226. }
  9227. //---------------------------------------------------------------------------
  9228. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9229. {
  9230. // when queue panel is resized here directly, the status bar is stretched
  9231. // over whole space the panel occupied
  9232. PostComponentHide(fcQueueView);
  9233. }
  9234. //---------------------------------------------------------------------------
  9235. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9236. {
  9237. ComponentVisible[fcQueueFileList] = false;
  9238. }
  9239. //---------------------------------------------------------------------------
  9240. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9241. {
  9242. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9243. // Scrollbars colors are refreshed by WM_THEMECHANGED.
  9244. RefreshColorMode();
  9245. ResetSysDarkTheme();
  9246. ConfigurationChanged();
  9247. ConfigureInterface();
  9248. // To update references to recreated/destroyed themes in SessionsPageControl
  9249. UpdateControls();
  9250. }
  9251. //---------------------------------------------------------------------------
  9252. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9253. {
  9254. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9255. if (!FInvalid &&
  9256. (Message.LParam != 0) &&
  9257. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9258. {
  9259. ThemeChanged();
  9260. }
  9261. TForm::Dispatch(&Message);
  9262. }
  9263. //---------------------------------------------------------------------------
  9264. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9265. {
  9266. TMessage * M = static_cast<TMessage*>(Message);
  9267. switch (M->Msg)
  9268. {
  9269. case CM_DIALOGCHAR:
  9270. CMDialogChar(*M);
  9271. break;
  9272. case WM_APPCOMMAND:
  9273. WMAppCommand(*M);
  9274. break;
  9275. case WM_SYSCOMMAND:
  9276. WMSysCommand(*M);
  9277. break;
  9278. case WM_QUERYENDSESSION:
  9279. WMQueryEndSession(*M);
  9280. break;
  9281. case WM_ENDSESSION:
  9282. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9283. break;
  9284. case WM_COMPONENT_HIDE:
  9285. {
  9286. Byte Component = static_cast<Byte>(M->WParam);
  9287. // sanity check
  9288. if (ComponentVisible[Component])
  9289. {
  9290. // special treatment
  9291. if (Component == fcQueueView)
  9292. {
  9293. ToggleQueueVisibility();
  9294. DebugAssert(!ComponentVisible[fcQueueView]);
  9295. }
  9296. else
  9297. {
  9298. ComponentVisible[Component] = false;
  9299. }
  9300. }
  9301. }
  9302. break;
  9303. case WM_COPYDATA:
  9304. WMCopyData(*M);
  9305. break;
  9306. case WM_MANAGES_CAPTION:
  9307. // caption managed in TTerminalManager::UpdateAppTitle()
  9308. M->Result = 1;
  9309. break;
  9310. case WM_WANTS_MOUSEWHEEL:
  9311. M->Result = 1;
  9312. break;
  9313. case CM_SHOWINGCHANGED:
  9314. CMShowingChanged(*M);
  9315. break;
  9316. case WM_CLOSE:
  9317. WMClose(*M);
  9318. break;
  9319. case WM_DPICHANGED:
  9320. WMDpiChanged(*M);
  9321. break;
  9322. case WM_SETTINGCHANGE:
  9323. WMSettingChange(*M);
  9324. break;
  9325. case CM_DIALOGKEY:
  9326. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9327. break;
  9328. case WM_PASTE_FILES:
  9329. PasteFiles();
  9330. break;
  9331. case WM_IS_HIDDEN:
  9332. // To treat master password prompt as a main window while showing it when workspace is loading while
  9333. // the exporer is showing up (Visible is true already)
  9334. M->Result = !FShowing;
  9335. break;
  9336. case WM_SHOWWINDOW:
  9337. if (M->WParam)
  9338. {
  9339. AddStartupSequence(L"J");
  9340. }
  9341. TForm::Dispatch(Message);
  9342. break;
  9343. case WM_QUEUE_CALLBACK:
  9344. WMQueueCallback(*M);
  9345. break;
  9346. default:
  9347. TForm::Dispatch(Message);
  9348. break;
  9349. }
  9350. }
  9351. //---------------------------------------------------------------------------
  9352. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9353. {
  9354. // noop
  9355. }
  9356. //---------------------------------------------------------------------------
  9357. void TCustomScpExplorerForm::RegenerateSessionColorsImageList()
  9358. {
  9359. FSessionColors->Clear();
  9360. AddFixedSessionImages();
  9361. ::RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9362. UpdateImages();
  9363. }
  9364. //---------------------------------------------------------------------------
  9365. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9366. {
  9367. TForm::Dispatch(&Message);
  9368. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9369. UpdatePixelsPerInchMainWindowCounter();
  9370. }
  9371. //---------------------------------------------------------------------------
  9372. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9373. {
  9374. AppLog(L"Main window WM_CLOSE");
  9375. // Cannot close window while we are busy.
  9376. // We cannot test this in FormCloseQuery as that is called also from
  9377. // Close(), which is called by CloseApplicationAction. So we can be busy
  9378. // there already even, when it is legitimate to close the application.
  9379. // Possibly a better place to handle this would be WMSysCommand.
  9380. if (NonVisualDataModule->Busy)
  9381. {
  9382. Message.Result = 1;
  9383. }
  9384. else
  9385. {
  9386. TForm::Dispatch(&Message);
  9387. }
  9388. }
  9389. //---------------------------------------------------------------------------
  9390. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9391. {
  9392. if (!FShowingChanged)
  9393. {
  9394. AddStartupSequence(L"D");
  9395. FShowingChanged = true;
  9396. }
  9397. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9398. bool NoSession = (ManagedSession == NULL);
  9399. // This calls TCustomScpExplorerForm::DoShow
  9400. TForm::Dispatch(&Message);
  9401. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9402. if (Showing && !FStarted)
  9403. {
  9404. FStarted = true;
  9405. InterfaceStarted();
  9406. }
  9407. if (Showing && NoSession)
  9408. {
  9409. // When we are starting minimized (i.e. from an installer),
  9410. // postpone showing Login dialog until we get restored.
  9411. // Otherwise the Login dialog (and Authentication window) show restored
  9412. // over invisible (minimized) main window.
  9413. if (WindowState == wsMinimized)
  9414. {
  9415. FNeedSession = true;
  9416. }
  9417. else
  9418. {
  9419. // This happens before application ever goes idle, so the toolbars would
  9420. // stay enabled (initial state) until the Login dialog is dismissed.
  9421. UpdateActions();
  9422. NonVisualDataModule->StartBusy();
  9423. try
  9424. {
  9425. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9426. // otherwise the dialog does not receive focus.
  9427. // With Commander interface the ProcessMessages is called already
  9428. // by TDriveView, but with Explorer interface, we need to call it explicily
  9429. Application->ProcessMessages();
  9430. // do not reload sessions, they have been loaded just now (optimization)
  9431. NeedSession(true);
  9432. }
  9433. __finally
  9434. {
  9435. NonVisualDataModule->EndBusy();
  9436. }
  9437. }
  9438. }
  9439. }
  9440. //---------------------------------------------------------------------------
  9441. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9442. {
  9443. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9444. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9445. }
  9446. //---------------------------------------------------------------------------
  9447. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9448. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9449. int & MaxHeight)
  9450. {
  9451. // workaround for bug in TWinControl.CalcConstraints
  9452. // Check for empty rect (restore from iconic state) is done there only after
  9453. // call to AdjustClientRect, which enlarges the rect (for forms).
  9454. TRect R = GetClientRect();
  9455. // when restoring from iconic state, place no restrictions
  9456. if (IsRectEmpty(R))
  9457. {
  9458. MinWidth = 0;
  9459. MinHeight = 0;
  9460. MaxWidth = 32000;
  9461. MaxHeight = 32000;
  9462. }
  9463. }
  9464. //---------------------------------------------------------------------------
  9465. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9466. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9467. {
  9468. // terminal can be already closed (e.g. dropped connection)
  9469. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9470. {
  9471. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9472. try
  9473. {
  9474. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9475. }
  9476. catch(...)
  9477. {
  9478. if (!Terminal->Active)
  9479. {
  9480. Close = true;
  9481. }
  9482. throw;
  9483. }
  9484. }
  9485. }
  9486. //---------------------------------------------------------------------------
  9487. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9488. {
  9489. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9490. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9491. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9492. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9493. {
  9494. OnGetSpaceAvailable = GetSpaceAvailable;
  9495. }
  9496. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9497. OnGetSpaceAvailable);
  9498. }
  9499. //---------------------------------------------------------------------------
  9500. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9501. {
  9502. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9503. Terminal->FillSessionDataForCode(Data.get());
  9504. return Data.release();
  9505. }
  9506. //---------------------------------------------------------------------------
  9507. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9508. {
  9509. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9510. DoGenerateUrlDialog(Data.get(), Paths);
  9511. }
  9512. //---------------------------------------------------------------------------
  9513. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9514. {
  9515. GenerateUrl(NULL);
  9516. }
  9517. //---------------------------------------------------------------------------
  9518. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9519. {
  9520. std::unique_ptr<TStrings> Paths(new TStringList());
  9521. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9522. GenerateUrl(Paths.get());
  9523. }
  9524. //---------------------------------------------------------------------------
  9525. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9526. {
  9527. FSessionColor = value;
  9528. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9529. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9530. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9531. DebugAssert(ColorItem != NULL);
  9532. ColorItem->Color = C;
  9533. NonVisualDataModule->ColorMenuItem->Color = C;
  9534. UpdateControls();
  9535. }
  9536. //---------------------------------------------------------------------------
  9537. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9538. {
  9539. if (value != FSessionColor)
  9540. {
  9541. UpdateSessionColor(value);
  9542. // Is null when called from LastTerminalClosed
  9543. if (Terminal != NULL)
  9544. {
  9545. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9546. }
  9547. }
  9548. }
  9549. //---------------------------------------------------------------------------
  9550. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9551. {
  9552. bool Result = FNoteTimer->Enabled;
  9553. if (Result)
  9554. {
  9555. // cannot cancel note too early
  9556. bool NotEarly =
  9557. (Now() - FNoteShown >
  9558. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9559. if (Force || NotEarly)
  9560. {
  9561. FNoteTimer->Enabled = false;
  9562. FNote = L"";
  9563. SAFE_DESTROY(FNoteData);
  9564. FOnNoteClick = NULL;
  9565. FNoteHints = FNotes->Text;
  9566. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9567. UpdateStatusBar();
  9568. }
  9569. }
  9570. return Result;
  9571. }
  9572. //---------------------------------------------------------------------------
  9573. void TCustomScpExplorerForm::CancelNote(const UnicodeString & Note)
  9574. {
  9575. if (FNote == Note)
  9576. {
  9577. CancelNote(true);
  9578. }
  9579. }
  9580. //---------------------------------------------------------------------------
  9581. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9582. {
  9583. DebugAssert(FNoteTimer->Enabled);
  9584. CancelNote(true);
  9585. }
  9586. //---------------------------------------------------------------------------
  9587. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9588. {
  9589. FNoteHints = FNotes->Text.TrimRight();
  9590. }
  9591. //---------------------------------------------------------------------------
  9592. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9593. {
  9594. int P = Note.Pos(L"\n");
  9595. if (P > 0)
  9596. {
  9597. Note.SetLength(P - 1);
  9598. }
  9599. FNotes->Add(FORMAT(L"[%s] %s",
  9600. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9601. while (FNotes->Count > 10)
  9602. {
  9603. FNotes->Delete(0);
  9604. }
  9605. if (UpdateNow)
  9606. {
  9607. UpdateNoteHints();
  9608. UpdateStatusBar();
  9609. }
  9610. }
  9611. //---------------------------------------------------------------------------
  9612. void TCustomScpExplorerForm::PostNote(
  9613. const UnicodeString & ANote, unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9614. {
  9615. UnicodeString Note = ANote;
  9616. int P = Note.Pos(L"\n");
  9617. if (P > 0)
  9618. {
  9619. Note.SetLength(P - 1);
  9620. }
  9621. UpdateNoteHints();
  9622. FNote = Note;
  9623. SAFE_DESTROY(FNoteData);
  9624. FNoteData = NoteData;
  9625. FOnNoteClick = OnNoteClick;
  9626. AddNote(Note, false);
  9627. UpdateStatusBar();
  9628. FNoteShown = Now();
  9629. FNoteTimer->Enabled = false;
  9630. if (Seconds == 0)
  9631. {
  9632. Seconds = WinConfiguration->NotificationsTimeout;
  9633. }
  9634. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9635. FNoteTimer->Enabled = true;
  9636. }
  9637. //---------------------------------------------------------------------------
  9638. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9639. {
  9640. PostNote(LoadStr(DIRECTORY_READING_CANCELLED));
  9641. }
  9642. //---------------------------------------------------------------------------
  9643. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9644. {
  9645. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9646. {
  9647. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9648. }
  9649. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9650. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9651. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))));
  9652. }
  9653. //---------------------------------------------------------------------------
  9654. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9655. {
  9656. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9657. UnicodeString Note =
  9658. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9659. PostNote(Note);
  9660. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9661. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9662. }
  9663. //---------------------------------------------------------------------------
  9664. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9665. {
  9666. WinConfiguration->FormatSizeBytes = Style;
  9667. }
  9668. //---------------------------------------------------------------------------
  9669. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9670. {
  9671. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9672. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9673. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9674. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))));
  9675. }
  9676. //---------------------------------------------------------------------------
  9677. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9678. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9679. {
  9680. if (Panel->Index == 0)
  9681. {
  9682. if (FOnNoteClick != NULL)
  9683. {
  9684. // prevent the user data from being freed by possible call
  9685. // to CancelNote or PostNote during call to OnNoteClick
  9686. std::unique_ptr<TObject> NoteData(FNoteData);
  9687. TNotifyEvent OnNoteClick = FOnNoteClick;
  9688. FNoteData = NULL;
  9689. // need to cancel the note as we are going to delete its user data
  9690. CancelNote(true);
  9691. OnNoteClick(NoteData.get());
  9692. }
  9693. }
  9694. if (HasAvailableTerminal() &&
  9695. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9696. {
  9697. FileSystemInfo();
  9698. }
  9699. }
  9700. //---------------------------------------------------------------------------
  9701. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9702. {
  9703. // workaround:
  9704. // 1) for unknown reason, disabling window, while minimized,
  9705. // prevents it from restoring, even if it was enabled again meanwhile
  9706. // 2) when disabling the main window, while another has focus
  9707. // minimize is no longer possible
  9708. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9709. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9710. // Shouldn't we use IsApplicationMinimized() here?
  9711. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9712. {
  9713. AppLog(L"Disabling window");
  9714. Enabled = false;
  9715. }
  9716. FLockLevel++;
  9717. }
  9718. //---------------------------------------------------------------------------
  9719. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9720. {
  9721. DebugAssert(FLockLevel > 0);
  9722. FLockLevel--;
  9723. if (FLockLevel == 0)
  9724. {
  9725. DebugAssert(FLockSuspendLevel == 0);
  9726. AppLog(L"Re-enabling window");
  9727. Enabled = true;
  9728. // VCL_COPY (TCustomForm.SetWindowFocus)
  9729. if (Active && (ActiveControl != NULL))
  9730. {
  9731. ::SetFocus(ActiveControl->Handle);
  9732. if (GetFocus() == ActiveControl->Handle)
  9733. {
  9734. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9735. }
  9736. }
  9737. }
  9738. }
  9739. //---------------------------------------------------------------------------
  9740. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9741. {
  9742. // We need to make sure that window is enabled when the last modal window closes
  9743. // otherwise focus is not restored correctly.
  9744. // So we re-enable the window when modal window opens and
  9745. // disable it back after is closes
  9746. if (FLockLevel > 0)
  9747. {
  9748. // while we have nesting counter, we know that we never be called
  9749. // recursivelly as Application->OnModalBegin is called only
  9750. // for the top-level modal window
  9751. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9752. {
  9753. // won't be disabled when conditions in LockWindow() were not satisfied
  9754. FDisabledOnLockSuspend = !Enabled;
  9755. // When minimized to tray (or actually when set to SW_HIDE),
  9756. // setting Enabled makes the window focusable even when there's
  9757. // modal window over it
  9758. if (!FTrayIcon->Visible)
  9759. {
  9760. Enabled = true;
  9761. }
  9762. }
  9763. FLockSuspendLevel++;
  9764. }
  9765. }
  9766. //---------------------------------------------------------------------------
  9767. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9768. {
  9769. if (FLockSuspendLevel > 0)
  9770. {
  9771. DebugAssert(FLockLevel > 0);
  9772. FLockSuspendLevel--;
  9773. // see comment in SuspendWindowLock
  9774. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9775. {
  9776. // Note that window can be enabled here, when we were minized to tray when
  9777. // was SuspendWindowLock() called.
  9778. // We should possibly do the same check as in LockWindow(),
  9779. // if it is ever possible that the consitions change between
  9780. // SuspendWindowLock() and ResumeWindowLock()
  9781. Enabled = !FDisabledOnLockSuspend;
  9782. }
  9783. }
  9784. }
  9785. //---------------------------------------------------------------------------
  9786. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9787. {
  9788. TTBXComboBoxItem * RemotePathComboBox =
  9789. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9790. if (!TextOnly)
  9791. {
  9792. TStrings * Items = RemotePathComboBox->Strings;
  9793. Items->BeginUpdate();
  9794. try
  9795. {
  9796. Items->Clear();
  9797. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9798. {
  9799. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9800. while (!IsUnixRootPath(APath))
  9801. {
  9802. int P = APath.LastDelimiter(L'/');
  9803. DebugAssert(P >= 0);
  9804. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9805. APath.SetLength(P - 1);
  9806. }
  9807. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9808. }
  9809. }
  9810. __finally
  9811. {
  9812. Items->EndUpdate();
  9813. }
  9814. }
  9815. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9816. // Setting ItemIndex to -1 does not reset its text
  9817. if (RemotePathComboBox->Strings->Count == 0)
  9818. {
  9819. RemotePathComboBox->Text = L"";
  9820. }
  9821. }
  9822. //---------------------------------------------------------------------------
  9823. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9824. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9825. {
  9826. if (AIndex < 0)
  9827. {
  9828. AIndex = Sender->ItemIndex;
  9829. }
  9830. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9831. }
  9832. //---------------------------------------------------------------------------
  9833. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9834. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9835. int & ImageIndex)
  9836. {
  9837. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9838. }
  9839. //---------------------------------------------------------------------------
  9840. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9841. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9842. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9843. {
  9844. if (!IsLocalBrowserMode())
  9845. {
  9846. ARect.Left += (10 * AIndex);
  9847. }
  9848. }
  9849. //---------------------------------------------------------------------------
  9850. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9851. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9852. {
  9853. AWidth += (10 * AIndex);
  9854. }
  9855. //---------------------------------------------------------------------------
  9856. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9857. {
  9858. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9859. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9860. int Index = RemotePathComboBox->ItemIndex;
  9861. while (Index < RemotePathComboBox->Strings->Count - 1)
  9862. {
  9863. APath = UnixExtractFileDir(APath);
  9864. Index++;
  9865. }
  9866. // VanDyke style paths
  9867. if (APath.IsEmpty())
  9868. {
  9869. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9870. APath = ROOTDIRECTORY;
  9871. }
  9872. if (RemoteDirView->Path != APath)
  9873. {
  9874. RemoteDirView->Path = APath;
  9875. }
  9876. }
  9877. //---------------------------------------------------------------------------
  9878. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9879. {
  9880. DoRemotePathComboBoxItemClick(Sender);
  9881. }
  9882. //---------------------------------------------------------------------------
  9883. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9884. {
  9885. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9886. DebugUsedParam(Sender);
  9887. UpdateRemotePathComboBox(true);
  9888. }
  9889. //---------------------------------------------------------------------------
  9890. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9891. {
  9892. DoRemotePathComboBoxCancel(Sender);
  9893. }
  9894. //---------------------------------------------------------------------------
  9895. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9896. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9897. {
  9898. ResetIncrementalSearch();
  9899. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9900. DebugAssert(DirView != NULL);
  9901. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9902. {
  9903. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9904. // OnEditing is called also from TCustomListView::CanEdit
  9905. if (Edit != NULL)
  9906. {
  9907. EditSelectBaseName(Edit);
  9908. }
  9909. }
  9910. }
  9911. //---------------------------------------------------------------------------
  9912. //---------------------------------------------------------------------------
  9913. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9914. {
  9915. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9916. Result->AutoDetectDnD = false;
  9917. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9918. Result->RenderDataOn = rdoEnterAndDropSync;
  9919. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9920. return Result;
  9921. }
  9922. //---------------------------------------------------------------------------
  9923. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9924. {
  9925. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9926. UseDarkMode(this);
  9927. }
  9928. //---------------------------------------------------------------------------
  9929. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9930. {
  9931. TForm::CreateWnd();
  9932. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9933. UpdateDarkMode();
  9934. if (FSessionsDragDropFilesEx == NULL)
  9935. {
  9936. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9937. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9938. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9939. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9940. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9941. }
  9942. if (FQueueDragDropFilesEx == NULL)
  9943. {
  9944. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9945. // No need to set OnDragOver as we do not have any restrictions
  9946. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9947. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9948. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9949. }
  9950. }
  9951. //---------------------------------------------------------------------------
  9952. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9953. {
  9954. TForm::DestroyWnd();
  9955. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9956. FQueueDragDropFilesEx->DragDropControl = NULL;
  9957. }
  9958. //---------------------------------------------------------------------------
  9959. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9960. {
  9961. SideEnter(FCurrentSide);
  9962. FEverShown = true;
  9963. }
  9964. //---------------------------------------------------------------------------
  9965. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9966. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9967. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9968. {
  9969. if (!NonVisualDataModule->Busy)
  9970. {
  9971. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9972. Configuration->Usage->Inc(L"FileFinds");
  9973. LockWindow(true);
  9974. NonVisualDataModule->StartBusy();
  9975. WinConfiguration->LockedInterface = true;
  9976. try
  9977. {
  9978. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9979. }
  9980. __finally
  9981. {
  9982. WinConfiguration->LockedInterface = false;
  9983. NonVisualDataModule->EndBusy();
  9984. UnlockWindow();
  9985. }
  9986. }
  9987. }
  9988. //---------------------------------------------------------------------------
  9989. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9990. {
  9991. if (!NonVisualDataModule->Busy)
  9992. {
  9993. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9994. SetFocus();
  9995. RemoteDirView->Path = UnixExtractFilePath(Path);
  9996. UnicodeString FileName = UnixExtractFileName(Path);
  9997. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9998. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9999. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  10000. if (Item == NULL)
  10001. {
  10002. ReloadDirectory(osRemote);
  10003. Item = RemoteDirView->FindFileItem(FileName);
  10004. }
  10005. if (Item != NULL)
  10006. {
  10007. RemoteDirView->ItemFocused = Item;
  10008. RemoteDirView->ItemFocused->MakeVisible(false);
  10009. RemoteDirView->SetFocus();
  10010. }
  10011. }
  10012. }
  10013. //---------------------------------------------------------------------------
  10014. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  10015. {
  10016. bool Result = !NonVisualDataModule->Busy;
  10017. if (Result)
  10018. {
  10019. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  10020. }
  10021. return Result;
  10022. }
  10023. //---------------------------------------------------------------------------
  10024. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  10025. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10026. {
  10027. if (CanOperateOnFoundFiles(ATerminal))
  10028. {
  10029. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished, OnFileOperationFinished);
  10030. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  10031. }
  10032. }
  10033. //---------------------------------------------------------------------------
  10034. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  10035. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10036. {
  10037. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  10038. }
  10039. //---------------------------------------------------------------------------
  10040. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  10041. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10042. {
  10043. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  10044. }
  10045. //---------------------------------------------------------------------------
  10046. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  10047. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  10048. {
  10049. if (CanOperateOnFoundFiles(ATerminal))
  10050. {
  10051. for (int Index = 0; Index < FileList->Count; Index++)
  10052. {
  10053. UnicodeString FileName = FileList->Strings[Index];
  10054. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  10055. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  10056. OnFileOperationFinished(osRemote, FileName, true, true);
  10057. }
  10058. }
  10059. }
  10060. //---------------------------------------------------------------------------
  10061. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  10062. {
  10063. FFileFindTerminal = Terminal;
  10064. ShowFileFindDialog(
  10065. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  10066. DoDownloadFoundFiles, DoEditFoundFiles);
  10067. }
  10068. //---------------------------------------------------------------------------
  10069. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  10070. {
  10071. FTaskbarList = TaskbarList;
  10072. }
  10073. //---------------------------------------------------------------------------
  10074. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  10075. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  10076. {
  10077. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10078. if (Index >= 0)
  10079. {
  10080. if (Button == mbLeft)
  10081. {
  10082. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  10083. // If switching tab (switching session) takes long enough for user
  10084. // to actually release the button, "mouse down" is still raised,
  10085. // but we do not get "mouse up" event, so dragging is not cancelled,
  10086. // prevent that by not beginning dragging in the first place.
  10087. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  10088. if (IsKeyPressed(Key))
  10089. {
  10090. // when user clicks the "+", we get mouse down only after the session
  10091. // is closed, when new session tab is already on X:Y, so dragging
  10092. // starts, prevent that
  10093. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  10094. {
  10095. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10096. if (Terminal != NULL)
  10097. {
  10098. SessionsPageControl->BeginDrag(false);
  10099. }
  10100. }
  10101. }
  10102. }
  10103. else if (Button == mbMiddle)
  10104. {
  10105. // ignore middle-click for "New session tab" and the last local-local tab
  10106. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10107. if ((Session != NULL) && CanCloseSession(Session))
  10108. {
  10109. CloseSessionTab(Index);
  10110. }
  10111. }
  10112. }
  10113. }
  10114. //---------------------------------------------------------------------------
  10115. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10116. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10117. {
  10118. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10119. // do not allow dropping on the "+" tab
  10120. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10121. if ((TargetTerminal != NULL) &&
  10122. (SessionsPageControl->ActivePage->PageIndex != Index))
  10123. {
  10124. Configuration->Usage->Inc(L"SessionTabMoves");
  10125. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10126. // but we want to actually prevent that to avoid flicker
  10127. SessionsPageControl->ActivePage->PageIndex = Index;
  10128. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10129. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10130. }
  10131. }
  10132. //---------------------------------------------------------------------------
  10133. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10134. TObject * Sender, TObject * Source, int X, int Y,
  10135. TDragState /*State*/, bool & Accept)
  10136. {
  10137. Accept = (Sender == Source);
  10138. if (Accept)
  10139. {
  10140. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10141. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10142. // do not allow dragging to the "+" tab
  10143. Accept = (Terminal != NULL);
  10144. }
  10145. }
  10146. //---------------------------------------------------------------------------
  10147. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10148. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10149. {
  10150. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10151. if (Index < 0)
  10152. {
  10153. Effect = DROPEFFECT_NONE;
  10154. }
  10155. else
  10156. {
  10157. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10158. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10159. if (!IsAvailableTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10160. {
  10161. Effect = DROPEFFECT_NONE;
  10162. }
  10163. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10164. {
  10165. Effect = DROPEFFECT_COPY;
  10166. }
  10167. }
  10168. }
  10169. //---------------------------------------------------------------------------
  10170. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10171. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10172. {
  10173. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10174. // do not allow dropping on local-local, disconnected and the "+" tab
  10175. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10176. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10177. if (DebugAlwaysTrue(IsAvailableTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10178. {
  10179. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10180. if (!IsFileControl(DropSourceControl, osRemote))
  10181. {
  10182. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10183. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10184. // Why don't we use Terminal->CurrentDirectory directly?
  10185. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10186. // do not force queue, drag drop
  10187. false, true);
  10188. }
  10189. }
  10190. }
  10191. //---------------------------------------------------------------------------
  10192. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10193. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10194. {
  10195. // Downloads are handled in RemoteFileControlDDEnd
  10196. if (!IsFileControl(DropSourceControl, osRemote))
  10197. {
  10198. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10199. Terminal->CurrentDirectory,
  10200. // force queue, drag drop
  10201. true, true);
  10202. }
  10203. }
  10204. //---------------------------------------------------------------------------
  10205. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10206. {
  10207. FShowing = false;
  10208. // Do not save empty workspace
  10209. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10210. {
  10211. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10212. UnicodeString Name = WorkspaceName();
  10213. DoSaveWorkspace(
  10214. Name, DataList.get(),
  10215. !Configuration->DisablePasswordStoring &&
  10216. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10217. WinConfiguration->LastStoredSession = Name;
  10218. }
  10219. AppLog(L"Closing main window");
  10220. }
  10221. //---------------------------------------------------------------------------
  10222. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10223. {
  10224. TManagedTerminal * ManagedTerminal =
  10225. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10226. if (ManagedTerminal != NULL)
  10227. {
  10228. ManagedTerminal->DirectoryLoaded = Now();
  10229. }
  10230. }
  10231. //---------------------------------------------------------------------------
  10232. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10233. TListItem * /*Item*/, bool /*Selected*/)
  10234. {
  10235. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10236. switch (DirView->LastSelectMethod)
  10237. {
  10238. case smKeyboard:
  10239. Configuration->Usage->Inc(L"KeyboardSelections");
  10240. break;
  10241. case smMouse:
  10242. Configuration->Usage->Inc(L"MouseSelections");
  10243. break;
  10244. }
  10245. }
  10246. //---------------------------------------------------------------------------
  10247. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10248. {
  10249. if (Color != 0)
  10250. {
  10251. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10252. }
  10253. else
  10254. {
  10255. return FSessionTabImageIndex;
  10256. }
  10257. }
  10258. //---------------------------------------------------------------------------
  10259. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10260. {
  10261. TPngImageCollectionItem * Item =
  10262. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10263. FSessionColors->AddPng(Item->PngImage);
  10264. return FSessionColors->Count - 1;
  10265. }
  10266. //---------------------------------------------------------------------------
  10267. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10268. {
  10269. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10270. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10271. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10272. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10273. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10274. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10275. }
  10276. //---------------------------------------------------------------------------
  10277. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10278. {
  10279. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10280. }
  10281. //---------------------------------------------------------------------------
  10282. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10283. {
  10284. switch (Side)
  10285. {
  10286. case osLocal:
  10287. return FNewLocalTabTabImageIndex;
  10288. case osRemote:
  10289. case osCurrent:
  10290. return FNewRemoteTabTabImageIndex;
  10291. default:
  10292. DebugFail();
  10293. return -1;
  10294. }
  10295. }
  10296. //---------------------------------------------------------------------------
  10297. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10298. {
  10299. for (int Index = 0; Index < Control->ControlCount; Index++)
  10300. {
  10301. TControl * AControl = Control->Controls[Index];
  10302. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10303. if (WinControl != NULL)
  10304. {
  10305. CollectItemsWithTextDisplayMode(WinControl);
  10306. }
  10307. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10308. if (Toolbar != NULL)
  10309. {
  10310. // we care for top-level items only
  10311. TTBCustomItem * Items = Toolbar->Items;
  10312. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10313. {
  10314. TTBCustomItem * Item = Items->Items[ItemIndex];
  10315. if (((Item->DisplayMode == nbdmImageAndText) ||
  10316. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10317. EligibleForImageDisplayMode(Item))
  10318. {
  10319. FItemsWithTextDisplayMode.insert(Item);
  10320. }
  10321. }
  10322. }
  10323. }
  10324. }
  10325. //---------------------------------------------------------------------------
  10326. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10327. {
  10328. return true;
  10329. }
  10330. //---------------------------------------------------------------------------
  10331. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10332. {
  10333. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10334. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10335. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10336. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10337. bool Result = true;
  10338. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10339. {
  10340. TTBCustomItem * Item = *i;
  10341. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10342. if (Label != NULL)
  10343. {
  10344. // optimization
  10345. if (Label->Visible == SelectiveToolbarText)
  10346. {
  10347. Result = false;
  10348. }
  10349. else
  10350. {
  10351. Label->Visible = SelectiveToolbarText;
  10352. }
  10353. }
  10354. else
  10355. {
  10356. // optimization
  10357. if (Item->DisplayMode == DisplayMode)
  10358. {
  10359. Result = false;
  10360. }
  10361. else
  10362. {
  10363. Item->DisplayMode = DisplayMode;
  10364. }
  10365. }
  10366. ++i;
  10367. }
  10368. UpdateNewTabTab();
  10369. return Result;
  10370. }
  10371. //---------------------------------------------------------------------------
  10372. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10373. {
  10374. DebugFail();
  10375. }
  10376. //---------------------------------------------------------------------------
  10377. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10378. {
  10379. // Among other, a lock level is non zero, while directory is being loaded,
  10380. // even when it happens as a result of dirview navigation,
  10381. // i.e. when TNonVisualDataModule is NOT FBusy.
  10382. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10383. // Among other this prevents a panel auto update to occur while
  10384. // directory is changing.
  10385. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10386. }
  10387. //---------------------------------------------------------------------------
  10388. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10389. {
  10390. // While the window is disabled, we still seem to process menu shortcuts at least,
  10391. // so stop it at least here.
  10392. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10393. bool Result;
  10394. if (Allowed == aaUpdate)
  10395. {
  10396. Result = true;
  10397. }
  10398. else
  10399. {
  10400. Result = !NonVisualDataModule->Busy;
  10401. if (Result && (Allowed == aaShortCut))
  10402. {
  10403. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10404. Action->Update();
  10405. Result = Action->Enabled;
  10406. }
  10407. }
  10408. return Result;
  10409. }
  10410. //---------------------------------------------------------------------------
  10411. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10412. {
  10413. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10414. }
  10415. //---------------------------------------------------------------------------
  10416. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10417. {
  10418. // This is somewhat redundant to LockWindow() call from
  10419. // TTerminalManager::TerminalReadDirectoryProgress.
  10420. // But disabling window is known not to block keyboard shorcuts
  10421. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10422. if (Busy > 0)
  10423. {
  10424. if (NonVisualDataModule->Busy)
  10425. {
  10426. State = false;
  10427. }
  10428. else
  10429. {
  10430. NonVisualDataModule->StartBusy();
  10431. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10432. LockWindow();
  10433. }
  10434. }
  10435. else if (Busy < 0)
  10436. {
  10437. UnlockWindow();
  10438. NonVisualDataModule->EndBusy();
  10439. }
  10440. else
  10441. {
  10442. State = NonVisualDataModule->Busy;
  10443. }
  10444. }
  10445. //---------------------------------------------------------------------------
  10446. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10447. {
  10448. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10449. if (Index >= 0)
  10450. {
  10451. TPopupMenu * PopupMenu = NULL;
  10452. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10453. if (Session != NULL)
  10454. {
  10455. SessionsPageControl->ActivePageIndex = Index;
  10456. if (DebugAlwaysTrue(SessionTabSwitched()))
  10457. {
  10458. // copied from TControl.WMContextMenu
  10459. SendCancelMode(SessionsPageControl);
  10460. // explicit popup instead of using PopupMenu property
  10461. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10462. // while connecting yet not-connected session and hence
  10463. // allowing an access to commands over not-completely connected session
  10464. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10465. }
  10466. }
  10467. else
  10468. {
  10469. if (SupportsLocalBrowser())
  10470. {
  10471. PopupMenu = NonVisualDataModule->NewTabPopup;
  10472. }
  10473. }
  10474. if (PopupMenu != NULL)
  10475. {
  10476. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10477. PopupMenu->PopupComponent = SessionsPageControl;
  10478. PopupMenu->Popup(Point.x, Point.y);
  10479. }
  10480. }
  10481. Handled = true;
  10482. }
  10483. //---------------------------------------------------------------------------
  10484. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10485. {
  10486. return HasAvailableTerminal() && Terminal->IsCapable[fcChangePassword];
  10487. }
  10488. //---------------------------------------------------------------------------
  10489. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10490. {
  10491. Configuration->Usage->Inc(L"PasswordChanges");
  10492. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10493. ChangePasswordData->DisableAuthentationsExceptPassword();
  10494. ChangePasswordData->ChangePassword = true;
  10495. std::unique_ptr<TTerminal> ChangePasswordSession(
  10496. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10497. ChangePasswordSession->AutoReadDirectory = false;
  10498. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10499. {
  10500. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10501. }
  10502. else
  10503. {
  10504. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10505. }
  10506. }
  10507. //---------------------------------------------------------------------------
  10508. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10509. {
  10510. // No nice way to assert SSH2
  10511. return HasAvailableTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10512. }
  10513. //---------------------------------------------------------------------------
  10514. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10515. {
  10516. TOperationVisualizer OperationVisualizer;
  10517. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10518. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10519. }
  10520. //---------------------------------------------------------------------------
  10521. void __fastcall TCustomScpExplorerForm::FormAfterMonitorDpiChanged(TObject *, int OldDPI, int NewDPI)
  10522. {
  10523. DebugUsedParam(OldDPI);
  10524. DebugAssert(NewDPI == GetControlPixelsPerInch(this));
  10525. GlyphsModule->PixelsPerInch = NewDPI;
  10526. // Can be called too early when primary monitor has non-system dpi
  10527. if (FSessionColors != NULL)
  10528. {
  10529. RegenerateSessionColorsImageList();
  10530. }
  10531. UpdateTabsSize();
  10532. UpdateSessionsPageControlHeight();
  10533. QueueFileListColumnAutoSize();
  10534. }
  10535. //---------------------------------------------------------------------------
  10536. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10537. {
  10538. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10539. }
  10540. //---------------------------------------------------------------------
  10541. class TPublicControl : public TControl
  10542. {
  10543. friend class TCustomScpExplorerForm;
  10544. };
  10545. //---------------------------------------------------------------------------
  10546. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10547. {
  10548. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10549. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10550. }
  10551. //---------------------------------------------------------------------------
  10552. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10553. {
  10554. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10555. OpenBookmark(Side, Bookmark);
  10556. }
  10557. //---------------------------------------------------------------------------
  10558. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10559. {
  10560. DoBookmarkClick(osLocal, Sender);
  10561. }
  10562. //---------------------------------------------------------------------------
  10563. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10564. {
  10565. DoBookmarkClick(osRemote, Sender);
  10566. }
  10567. //---------------------------------------------------------------------------
  10568. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10569. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10570. {
  10571. if (BookmarkList != NULL)
  10572. {
  10573. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10574. if (IsLocalBrowserMode())
  10575. {
  10576. Side = osLocal;
  10577. }
  10578. if (!WinConfiguration->UseLocationProfiles)
  10579. {
  10580. std::unique_ptr<TStringList> Directories(new TStringList());
  10581. Directories->CaseSensitive = (Side == osRemote);
  10582. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10583. {
  10584. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10585. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10586. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10587. {
  10588. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10589. Item->Caption = EscapeHotkey(Directory);
  10590. Item->ShortCut = Bookmark->ShortCut;
  10591. Item->OnClick = OnBookmarkClick;
  10592. Item->Tag = reinterpret_cast<int>(Bookmark);
  10593. Directories->Add(Directory);
  10594. Menu->Add(Item.release());
  10595. }
  10596. }
  10597. }
  10598. else
  10599. {
  10600. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10601. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10602. {
  10603. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10604. if (!Bookmark->Node.IsEmpty())
  10605. {
  10606. Folders->Add(Bookmark->Node);
  10607. }
  10608. }
  10609. for (int Index = 0; Index < Folders->Count; Index++)
  10610. {
  10611. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10612. Item->Caption = Folders->Strings[Index];
  10613. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10614. Folders->Objects[Index] = Item.get();
  10615. Menu->Add(Item.release());
  10616. }
  10617. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10618. {
  10619. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10620. TTBCustomItem * Parent;
  10621. if (!Bookmark->Node.IsEmpty())
  10622. {
  10623. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10624. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10625. }
  10626. else
  10627. {
  10628. Parent = Menu;
  10629. }
  10630. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10631. Item->Caption = Bookmark->Name;
  10632. Item->ShortCut = Bookmark->ShortCut;
  10633. Item->OnClick = OnBookmarkClick;
  10634. Item->Tag = reinterpret_cast<int>(Bookmark);
  10635. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10636. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10637. {
  10638. // No hint for location profiles that are actually mere "bookmarks"
  10639. }
  10640. else
  10641. {
  10642. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10643. UnicodeString LongHint;
  10644. if (!Bookmark->Local.IsEmpty())
  10645. {
  10646. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10647. }
  10648. if (!Bookmark->Remote.IsEmpty())
  10649. {
  10650. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10651. }
  10652. AddToList(Hint, LongHint, L"|");
  10653. Item->Hint = Hint;
  10654. }
  10655. Parent->Add(Item.release());
  10656. }
  10657. }
  10658. AddMenuSeparator(Menu);
  10659. }
  10660. }
  10661. //---------------------------------------------------------------------------
  10662. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10663. {
  10664. Menu->Clear();
  10665. std::unique_ptr<TTBCustomItem> Item;
  10666. Item.reset(new TTBXItem(Owner));
  10667. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10668. Item->Options = Item->Options << tboDefault;
  10669. Menu->Add(Item.release());
  10670. AddMenuSeparator(Menu);
  10671. if (Terminal != NULL)
  10672. {
  10673. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10674. }
  10675. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10676. Item.reset(new TTBXItem(Owner));
  10677. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10678. Menu->Add(Item.release());
  10679. }
  10680. //---------------------------------------------------------------------------
  10681. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10682. {
  10683. bool Result = true;
  10684. bool Remote = !IsSideLocalBrowser(Side);
  10685. try
  10686. {
  10687. UnicodeString APath = Path;
  10688. if (Remote)
  10689. {
  10690. Terminal->ExceptionOnFail = true;
  10691. }
  10692. else
  10693. {
  10694. APath = ExpandEnvironmentVariables(Path);
  10695. }
  10696. try
  10697. {
  10698. DirView(Side)->Path = APath;
  10699. }
  10700. __finally
  10701. {
  10702. if (Remote)
  10703. {
  10704. Terminal->ExceptionOnFail = false;
  10705. }
  10706. }
  10707. }
  10708. catch (Exception & E)
  10709. {
  10710. if (!Remote || Terminal->Active)
  10711. {
  10712. ShowExtendedExceptionEx(Terminal, &E);
  10713. Result = false;
  10714. }
  10715. else
  10716. {
  10717. throw;
  10718. }
  10719. }
  10720. return Result;
  10721. }
  10722. //---------------------------------------------------------------------------
  10723. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10724. {
  10725. // Make sure there some feedback even when loading tiny local folders
  10726. TInstantOperationVisualizer Visualizer;
  10727. DirView(Side)->ReloadDirectory();
  10728. }
  10729. //---------------------------------------------------------------------------
  10730. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10731. {
  10732. if (Index == SessionsPageControl->TabIndex)
  10733. {
  10734. CloseTab();
  10735. }
  10736. else
  10737. {
  10738. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10739. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10740. TTerminalManager * Manager = TTerminalManager::Instance();
  10741. if (!Terminal->Active)
  10742. {
  10743. Manager->FreeTerminal(Terminal);
  10744. }
  10745. else
  10746. {
  10747. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10748. if (CanCloseQueue(Queue))
  10749. {
  10750. Manager->FreeTerminal(Terminal);
  10751. }
  10752. }
  10753. }
  10754. }
  10755. //---------------------------------------------------------------------------
  10756. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10757. {
  10758. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10759. if (Session == NULL)
  10760. {
  10761. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10762. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10763. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10764. //P = SessionsPageControl->ClientToScreen(P);
  10765. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10766. }
  10767. else
  10768. {
  10769. CloseSessionTab(Index);
  10770. }
  10771. }
  10772. //---------------------------------------------------------------------------
  10773. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10774. {
  10775. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10776. {
  10777. TInstantOperationVisualizer Visualizer;
  10778. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10779. // before we create a new data object
  10780. ClipboardClear();
  10781. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10782. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10783. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10784. // Intermediate variable to WORKAROUND a crash in compiler
  10785. TObjectList * ClipboardFakeMonitors =
  10786. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10787. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10788. if (FClipboardDragDropFilesEx.get() == NULL)
  10789. {
  10790. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10791. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10792. }
  10793. FClipboardDragDropFilesEx->FileList->Clear();
  10794. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10795. FClipboardDragDropFilesEx->CopyToClipboard();
  10796. FClipboardTerminal = Terminal;
  10797. // Need full paths, as cwd can be different once files are pasted
  10798. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10799. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10800. {
  10801. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10802. }
  10803. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10804. }
  10805. }
  10806. //---------------------------------------------------------------------------
  10807. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10808. {
  10809. if (OpenClipboard(0))
  10810. {
  10811. AppLog(L"Clearing clipboard");
  10812. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10813. CloseClipboard();
  10814. }
  10815. }
  10816. //---------------------------------------------------------------------------
  10817. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10818. {
  10819. return !FClipboardFakeDirectory.IsEmpty();
  10820. }
  10821. //---------------------------------------------------------------------------
  10822. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10823. {
  10824. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10825. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10826. FClipboardFakeDirectory = UnicodeString();
  10827. FClipboardTerminal = NULL;
  10828. if (FDownloadingFromClipboard)
  10829. {
  10830. // We are called by the monitor, so attempt to release it would deadlock
  10831. FClipboardFakeMonitorsPendingReset = true;
  10832. }
  10833. else
  10834. {
  10835. FClipboardFakeMonitors.reset(NULL);
  10836. }
  10837. }
  10838. //---------------------------------------------------------------------------
  10839. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10840. {
  10841. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10842. {
  10843. ClipboardStop();
  10844. }
  10845. }
  10846. //---------------------------------------------------------------------------
  10847. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10848. {
  10849. TTerminalManager * Manager = TTerminalManager::Instance();
  10850. Manager->ActiveSession = FClipboardTerminal;
  10851. TTransferOperationParam Params;
  10852. Params.TargetDirectory = TargetDirectory;
  10853. Params.DragDrop = DragDrop;
  10854. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10855. }
  10856. //---------------------------------------------------------------------------
  10857. void TCustomScpExplorerForm::PasteFilesCleanupRetry(const UnicodeString & Target)
  10858. {
  10859. bool Removed = RemoveDir(ApiPath(Target));
  10860. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10861. }
  10862. //---------------------------------------------------------------------------
  10863. void TCustomScpExplorerForm::PasteFiles()
  10864. {
  10865. // Guard against possible race conditions
  10866. if (!FClipboardPasteTarget.IsEmpty())
  10867. {
  10868. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10869. UnicodeString Target = FClipboardPasteTarget;
  10870. FClipboardPasteTarget = EmptyStr;
  10871. // Can fail as it can be e.g. locked by AV, so we retry that later
  10872. bool Removed = RemoveDir(ApiPath(Target));
  10873. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10874. try
  10875. {
  10876. if (NonVisualDataModule->Busy)
  10877. {
  10878. AppLog(L"Is busy, cannot paste");
  10879. }
  10880. else
  10881. {
  10882. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10883. FClipboardFakeMonitorsPendingReset = false;
  10884. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10885. TAutoFlag Flag(FDownloadingFromClipboard);
  10886. AppLog(L"Downloading to paste target...");
  10887. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10888. AppLog(L"Downloaded to paste target...");
  10889. }
  10890. }
  10891. __finally
  10892. {
  10893. if (!Removed)
  10894. {
  10895. PasteFilesCleanupRetry(Target);
  10896. }
  10897. }
  10898. }
  10899. }
  10900. //---------------------------------------------------------------------------
  10901. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10902. {
  10903. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10904. // (as it pumps a Windows message queue while being shutted down)
  10905. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10906. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10907. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10908. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10909. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10910. {
  10911. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10912. FClipboardPasteTarget = FileName;
  10913. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10914. // Postponing removing (or actually whole pasting operation) seems to help.
  10915. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10916. }
  10917. }
  10918. //---------------------------------------------------------------------------
  10919. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10920. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10921. {
  10922. TFileMasks::TParams MaskParams;
  10923. MaskParams.Size = Size;
  10924. MaskParams.Modification = Modification;
  10925. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10926. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10927. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10928. if (!Local && Directory)
  10929. {
  10930. FileName = UnixExcludeTrailingBackslash(FileName);
  10931. }
  10932. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10933. {
  10934. bool ImplicitMatch;
  10935. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10936. !ImplicitMatch)
  10937. {
  10938. Color = Iter->Color;
  10939. break;
  10940. }
  10941. }
  10942. }
  10943. //---------------------------------------------------------------------------
  10944. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10945. {
  10946. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10947. if (!DirView->IsEditing())
  10948. {
  10949. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10950. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10951. // while searching
  10952. if (Key == VK_BACK)
  10953. {
  10954. if (FIncrementalSearchState.Searching)
  10955. {
  10956. if (FIncrementalSearchState.Text.Length() <= 1)
  10957. {
  10958. ResetIncrementalSearch();
  10959. }
  10960. else
  10961. {
  10962. UnicodeString NewText = LeftStr(FIncrementalSearchState.Text, FIncrementalSearchState.Text.Length() - 1);
  10963. IncrementalSearch(NewText, false, false);
  10964. }
  10965. Key = 0;
  10966. }
  10967. }
  10968. }
  10969. }
  10970. //---------------------------------------------------------------------------
  10971. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10972. {
  10973. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10974. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10975. {
  10976. // Filter control sequences.
  10977. // When not searching yet, prefer use of the space for toggling file selection
  10978. // (so we cannot incrementally search for a string starting with a space).
  10979. if ((Key > VK_SPACE) ||
  10980. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && FIncrementalSearchState.Searching))
  10981. {
  10982. IncrementalSearch(FIncrementalSearchState.Text + Key, false, false);
  10983. Key = 0;
  10984. }
  10985. }
  10986. }
  10987. //---------------------------------------------------------------------------
  10988. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10989. {
  10990. if (FIncrementalSearchState.Searching)
  10991. {
  10992. FIncrementalSearchState.Reset();
  10993. DirView(osCurrent)->UpdateStatusBar();
  10994. }
  10995. }
  10996. //---------------------------------------------------------------------------
  10997. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10998. {
  10999. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  11000. if (Item == NULL)
  11001. {
  11002. MessageBeep(MB_ICONHAND);
  11003. }
  11004. else
  11005. {
  11006. TCustomDirView * ADirView = DirView(osCurrent);
  11007. {
  11008. TAutoNestingCounter Guard(FIncrementalSearching);
  11009. ADirView->FocusItem(Item);
  11010. if (ADirView->NortonLike == nlOff)
  11011. {
  11012. if ((ADirView->Selected != Item) ||
  11013. (ADirView->SelCount > 1))
  11014. {
  11015. ADirView->ClearSelection();
  11016. ADirView->Selected = Item;
  11017. }
  11018. }
  11019. }
  11020. FIncrementalSearchState.Searching = true;
  11021. FIncrementalSearchState.Text = Text;
  11022. Item->MakeVisible(false);
  11023. TListItem * NextItem = SearchFile(Text, true, Reverse);
  11024. FIncrementalSearchState.HaveNext = (NextItem != NULL) && (NextItem != Item);
  11025. ADirView->UpdateStatusBar();
  11026. }
  11027. }
  11028. //---------------------------------------------------------------------------
  11029. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  11030. {
  11031. int Index = Item->Index;
  11032. if (!Reverse)
  11033. {
  11034. Index++;
  11035. if (Index >= Item->Owner->Count)
  11036. {
  11037. Index = 0;
  11038. }
  11039. }
  11040. else
  11041. {
  11042. Index--;
  11043. if (Index < 0)
  11044. {
  11045. Index = Item->Owner->Count - 1;
  11046. }
  11047. }
  11048. return Item->Owner->Item[Index];
  11049. }
  11050. //---------------------------------------------------------------------------
  11051. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  11052. {
  11053. TCustomDirView * ADirView = DirView(osCurrent);
  11054. if (ADirView->Items->Count == 0)
  11055. {
  11056. return NULL;
  11057. }
  11058. else
  11059. {
  11060. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  11061. TListItem * Item = CurrentItem;
  11062. if (SkipCurrent)
  11063. {
  11064. Item = DebugNotNull(GetNextFile(Item, Reverse));
  11065. }
  11066. while (true)
  11067. {
  11068. bool Matches = false;
  11069. switch (WinConfiguration->PanelSearch)
  11070. {
  11071. case isNameStartOnly:
  11072. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  11073. break;
  11074. case isName:
  11075. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  11076. break;
  11077. case isAll:
  11078. int ColCount = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Count : 1;
  11079. int Index = 0;
  11080. while ((Index < ColCount) && !Matches)
  11081. {
  11082. bool Visible = (ADirView->DirViewStyle == dvsReport) ? ADirView->ColProperties->Visible[Index] : true;
  11083. if (Visible)
  11084. {
  11085. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  11086. }
  11087. Index++;
  11088. }
  11089. break;
  11090. }
  11091. if (Matches)
  11092. {
  11093. return Item;
  11094. }
  11095. Item = GetNextFile(Item, Reverse);
  11096. if (Item == CurrentItem)
  11097. {
  11098. return NULL;
  11099. }
  11100. }
  11101. }
  11102. }
  11103. //---------------------------------------------------------------------------
  11104. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  11105. {
  11106. ResetIncrementalSearch();
  11107. }
  11108. //---------------------------------------------------------------------------
  11109. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  11110. {
  11111. if (Message.CharCode == VK_TAB)
  11112. {
  11113. if (!FIncrementalSearchState.Text.IsEmpty())
  11114. {
  11115. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11116. bool Reverse = Shift.Contains(ssShift);
  11117. IncrementalSearch(FIncrementalSearchState.Text, true, Reverse);
  11118. Message.Result = 1;
  11119. return;
  11120. }
  11121. }
  11122. else if (Message.CharCode == VK_ESCAPE)
  11123. {
  11124. if (FIncrementalSearchState.Searching)
  11125. {
  11126. ResetIncrementalSearch();
  11127. Message.Result = 1;
  11128. return;
  11129. }
  11130. }
  11131. TForm::Dispatch(&Message);
  11132. }
  11133. //---------------------------------------------------------------------------
  11134. void __fastcall TCustomScpExplorerForm::Deactivate()
  11135. {
  11136. TForm::Deactivate();
  11137. // E.g. when switching to an internal editor window
  11138. ResetIncrementalSearch();
  11139. }
  11140. //---------------------------------------------------------------------------
  11141. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11142. {
  11143. // When switching to another application
  11144. ResetIncrementalSearch();
  11145. }
  11146. //---------------------------------------------------------------------------
  11147. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11148. {
  11149. ResetIncrementalSearch();
  11150. }
  11151. //---------------------------------------------------------------------------
  11152. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11153. {
  11154. if (FIncrementalSearching <= 0)
  11155. {
  11156. ResetIncrementalSearch();
  11157. }
  11158. }
  11159. //---------------------------------------------------------------------------
  11160. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11161. {
  11162. CountClicksForWindowPrint(this);
  11163. }
  11164. //---------------------------------------------------------------------------
  11165. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11166. {
  11167. CenterReconnectToolbar();
  11168. }
  11169. //---------------------------------------------------------------------------
  11170. void TCustomScpExplorerForm::DoExploreFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11171. {
  11172. if (!FileName.IsEmpty())
  11173. {
  11174. DirView->FocusByName(FileName);
  11175. if (DirView->ItemFocused != NULL)
  11176. {
  11177. DirView->ItemFocused->Selected = true;
  11178. }
  11179. }
  11180. }
  11181. //---------------------------------------------------------------------------
  11182. void __fastcall TCustomScpExplorerForm::ExploreFile(const UnicodeString & FileName)
  11183. {
  11184. DoExploreFile(RemoteDirView, FileName);
  11185. }
  11186. //---------------------------------------------------------------------------
  11187. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11188. {
  11189. if (!FQueueStatusUpdating)
  11190. {
  11191. bool Refresh;
  11192. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11193. {
  11194. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11195. }
  11196. else
  11197. {
  11198. Refresh = (FQueueFileList->GetCount() > 0);
  11199. if (Refresh)
  11200. {
  11201. FQueueFileList->Clear();
  11202. }
  11203. }
  11204. int Count = FQueueFileList->GetCount();
  11205. if (QueueFileList->Items->Count != Count)
  11206. {
  11207. DebugAssert(Refresh);
  11208. QueueFileList->Items->Count = Count;
  11209. }
  11210. if (Refresh)
  11211. {
  11212. QueueFileList->Invalidate();
  11213. }
  11214. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11215. }
  11216. }
  11217. //---------------------------------------------------------------------------
  11218. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11219. {
  11220. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11221. }
  11222. //---------------------------------------------------------------------------
  11223. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11224. {
  11225. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11226. // See TSynchronizeChecklistDialog::UpdateTimer
  11227. if (QueueFileList->Items->Count > 0)
  11228. {
  11229. QueueFileList->Items->Item[0]->MakeVisible(false);
  11230. }
  11231. UpdateQueueFileList();
  11232. }
  11233. //---------------------------------------------------------------------------
  11234. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11235. {
  11236. Active = QueueView3->Focused() || QueueFileList->Focused();
  11237. }
  11238. //---------------------------------------------------------------------------
  11239. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11240. {
  11241. QueueLabelUpdateStatus();
  11242. }
  11243. //---------------------------------------------------------------------------
  11244. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11245. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11246. {
  11247. int State = FQueueFileList->GetState(Item->Index);
  11248. if (State == qfsProcessed)
  11249. {
  11250. Sender->Canvas->Font->Color = clGrayText;
  11251. }
  11252. }
  11253. //---------------------------------------------------------------------------
  11254. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11255. {
  11256. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11257. QueueFileList->Column[0]->Width =
  11258. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11259. }
  11260. //---------------------------------------------------------------------------
  11261. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11262. {
  11263. QueueFileListColumnAutoSize();
  11264. }
  11265. //---------------------------------------------------------------------------
  11266. void __fastcall TCustomScpExplorerForm::CloseApp()
  11267. {
  11268. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11269. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11270. // So we clear the flag here.
  11271. DebugAssert(NonVisualDataModule->Busy);
  11272. NonVisualDataModule->EndBusy();
  11273. try
  11274. {
  11275. Close();
  11276. }
  11277. __finally
  11278. {
  11279. NonVisualDataModule->StartBusy();
  11280. }
  11281. }
  11282. //---------------------------------------------------------------------------
  11283. bool TCustomScpExplorerForm::IsAvailableTerminal(TTerminal * Terminal)
  11284. {
  11285. return TTerminalManager::Instance()->IsAvailableTerminal(Terminal);
  11286. }
  11287. //---------------------------------------------------------------------------
  11288. bool TCustomScpExplorerForm::HasAvailableTerminal()
  11289. {
  11290. return IsAvailableTerminal(Terminal);
  11291. }
  11292. //---------------------------------------------------------------------------
  11293. void TCustomScpExplorerForm::LocalLocalCopy(
  11294. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11295. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11296. {
  11297. DebugFail();
  11298. }
  11299. //---------------------------------------------------------------------------
  11300. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11301. {
  11302. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11303. }
  11304. //---------------------------------------------------------------------------
  11305. void TCustomScpExplorerForm::UpdateTabsSize()
  11306. {
  11307. // 1) Changing tab list triggers the OnResize.
  11308. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11309. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11310. {
  11311. // UpdateTabsCaptionTruncation should be enough
  11312. SessionListChanged(true);
  11313. }
  11314. }
  11315. //---------------------------------------------------------------------------
  11316. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11317. {
  11318. UpdateTabsSize();
  11319. }
  11320. //---------------------------------------------------------------------------
  11321. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11322. {
  11323. if (ASession == ManagedSession)
  11324. {
  11325. UpdateSession(ASession);
  11326. }
  11327. TSessionData * Data = ASession->StateData;
  11328. UnicodeString Result;
  11329. if (Side == osLocal)
  11330. {
  11331. Result = Data->LocalDirectory;
  11332. }
  11333. else if (DebugAlwaysTrue(Side == osOther))
  11334. {
  11335. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11336. }
  11337. return Result;
  11338. }
  11339. //---------------------------------------------------------------------------
  11340. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11341. {
  11342. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11343. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11344. if (Title == Result)
  11345. {
  11346. Result = EmptyStr;
  11347. }
  11348. else
  11349. {
  11350. Result += L"\n";
  11351. }
  11352. return Result;
  11353. }
  11354. //---------------------------------------------------------------------------
  11355. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11356. {
  11357. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11358. if (!ASession->Active)
  11359. {
  11360. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11361. }
  11362. else
  11363. {
  11364. Result += GetSessionPath(ASession, osRemote);
  11365. }
  11366. return Result;
  11367. }
  11368. //---------------------------------------------------------------------------
  11369. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11370. {
  11371. return LoadStr(NEW_REMOTE_TAB_HINT);
  11372. }
  11373. //---------------------------------------------------------------------------
  11374. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11375. {
  11376. if (Index >= 0)
  11377. {
  11378. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11379. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11380. if (TabSession == NULL)
  11381. {
  11382. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11383. if (NewTabTabCaption != TabSheet->Caption)
  11384. {
  11385. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11386. }
  11387. }
  11388. else
  11389. {
  11390. TTerminalManager * Manager = TTerminalManager::Instance();
  11391. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11392. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11393. }
  11394. }
  11395. }
  11396. //---------------------------------------------------------------------------
  11397. typedef std::vector<TListItem *> TListItemsVector;
  11398. struct TCalculateSizeOperation
  11399. {
  11400. TCalculateSizeStats Stats;
  11401. TListItemsVector ListItems;
  11402. size_t Index;
  11403. };
  11404. //---------------------------------------------------------------------------
  11405. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11406. {
  11407. TCalculateSizeOperation CalculateSizeOperation;
  11408. Side = GetSide(Side);
  11409. TCustomDirView * ADirView = DirView(Side);
  11410. bool LocalSide = IsSideLocalBrowser(Side);
  11411. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11412. std::unique_ptr<TStrings> FileList(new TStringList());
  11413. for (int Index = 0; Index < AllFileList->Count; Index++)
  11414. {
  11415. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11416. if (ADirView->ItemIsDirectory(Item))
  11417. {
  11418. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11419. CalculateSizeOperation.ListItems.push_back(Item);
  11420. }
  11421. }
  11422. CalculateSizeOperation.Index = 0;
  11423. __int64 Size = 0;
  11424. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation, &CalculateSizeOperation);
  11425. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11426. FOnFileOperationFinished = DirectorySizeCalculated;
  11427. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation, foCalculateSize);
  11428. TCalculatedSizes CalculatedSizes;
  11429. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11430. if (LocalSide)
  11431. {
  11432. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, Side);
  11433. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11434. }
  11435. else
  11436. {
  11437. TCalculateSizeParams Params;
  11438. Params.Stats = &CalculateSizeOperation.Stats;
  11439. Params.UseCache = true;
  11440. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11441. }
  11442. }
  11443. //---------------------------------------------------------------------------
  11444. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(
  11445. TOperationSide Side, const UnicodeString & FileName, bool Success, bool NotCancelled)
  11446. {
  11447. DebugAssert(FCalculateSizeOperation != NULL);
  11448. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11449. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11450. // optimization
  11451. bool GotExpectedItem =
  11452. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11453. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11454. int Index = -1;
  11455. if (DebugAlwaysTrue(GotExpectedItem))
  11456. {
  11457. Index = FCalculateSizeOperation->Index;
  11458. FCalculateSizeOperation->Index++;
  11459. }
  11460. else
  11461. {
  11462. TListItemsVector::iterator I =
  11463. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11464. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11465. {
  11466. Index = I - FCalculateSizeOperation->ListItems.begin();
  11467. }
  11468. }
  11469. if (DebugAlwaysTrue(Index >= 0) && Success && NotCancelled)
  11470. {
  11471. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11472. ADirView->SetItemCalculatedSize(Item, Size);
  11473. }
  11474. }
  11475. //---------------------------------------------------------------------------
  11476. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11477. {
  11478. Accept = false;
  11479. }
  11480. //---------------------------------------------------------------------------
  11481. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11482. {
  11483. // Send Ctrl+Gray+ to the list view
  11484. TKeyboardState KeyState;
  11485. GetKeyboardState(KeyState);
  11486. TKeyboardState NewKeyState;
  11487. memset(NewKeyState, 0, sizeof(NewKeyState));
  11488. NewKeyState[VK_CONTROL] = 0x81;
  11489. SetKeyboardState(NewKeyState);
  11490. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11491. SetKeyboardState(KeyState);
  11492. }
  11493. //---------------------------------------------------------------------------
  11494. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11495. {
  11496. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11497. }
  11498. //---------------------------------------------------------------------------
  11499. void * TCustomScpExplorerForm::SaveFocus()
  11500. {
  11501. return NULL;
  11502. }
  11503. //---------------------------------------------------------------------------
  11504. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11505. {
  11506. DebugUsedParam(Focus);
  11507. DebugAssert(Focus == NULL);
  11508. }
  11509. //---------------------------------------------------------------------------
  11510. void TCustomScpExplorerForm::IncrementalSearchStart()
  11511. {
  11512. TCustomDirView * ADirView = DirView(osCurrent);
  11513. ADirView->SetFocus();
  11514. if (!FIncrementalSearchState.Searching)
  11515. {
  11516. FIncrementalSearchState.Searching = true;
  11517. FIncrementalSearchState.HaveNext = false;
  11518. DebugAssert(FIncrementalSearchState.Text.IsEmpty());
  11519. ADirView->UpdateStatusBar();
  11520. }
  11521. }
  11522. //---------------------------------------------------------------------------
  11523. void __fastcall TCustomScpExplorerForm::RemoteDirViewThumbnailNeeded(
  11524. TUnixDirView *, TListItem * Item, TRemoteFile * File, const TSize & Size, TBitmap *& Bitmap)
  11525. {
  11526. // though when downloading to temporary folder, encryption should not be a problem
  11527. if (Terminal->IsCapable[fcBackgroundTransfers] &&
  11528. !File->IsDirectory)
  11529. {
  11530. UnicodeString FileName = File->FullFileName;
  11531. TFileMasks::TParams MaskParams;
  11532. MaskParams.Size = File->Size;
  11533. MaskParams.Modification = File->Modification;
  11534. if ((File->Size <= static_cast<__int64>(WinConfiguration->RemoteThumbnailSizeLimit) * 1024) &&
  11535. FRemoteThumbnailMask.Matches(FileName, false, File->IsDirectory, &MaskParams))
  11536. {
  11537. Bitmap = TTerminalManager::Instance()->ThumbnailNeeded(Terminal, Item->Index, File, Size);
  11538. }
  11539. }
  11540. }
  11541. //---------------------------------------------------------------------------
  11542. TThumbnailDownloadQueueItem * TCustomScpExplorerForm::AddThumbnailDownloadQueueItem(TManagedTerminal * ATerminal)
  11543. {
  11544. DebugAssert(ATerminal == Terminal);
  11545. TCopyParamType CopyParam = TemporaryFileCopyParam();
  11546. CopyParam.TransferMode = tmBinary;
  11547. UnicodeString SourceDir = ATerminal->CurrentDirectory;
  11548. UnicodeString TempDir, RootTempDir;
  11549. TemporaryDirectoryForRemoteFiles(SourceDir, CopyParam, true, TempDir, RootTempDir);
  11550. TTerminalQueue * AQueue = TTerminalManager::Instance()->FindQueueForTerminal(ATerminal);
  11551. DebugAssert((Queue == NULL) || (AQueue == Queue)); // we might get here before queue is set
  11552. TThumbnailDownloadQueueItem * QueueItem =
  11553. new TThumbnailDownloadQueueItem(this, Terminal, SourceDir, TempDir, &CopyParam);
  11554. AddQueueItem(AQueue, QueueItem, ATerminal);
  11555. return QueueItem;
  11556. }
  11557. //---------------------------------------------------------------------------
  11558. enum { qccRemoteItemVisible, qccRemoteItemRedraw };
  11559. typedef std::pair<int, UnicodeString> TRemoteItemVisibleData;
  11560. //---------------------------------------------------------------------------
  11561. void TCustomScpExplorerForm::PostThumbnailVisibleQueueQuery(int Index, const UnicodeString & FileName)
  11562. {
  11563. // The queue might be destroyed before the WM_QUEUE_CALLBACK is processed
  11564. TRemoteItemVisibleData * Data = new TRemoteItemVisibleData();
  11565. Data->first = Index;
  11566. Data->second = FileName;
  11567. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemVisible, reinterpret_cast<WPARAM>(Data));
  11568. }
  11569. //---------------------------------------------------------------------------
  11570. void TCustomScpExplorerForm::PostThumbnailDrawRequest(int Index)
  11571. {
  11572. PostMessage(Handle, WM_QUEUE_CALLBACK, qccRemoteItemRedraw, Index);
  11573. }
  11574. //---------------------------------------------------------------------------
  11575. void TCustomScpExplorerForm::WMQueueCallback(TMessage & Message)
  11576. {
  11577. int Command = Message.WParam;
  11578. if (Command == qccRemoteItemVisible)
  11579. {
  11580. TRemoteItemVisibleData * Data = reinterpret_cast<TRemoteItemVisibleData *>(Message.LParam);
  11581. int Index = Data->first;
  11582. UnicodeString FileName = Data->second;
  11583. delete Data;
  11584. TGuard Guard(Terminal->ThumbnailsSection.get());
  11585. bool Visible = False;
  11586. if (Terminal->ThumbnailsEnabled &&
  11587. // though we should better also disable thumbnails once we switch to different view style
  11588. (RemoteDirView->DirViewStyle == dvsThumbnail))
  11589. {
  11590. // The message might be processed, while we are already loading a different directory
  11591. if ((Index >= 0) &&
  11592. (Index < RemoteDirView->Items->Count))
  11593. {
  11594. TListItem * Item = RemoteDirView->Items->Item[Index];
  11595. Visible =
  11596. (RemoteDirView->ItemFullFileName(Item) == FileName) &&
  11597. ListView_IsItemVisible(RemoteDirView->Handle, Index);
  11598. }
  11599. }
  11600. Terminal->ThumbnailVisible(Index, FileName, Visible);
  11601. }
  11602. else if (Command == qccRemoteItemRedraw)
  11603. {
  11604. int Index = Message.LParam;
  11605. if ((Index >= 0) &&
  11606. (Index < RemoteDirView->Items->Count))
  11607. {
  11608. RemoteDirView->InvalidateItem(RemoteDirView->Items->Item[Index]);
  11609. }
  11610. }
  11611. }
  11612. //---------------------------------------------------------------------------
  11613. void TCustomScpExplorerForm::InitializeRemoteThumbnailMask()
  11614. {
  11615. UnicodeString DefaultRemoteThumbnailMask = L"*.jpg;*.jpeg;*.gif;*.png;*.svg;*.bmp;*.raw;*.ico;*.heic;*.webp";
  11616. UnicodeString RemoteThumbnailMask = WinConfiguration->RemoteThumbnailMask;
  11617. if (RemoteThumbnailMask.IsEmpty() ||
  11618. StartsStr(L"+", RemoteThumbnailMask) || StartsStr(L"-", RemoteThumbnailMask) || StartsStr(L"*", RemoteThumbnailMask))
  11619. {
  11620. std::unique_ptr<TStrings> RemoteThumbnailMasks(new TStringList());
  11621. while (!DefaultRemoteThumbnailMask.IsEmpty())
  11622. {
  11623. RemoteThumbnailMasks->Add(CutToChar(DefaultRemoteThumbnailMask, L';', true));
  11624. }
  11625. RemoteThumbnailMasks.reset(ProcessFeatures(RemoteThumbnailMasks.get(), RemoteThumbnailMask));
  11626. RemoteThumbnailMask = EmptyStr;
  11627. for (int Index = 0; Index < RemoteThumbnailMasks->Count; Index++)
  11628. {
  11629. AddToList(RemoteThumbnailMask, RemoteThumbnailMasks->Strings[Index], L";");
  11630. }
  11631. }
  11632. FRemoteThumbnailMask.Masks = RemoteThumbnailMask;
  11633. }
  11634. //---------------------------------------------------------------------------
  11635. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartLoading(TObject *)
  11636. {
  11637. Terminal->StartLoadingDirectory();
  11638. }
  11639. //---------------------------------------------------------------------------
  11640. void __fastcall TCustomScpExplorerForm::RemoteDirViewStartReading(TObject *)
  11641. {
  11642. Terminal->DisableThumbnails();
  11643. }
  11644. //---------------------------------------------------------------------------
  11645. void TCustomScpExplorerForm::ChangeDirViewStyle(TOperationSide Side, TDirViewStyle DirViewStyle)
  11646. {
  11647. TCustomDirView * ADirView = DirView(Side);
  11648. if (ADirView->DirViewStyle != DirViewStyle)
  11649. {
  11650. if (DirViewStyle == dvsThumbnail)
  11651. {
  11652. if (dynamic_cast<TUnixDirView *>(ADirView) != NULL)
  11653. {
  11654. Configuration->Usage->Inc(L"ThumbnailsRemote");
  11655. }
  11656. else
  11657. {
  11658. Configuration->Usage->Inc(L"ThumbnailsLocal");
  11659. }
  11660. }
  11661. ADirView->DirViewStyle = DirViewStyle;
  11662. UpdateControls();
  11663. }
  11664. }
  11665. //---------------------------------------------------------------------------
  11666. void __fastcall TCustomScpExplorerForm::ActiveFormChange(TObject *)
  11667. {
  11668. HWND WindowHandle = GetForegroundWindow();
  11669. if ((WindowHandle != nullptr) && (WindowHandle != FOperationStatusWindow))
  11670. {
  11671. DWORD ProcessId;
  11672. if ((GetWindowThreadProcessId(WindowHandle, &ProcessId) != 0) &&
  11673. (ProcessId == GetCurrentProcessId()))
  11674. {
  11675. UnicodeString ClassName;
  11676. ClassName.SetLength(256);
  11677. GetClassName(WindowHandle, ClassName.c_str(), ClassName.Length());
  11678. PackStr(ClassName);
  11679. if ((ClassName == L"OperationStatusWindow") &&
  11680. !IsIconic(WindowHandle))
  11681. {
  11682. FOperationStatusWindow = WindowHandle;
  11683. PlaceOperationStatusWindow();
  11684. FOperationStatusWindowIterations = 0;
  11685. if (FOperationStatusWindowTimer == nullptr)
  11686. {
  11687. FOperationStatusWindowTimer = new TTimer(this);
  11688. }
  11689. FOperationStatusWindowTimer->OnTimer = OperationStatusWindowTimer;
  11690. FOperationStatusWindowTimer->Interval = 50;
  11691. FOperationStatusWindowTimer->Enabled = true;
  11692. }
  11693. }
  11694. }
  11695. }
  11696. //---------------------------------------------------------------------------
  11697. void __fastcall TCustomScpExplorerForm::OperationStatusWindowTimer(TObject *)
  11698. {
  11699. FOperationStatusWindowIterations++;
  11700. PlaceOperationStatusWindow();
  11701. if (FOperationStatusWindowIterations == 5)
  11702. {
  11703. SAFE_DESTROY(FOperationStatusWindowTimer);
  11704. }
  11705. }
  11706. //---------------------------------------------------------------------------
  11707. void TCustomScpExplorerForm::PlaceOperationStatusWindow()
  11708. {
  11709. TRect CurRect;
  11710. if ((Screen->ActiveForm != nullptr) &&
  11711. GetWindowRect(FOperationStatusWindow, &CurRect))
  11712. {
  11713. TRect Rect = CurRect;
  11714. CenterFormOn(Rect, Screen->ActiveForm, nullptr);
  11715. if (Rect != CurRect)
  11716. {
  11717. // What TWinControl.SetBounds does
  11718. SetWindowPos(FOperationStatusWindow, 0, Rect.Left, Rect.Top, 0, 0, SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOSIZE);
  11719. }
  11720. }
  11721. }