CustomScpExplorer.cpp 402 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <Common.h>
  6. #include "CustomScpExplorer.h"
  7. #include <algorithm>
  8. #include <Bookmarks.h>
  9. #include <Interface.h>
  10. #include <Exceptions.h>
  11. #include <CoreMain.h>
  12. #include <FileSystems.h>
  13. #include <TextsCore.h>
  14. #include <TextsWin.h>
  15. #include <HelpWin.h>
  16. #include <VCLCommon.h>
  17. #include <Progress.h>
  18. #include <SynchronizeProgress.h>
  19. #include <DragExt.h>
  20. #include <WinApi.h>
  21. #include "GUITools.h"
  22. #include "NonVisual.h"
  23. #include "Glyphs.h"
  24. #include "Tools.h"
  25. #include "WinConfiguration.h"
  26. #include "TerminalManager.h"
  27. #include "EditorManager.h"
  28. #include "ProgParams.h"
  29. #include "Setup.h"
  30. #include <Consts.hpp>
  31. #include <DateUtils.hpp>
  32. #include <TB2Common.hpp>
  33. #include <DirectoryMonitor.hpp>
  34. #include <System.IOUtils.hpp>
  35. //---------------------------------------------------------------------------
  36. #pragma package(smart_init)
  37. #pragma link "CustomDirView"
  38. #pragma link "CustomUnixDirView"
  39. #pragma link "IEListView"
  40. #pragma link "NortonLikeListView"
  41. #pragma link "UnixDirView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "UnixDriveView"
  44. #pragma link "CustomDriveView"
  45. #pragma link "TB2Dock"
  46. #pragma link "TBXStatusBars"
  47. #pragma link "TB2Item"
  48. #pragma link "TB2Toolbar"
  49. #pragma link "ThemePageControl"
  50. #pragma link "PathLabel"
  51. #pragma resource "*.dfm"
  52. //---------------------------------------------------------------------------
  53. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  54. #define WM_PASTE_FILES (WM_WINSCP_USER + 14)
  55. static const int SessionPanelCount = 3;
  56. //---------------------------------------------------------------------------
  57. class TMutexGuard
  58. {
  59. public:
  60. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  61. int Timeout = 5000)
  62. {
  63. FMutex = NULL;
  64. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  65. if (WaitResult == WAIT_TIMEOUT)
  66. {
  67. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  68. }
  69. else
  70. {
  71. FMutex = AMutex;
  72. }
  73. }
  74. ~TMutexGuard()
  75. {
  76. if (FMutex != NULL)
  77. {
  78. ReleaseMutex(FMutex);
  79. }
  80. }
  81. private:
  82. HANDLE FMutex;
  83. };
  84. //---------------------------------------------------------------------------
  85. class TWindowLock
  86. {
  87. public:
  88. TWindowLock(TCustomScpExplorerForm * Form) :
  89. FForm(Form)
  90. {
  91. FForm->LockWindow();
  92. }
  93. ~TWindowLock()
  94. {
  95. FForm->UnlockWindow();
  96. }
  97. private:
  98. TCustomScpExplorerForm * FForm;
  99. };
  100. //---------------------------------------------------------------------------
  101. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  102. FForm(Form)
  103. {
  104. FForm->BatchStart(FBatchStorage);
  105. }
  106. //---------------------------------------------------------------------------
  107. TAutoBatch::~TAutoBatch()
  108. {
  109. FForm->BatchEnd(FBatchStorage);
  110. }
  111. //---------------------------------------------------------------------------
  112. struct TTransferOperationParam
  113. {
  114. TTransferOperationParam();
  115. UnicodeString TargetDirectory;
  116. bool Temp;
  117. bool DragDrop;
  118. int Options;
  119. TAutoSwitch Queue;
  120. };
  121. //---------------------------------------------------------------------------
  122. TTransferOperationParam::TTransferOperationParam()
  123. {
  124. Temp = false;
  125. DragDrop = false;
  126. Options = 0;
  127. Queue = asAuto;
  128. }
  129. //---------------------------------------------------------------------------
  130. class TTransferPresetNoteData : public TObject
  131. {
  132. public:
  133. UnicodeString Message;
  134. };
  135. //---------------------------------------------------------------------------
  136. class TTerminalNoteData : public TObject
  137. {
  138. public:
  139. TManagedTerminal * Terminal;
  140. };
  141. //---------------------------------------------------------------------------
  142. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  143. FFormRestored(false),
  144. TForm(Owner)
  145. {
  146. AddStartupSequence(L"F");
  147. FInvalid = false;
  148. FCurrentSide = osRemote;
  149. FEverShown = false;
  150. FDocks = new TList();
  151. InitControls();
  152. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  153. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  154. NonVisualDataModule->ScpExplorer = this;
  155. RestoreParams();
  156. ConfigurationChanged();
  157. RemoteDirView->Invalidate();
  158. FAutoOperation = false;
  159. FOnFileOperationFinished = NULL;
  160. FPrimaryOperation = foNone;
  161. FForceExecution = false;
  162. FIgnoreNextDialogChar = 0;
  163. FErrorList = NULL;
  164. FSynchronizeProgressForm = NULL;
  165. FProgressForm = NULL;
  166. FRefreshLocalDirectory = false;
  167. FRefreshRemoteDirectory = false;
  168. FDDExtMapFile = NULL;
  169. // CreateMutexW keeps failing with ERROR_NOACCESS
  170. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  171. DebugAssert(FDDExtMutex != NULL);
  172. FDDTargetControl = NULL;
  173. FDelayedDeletionTimer = NULL;
  174. FDelayedDeletionList = new TStringList();
  175. FDDFileList = NULL;
  176. FPendingTempSpaceWarn = false;
  177. FCapturedLog = NULL;
  178. FDragDropOperation = false;
  179. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  180. FAllowTransferPresetAutoSelect = true;
  181. FSessionChanging = false;
  182. FCopyParamDefault = L"";
  183. FSynchronizeController = NULL;
  184. FPendingQueueActionItem = NULL;
  185. FLockLevel = 0;
  186. FLockSuspendLevel = 0;
  187. FDisabledOnLockSuspend = false;
  188. FAlternativeDelete = false;
  189. FTrayIcon = new ::TTrayIcon(0);
  190. FTrayIcon->OnClick = TrayIconClick;
  191. FMaxQueueLength = 0;
  192. FLastContextPopupScreenPoint = TPoint(-1, -1);
  193. FTransferResumeList = NULL;
  194. FDeletedFiles = NULL;
  195. FMoveToQueue = false;
  196. StandaloneOperation = false;
  197. FOnFeedSynchronizeError = NULL;
  198. FOnSynchronizeAbort = NULL;
  199. FSynchronizeTerminal = NULL;
  200. FNeedSession = false;
  201. FDoNotIdleCurrentTerminal = 0;
  202. FIncrementalSearching = 0;
  203. FIncrementalSearchHaveNext = false;
  204. FQueueFileList.reset(new TQueueFileList());
  205. FProgressSide = osCurrent;
  206. FCalculateSizeOperation = NULL;
  207. FDownloadingFromClipboard = false;
  208. FClipboardFakeMonitorsPendingReset = false;
  209. FHiContrastTheme = NULL;
  210. FEditorManager = new TEditorManager();
  211. FEditorManager->OnFileChange = ExecutedFileChanged;
  212. FEditorManager->OnFileReload = ExecutedFileReload;
  213. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  214. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  215. FLocalEditors = new TList();
  216. FQueueStatus = NULL;
  217. FQueueStatusSection = new TCriticalSection();
  218. FQueueStatusInvalidated = false;
  219. FQueueItemInvalidated = false;
  220. FQueueStatusUpdating = false;
  221. FQueueActedItem = NULL;
  222. FQueueController = new TQueueController(QueueView3);
  223. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  224. FUserActionTimer = new TTimer(this);
  225. FUserActionTimer->Enabled = false;
  226. FUserActionTimer->Interval = 10;
  227. FUserActionTimer->OnTimer = UserActionTimer;
  228. FNotes = new TStringList();
  229. FNoteTimer = new TTimer(this);
  230. FNoteTimer->Enabled = false;
  231. FNoteTimer->OnTimer = NoteTimer;
  232. FOnNoteClick = NULL;
  233. FOle32Library = LoadLibrary(L"Ole32.dll");
  234. FDragMoveCursor = FOle32Library != NULL ?
  235. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  236. UseSystemSettings(this);
  237. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  238. static_cast<TObject*>(GetComponent(fcTransferList)));
  239. DebugAssert(TransferList != NULL);
  240. FTransferListHoverIndex = -1;
  241. TransferList->OnChange = TransferListChange;
  242. TransferList->OnDrawItem = TransferListDrawItem;
  243. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  244. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  245. UseDesktopFont(SessionsPageControl);
  246. UpdateSessionsPageControlHeight();
  247. UseDesktopFont(RemoteDirView);
  248. UseDesktopFont(RemoteDriveView);
  249. UseDesktopFont(QueueView3);
  250. UseDesktopFont(QueueFileList);
  251. UseDesktopFont(QueueLabel);
  252. UseDesktopFont(RemoteStatusBar);
  253. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  254. QueueSplitter->ShowHint = true;
  255. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  256. QueueFileListSplitter->ShowHint = true;
  257. RemotePanelSplitter->ShowHint = true;
  258. UpdateImages();
  259. FCustomCommandMenu = CreateTBXPopupMenu(this);
  260. FCustomCommandLocalFileList = NULL;
  261. FCustomCommandRemoteFileList = NULL;
  262. FSessionColors = new TPngImageList(this);
  263. FSessionColors->ColorDepth = cd32Bit;
  264. AddFixedSessionImages();
  265. SessionsPageControl->Images = FSessionColors;
  266. UpdateQueueLabel();
  267. CheckStoreTransition();
  268. CreateHiddenWindow();
  269. StartUpdates();
  270. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  271. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  272. DriveInfo->NeedData();
  273. }
  274. //---------------------------------------------------------------------------
  275. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  276. {
  277. FInvalid = true;
  278. ReleaseHiContrastTheme();
  279. if (FClipboardTerminal != NULL)
  280. {
  281. ClipboardClear(); // implies ClipboardStop
  282. }
  283. // this has to be one of the very first things to do
  284. StopUpdateThread();
  285. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  286. TTerminalManager::Instance()->ScpExplorer = NULL;
  287. delete FCustomCommandLocalFileList;
  288. delete FCustomCommandRemoteFileList;
  289. delete FCustomCommandMenu;
  290. delete FTrayIcon;
  291. FTrayIcon = NULL;
  292. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  293. delete FEditorManager;
  294. ForceCloseLocalEditors();
  295. delete FLocalEditors;
  296. HideFileFindDialog();
  297. if (FDelayedDeletionTimer)
  298. {
  299. DoDelayedDeletion(NULL);
  300. SAFE_DESTROY(FDelayedDeletionTimer);
  301. }
  302. SAFE_DESTROY(FDelayedDeletionList);
  303. // sometimes we do not get DDEnd so the list is not released
  304. SAFE_DESTROY(FDDFileList);
  305. DebugAssert(FSynchronizeController == NULL);
  306. CloseHandle(FDDExtMutex);
  307. FDDExtMutex = NULL;
  308. FreeLibrary(FOle32Library);
  309. FOle32Library = NULL;
  310. FDragMoveCursor = NULL;
  311. DebugAssert(!FErrorList);
  312. if (FEverShown)
  313. {
  314. // when window is never shown (like when running command-line operation),
  315. // particularly window site is not restored correctly (BoundsRect value set
  316. // in RestoreForm gets lost during handle allocation), so we do not want
  317. // it to be stored
  318. StoreParams();
  319. }
  320. ManagedSession = NULL;
  321. Queue = NULL;
  322. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  323. NonVisualDataModule->ScpExplorer = NULL;
  324. delete FQueueScrollOnDragOver;
  325. FQueueScrollOnDragOver = NULL;
  326. delete FQueueController;
  327. FQueueController = NULL;
  328. delete FQueueStatusSection;
  329. FQueueStatusSection = NULL;
  330. delete FQueueStatus;
  331. FQueueStatus = NULL;
  332. delete FUserActionTimer;
  333. FUserActionTimer = NULL;
  334. delete FNoteTimer;
  335. delete FNotes;
  336. delete FNoteData;
  337. SAFE_DESTROY(FDocks);
  338. SessionsPageControl->Images = NULL;
  339. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  340. SAFE_DESTROY(FSessionColors);
  341. SAFE_DESTROY(FSessionsDragDropFilesEx);
  342. SAFE_DESTROY(FHistoryMenu[0][0]);
  343. SAFE_DESTROY(FHistoryMenu[0][1]);
  344. SAFE_DESTROY(FHistoryMenu[1][0]);
  345. SAFE_DESTROY(FHistoryMenu[1][1]);
  346. if (FHiddenWindow != NULL)
  347. {
  348. DestroyWindow(FHiddenWindow);
  349. FHiddenWindow = NULL;
  350. }
  351. }
  352. //---------------------------------------------------------------------------
  353. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  354. {
  355. if (FHiContrastTheme != NULL)
  356. {
  357. ReleaseTBXTheme(FHiContrastTheme);
  358. FHiContrastTheme = NULL;
  359. }
  360. }
  361. //---------------------------------------------------------------------------
  362. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  363. {
  364. std::unique_ptr<TSessionData> Data;
  365. if (!Session.IsEmpty())
  366. {
  367. bool DefaultsOnly;
  368. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  369. }
  370. TTerminalManager * Manager = TTerminalManager::Instance();
  371. for (int Index = 0; Index < Manager->Count; Index++)
  372. {
  373. TTerminal * Terminal = Manager->Sessions[Index];
  374. if (Session.IsEmpty() ||
  375. Manager->IsActiveTerminalForSite(Terminal, Data.get()))
  376. {
  377. if (Path.IsEmpty())
  378. {
  379. Terminal->ClearCaches();
  380. }
  381. else
  382. {
  383. Terminal->DirectoryModified(Path, true);
  384. }
  385. }
  386. }
  387. // We should flag a pending refresh for the background terminals or busy foreground terminals
  388. if (HasActiveTerminal() &&
  389. CanCommandLineFromAnotherInstance() &&
  390. (Session.IsEmpty() || Manager->IsActiveTerminalForSite(Terminal, Data.get())) &&
  391. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  392. {
  393. Terminal->ReloadDirectory();
  394. }
  395. }
  396. //---------------------------------------------------------------------------
  397. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  398. {
  399. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  400. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  401. size_t MessageSize = sizeof(TCopyDataMessage);
  402. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  403. if (Result)
  404. {
  405. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  406. Result = (Message.Version == TCopyDataMessage::Version1);
  407. if (Result)
  408. {
  409. switch (Message.Command)
  410. {
  411. case TCopyDataMessage::CommandCanCommandLine:
  412. Result = CanCommandLineFromAnotherInstance();
  413. if (Result)
  414. {
  415. AppLog(L"Can process command-line from other instance");
  416. }
  417. else
  418. {
  419. AppLog(L"Cannot process command-line from other instance");
  420. }
  421. break;
  422. case TCopyDataMessage::CommandCommandLine:
  423. {
  424. UnicodeString CommandLine(Message.CommandLine);
  425. Result = CommandLineFromAnotherInstance(CommandLine);
  426. }
  427. break;
  428. case TCopyDataMessage::RefreshPanel:
  429. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  430. break;
  431. case TCopyDataMessage::MainWindowCheck:
  432. Result = true;
  433. break;
  434. default:
  435. Result = false;
  436. break;
  437. }
  438. }
  439. }
  440. Message.Result = Result ? 1 : 0;
  441. }
  442. //---------------------------------------------------------------------------
  443. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  444. {
  445. WNDCLASS WindowClass = {0};
  446. WindowClass.lpfnWndProc = DefWindowProc;
  447. WindowClass.hInstance = HInstance;
  448. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  449. FHiddenWindow = NULL;
  450. if (RegisterClass(&WindowClass))
  451. {
  452. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  453. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  454. }
  455. }
  456. //---------------------------------------------------------------------------
  457. bool __fastcall TCustomScpExplorerForm::CanConsole()
  458. {
  459. return
  460. HasActiveTerminal() &&
  461. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  462. }
  463. //---------------------------------------------------------------------------
  464. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  465. {
  466. bool Result = Visible && !NonVisualDataModule->Busy;
  467. return Result;
  468. }
  469. //---------------------------------------------------------------------------
  470. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  471. const UnicodeString & CommandLine)
  472. {
  473. TProgramParams Params(CommandLine);
  474. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  475. if (Result)
  476. {
  477. NonVisualDataModule->StartBusy();
  478. try
  479. {
  480. // this action is initiated from another process,
  481. // so it's likely that our window is not visible,
  482. // and user won't see what is going on
  483. Application->BringToFront();
  484. // reload sessions as we may be asked to open a session
  485. // just stored by another instance
  486. StoredSessions->Reload();
  487. UnicodeString SessionName = Params.Param[1];
  488. std::unique_ptr<TObjectList> DataList(new TObjectList());
  489. try
  490. {
  491. UnicodeString DownloadFile; // unused
  492. int Flags = GetCommandLineParseUrlFlags(&Params);
  493. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  494. }
  495. catch (EAbort &)
  496. {
  497. // Happens when opening session in PuTTY and in other situations,
  498. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  499. // to process the command-line on its own (or to pass it to yet another instance)
  500. }
  501. if (DataList->Count > 0)
  502. {
  503. TTerminalManager * Manager = TTerminalManager::Instance();
  504. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  505. }
  506. }
  507. __finally
  508. {
  509. NonVisualDataModule->EndBusy();
  510. }
  511. }
  512. return Result;
  513. }
  514. //---------------------------------------------------------------------------
  515. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  516. {
  517. TManagedTerminal * Result;
  518. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  519. {
  520. Result = FManagedSession;
  521. }
  522. else
  523. {
  524. Result = NULL;
  525. }
  526. return Result;
  527. }
  528. //---------------------------------------------------------------------------
  529. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  530. {
  531. if (FManagedSession != value)
  532. {
  533. TWindowLock Lock(this);
  534. SessionChanging();
  535. DoSetManagedSession(value, false);
  536. }
  537. }
  538. //---------------------------------------------------------------------------
  539. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  540. {
  541. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  542. FManagedSession = value;
  543. {
  544. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect);
  545. FAllowTransferPresetAutoSelect = false;
  546. TAutoFlag SessionChangingFlag(FSessionChanging);
  547. SessionChanged(Replace);
  548. }
  549. if (Terminal != NULL)
  550. {
  551. TransferPresetAutoSelect();
  552. }
  553. // Update app and tab titles, prevented above by FSessionChanging.
  554. UpdateControls();
  555. }
  556. //---------------------------------------------------------------------------
  557. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  558. {
  559. DoSetManagedSession(value, true);
  560. }
  561. //---------------------------------------------------------------------------
  562. void __fastcall TCustomScpExplorerForm::SessionChanging()
  563. {
  564. if (ManagedSession != NULL)
  565. {
  566. UpdateSession(ManagedSession);
  567. }
  568. }
  569. //---------------------------------------------------------------------------
  570. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  571. {
  572. if (ManagedSession != NULL)
  573. {
  574. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  575. }
  576. if (!TTerminalManager::Instance()->Updating)
  577. {
  578. SessionListChanged();
  579. }
  580. if (Terminal != NULL)
  581. {
  582. TObject * State = NULL;
  583. if (WinConfiguration->PreservePanelState)
  584. {
  585. State = Terminal->RemoteExplorerState;
  586. DirView(osRemote)->AnnounceState(State);
  587. }
  588. try
  589. {
  590. if (Replaced)
  591. {
  592. RemoteDirView->ReplaceTerminal(Terminal);
  593. }
  594. else
  595. {
  596. RemoteDirView->Terminal = Terminal;
  597. }
  598. if (Terminal->Active)
  599. {
  600. Terminal->RefreshDirectory();
  601. }
  602. if (State != NULL)
  603. {
  604. DirView(osRemote)->RestoreState(State);
  605. }
  606. }
  607. __finally
  608. {
  609. DirView(osRemote)->AnnounceState(NULL);
  610. }
  611. }
  612. else
  613. {
  614. RemoteDirView->Terminal = NULL;
  615. }
  616. InitStatusBar();
  617. UpdateTransferList();
  618. // Update panels Enable state before refreshing the labels
  619. UpdateControls();
  620. }
  621. //---------------------------------------------------------------------------
  622. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  623. {
  624. if (Queue != value)
  625. {
  626. if (FQueue != NULL)
  627. {
  628. FQueue->OnListUpdate = NULL;
  629. FQueue->OnQueueItemUpdate = NULL;
  630. }
  631. FQueue = value;
  632. if (FQueue != NULL)
  633. {
  634. DebugAssert(FQueue->OnListUpdate == NULL);
  635. FQueue->OnListUpdate = QueueListUpdate;
  636. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  637. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  638. }
  639. QueueChanged();
  640. }
  641. }
  642. //---------------------------------------------------------------------------
  643. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  644. TListItem * Item)
  645. {
  646. if (FQueueActedItem == Item)
  647. {
  648. FQueueActedItem = NULL;
  649. if ((QueueView3->PopupMenu != NULL) &&
  650. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  651. {
  652. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  653. ReleaseCapture();
  654. }
  655. }
  656. if (Item->Data == FPendingQueueActionItem)
  657. {
  658. FPendingQueueActionItem = NULL;
  659. }
  660. }
  661. //---------------------------------------------------------------------------
  662. bool TCustomScpExplorerForm::IsAnythingQueued()
  663. {
  664. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  665. }
  666. //---------------------------------------------------------------------------
  667. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  668. {
  669. {
  670. TGuard Guard(FQueueStatusSection);
  671. FQueueStatusInvalidated = false;
  672. if (FQueue != NULL)
  673. {
  674. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  675. }
  676. }
  677. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  678. {
  679. FMaxQueueLength = FQueueStatus->Count;
  680. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  681. }
  682. {
  683. TAutoFlag Flag(FQueueStatusUpdating);
  684. FQueueController->UpdateQueueStatus(FQueueStatus);
  685. }
  686. UpdateQueueFileList();
  687. SetQueueProgress();
  688. UpdateQueueView();
  689. bool IsEmpty = !IsAnythingQueued();
  690. if (IsEmpty && (Terminal != NULL))
  691. {
  692. TOnceDoneOperation OnceDoneOperation =
  693. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  694. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  695. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  696. {
  697. FQueue->Enabled = false;
  698. }
  699. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  700. {
  701. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  702. }
  703. }
  704. }
  705. //---------------------------------------------------------------------------
  706. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  707. {
  708. UnicodeString Result;
  709. if (FQueueStatus != NULL)
  710. {
  711. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  712. {
  713. TFileOperationProgressType * ProgressData =
  714. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  715. if ((ProgressData != NULL) && ProgressData->InProgress)
  716. {
  717. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  718. }
  719. }
  720. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  721. {
  722. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  723. }
  724. }
  725. return Result;
  726. }
  727. //---------------------------------------------------------------------------
  728. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  729. {
  730. ComponentVisible[fcQueueView] =
  731. !IsLocalBrowserMode() &&
  732. ((WinConfiguration->QueueView.Show == qvShow) ||
  733. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  734. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  735. }
  736. //---------------------------------------------------------------------------
  737. void __fastcall TCustomScpExplorerForm::QueueChanged()
  738. {
  739. if (FQueueStatus != NULL)
  740. {
  741. // UpdateFileList implementation relies on the status being recreated when session changes
  742. delete FQueueStatus;
  743. FQueueStatus = NULL;
  744. }
  745. UpdateQueueStatus(true);
  746. }
  747. //---------------------------------------------------------------------------
  748. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  749. {
  750. if (FQueue == Queue)
  751. {
  752. FQueueStatusInvalidated = true;
  753. }
  754. }
  755. //---------------------------------------------------------------------------
  756. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  757. TQueueItem * Item)
  758. {
  759. if (FQueue == Queue)
  760. {
  761. TGuard Guard(FQueueStatusSection);
  762. // this may be running in parallel with QueueChanged
  763. if (FQueueStatus != NULL)
  764. {
  765. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  766. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  767. {
  768. FRefreshLocalDirectory = (QueueItem == NULL) ||
  769. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  770. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  771. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  772. }
  773. if (QueueItem != NULL)
  774. {
  775. QueueItem->UserData = (void*)true;
  776. FQueueItemInvalidated = true;
  777. }
  778. }
  779. }
  780. }
  781. //---------------------------------------------------------------------------
  782. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  783. {
  784. // during standalone editing, we have no way to see/control queue,
  785. // so we have to always popup prompts automatically
  786. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  787. }
  788. //---------------------------------------------------------------------------
  789. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  790. {
  791. if (FQueueStatus != NULL)
  792. {
  793. bool QueueAutoPopup = IsQueueAutoPopup();
  794. bool NeedRefresh = FQueueController->NeedRefresh();
  795. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  796. FQueueItemInvalidated = false;
  797. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  798. bool Updated = false;
  799. TQueueItemProxy * QueueItem;
  800. bool WasUserAction;
  801. for (int Index = 0; Index < Limit; Index++)
  802. {
  803. bool Update = false;
  804. QueueItem = FQueueStatus->Items[Index];
  805. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  806. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  807. (FPendingQueueActionItem == NULL))
  808. {
  809. FPendingQueueActionItem = QueueItem;
  810. FUserActionTimer->Enabled = true;
  811. }
  812. if ((bool)QueueItem->UserData)
  813. {
  814. QueueItem->UserData = (void*)false;
  815. QueueItem->Update();
  816. Updated = true;
  817. Update = true;
  818. }
  819. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  820. {
  821. Update = true;
  822. }
  823. if (Update)
  824. {
  825. FQueueController->RefreshQueueItem(QueueItem);
  826. }
  827. }
  828. if (Updated)
  829. {
  830. NonVisualDataModule->UpdateNonVisibleActions();
  831. SetQueueProgress();
  832. UpdateQueueFileList();
  833. }
  834. }
  835. }
  836. //---------------------------------------------------------------------------
  837. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  838. {
  839. if (FTaskbarList != NULL)
  840. {
  841. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  842. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  843. }
  844. }
  845. //---------------------------------------------------------------------------
  846. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  847. {
  848. if (Progress >= 0)
  849. {
  850. if (FTaskbarList != NULL)
  851. {
  852. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  853. }
  854. }
  855. else
  856. {
  857. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  858. }
  859. }
  860. //---------------------------------------------------------------------------
  861. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  862. {
  863. int OverallProgress;
  864. // FProgressForm is null when this is called from SetQueueProgress
  865. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  866. {
  867. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  868. }
  869. else if (!ProgressData->IsIndeterminate())
  870. {
  871. OverallProgress = ProgressData->OverallProgress();
  872. }
  873. else
  874. {
  875. OverallProgress = -1;
  876. }
  877. SetTaskbarListProgressValue(OverallProgress);
  878. }
  879. //---------------------------------------------------------------------------
  880. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  881. {
  882. TTerminalManager::Instance()->QueueStatusUpdated();
  883. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  884. {
  885. // Do not animate task bar button, when items are queued, but processing is disabled
  886. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  887. {
  888. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  889. {
  890. TFileOperationProgressType * ProgressData = NULL;
  891. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  892. {
  893. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  894. }
  895. if ((ProgressData != NULL) &&
  896. ProgressData->InProgress)
  897. {
  898. SetTaskbarListProgressValue(ProgressData);
  899. }
  900. else
  901. {
  902. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  903. }
  904. }
  905. else
  906. {
  907. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  908. }
  909. }
  910. else
  911. {
  912. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  913. }
  914. }
  915. UpdateQueueLabel();
  916. }
  917. //---------------------------------------------------------------------------
  918. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  919. {
  920. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  921. if (FQueueStatus != NULL)
  922. {
  923. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  924. if (ActiveAndPendingPrimaryCount > 0)
  925. {
  926. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  927. }
  928. }
  929. QueueLabel->Caption = Caption;
  930. }
  931. //---------------------------------------------------------------------------
  932. void TCustomScpExplorerForm::CheckStoreTransition()
  933. {
  934. if (WinConfiguration->StoreTransition == stInit)
  935. {
  936. if (IsUWP())
  937. {
  938. WinConfiguration->StoreTransition = stStoreFresh;
  939. AppLog(L"Fresh UWP/store installation");
  940. }
  941. else
  942. {
  943. WinConfiguration->StoreTransition = stStandard;
  944. AppLog(L"Fresh standard installation");
  945. }
  946. }
  947. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  948. {
  949. WinConfiguration->StoreTransition = stStoreMigrated;
  950. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  951. AppLog(L"Standard installation migrated to store installation");
  952. }
  953. if (WinConfiguration->StoreTransition == stStoreMigrated)
  954. {
  955. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  956. Toolbar->Parent = MessageDock;
  957. Toolbar->FullSize = true;
  958. Toolbar->Color = Application->HintColor;
  959. TTBXLabelItem * LabelItem;
  960. LabelItem = new TTBXLabelItem(Toolbar);
  961. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  962. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  963. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  964. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  965. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  966. Toolbar->Items->Add(LabelItem);
  967. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  968. LinkItem->FontSettings->Color = LinkColor;
  969. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  970. LinkItem->OnClick = StoreTransitionLinkClick;
  971. Toolbar->Items->Add(LinkItem);
  972. AddMenuSeparator(Toolbar->Items);
  973. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  974. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  975. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  976. CloseItem->OnClick = StoreTransitionCloseClick;
  977. Toolbar->Items->Add(CloseItem);
  978. GiveTBItemPriority(CloseItem);
  979. }
  980. }
  981. //---------------------------------------------------------------------------
  982. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  983. {
  984. ShowHelp(HELP_STORE_TRANSITION);
  985. }
  986. //---------------------------------------------------------------------------
  987. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  988. {
  989. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  990. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  991. delete Toolbar;
  992. WinConfiguration->StoreTransition = stStoreAcknowledged;
  993. UpdateControls();
  994. }
  995. //---------------------------------------------------------------------------
  996. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  997. {
  998. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  999. static_cast<TComponent*>(GetComponent(fcTransferList)));
  1000. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  1001. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  1002. TransferList->Strings->BeginUpdate();
  1003. try
  1004. {
  1005. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  1006. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  1007. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  1008. if (FTransferDropDownHint.IsEmpty())
  1009. {
  1010. FTransferDropDownHint = TransferDropDown->Hint;
  1011. }
  1012. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1013. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1014. TransferDropDown->Text = StripHotkey(Name);
  1015. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1016. (FTransferDropDownHint, StripHotkey(Name),
  1017. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1018. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1019. // update the label, otherwise when it is updated only on the first draw
  1020. // of the list, it is drawn "bold" for some reason
  1021. FTransferListHoverIndex = TransferList->ItemIndex;
  1022. UpdateTransferLabel();
  1023. }
  1024. __finally
  1025. {
  1026. TransferList->Strings->EndUpdate();
  1027. }
  1028. }
  1029. //---------------------------------------------------------------------------
  1030. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1031. {
  1032. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1033. DebugAssert(Toolbar != NULL);
  1034. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1038. {
  1039. TForm::UpdateActions();
  1040. if (ComponentVisible[fcCustomCommandsBand])
  1041. {
  1042. UpdateCustomCommandsToolbar();
  1043. }
  1044. }
  1045. //---------------------------------------------------------------------------
  1046. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1047. {
  1048. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1052. {
  1053. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1054. {
  1055. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1056. // Without this, the panel turns gray and unused part of header turns black
  1057. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1058. }
  1059. }
  1060. //---------------------------------------------------------------------------
  1061. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1062. {
  1063. Color = GetBtnFaceColor();
  1064. DebugAssert(Configuration && RemoteDirView);
  1065. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1066. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1067. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1068. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1069. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1070. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1071. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1072. UpdateRowSelect(RemoteDirView);
  1073. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1074. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1075. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1076. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1077. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1078. UpdateSessionsPageControlHeight();
  1079. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1080. UpdateToolbarDisplayMode();
  1081. UpdateTransferList();
  1082. if (Terminal != NULL)
  1083. {
  1084. TransferPresetAutoSelect();
  1085. }
  1086. UpdateQueueView();
  1087. UpdateControls();
  1088. // this can be called even before constuctor finishes.
  1089. if (FEditorManager != NULL)
  1090. {
  1091. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1092. }
  1093. // this can be called even before constuctor finishes.
  1094. if (FLocalEditors != NULL)
  1095. {
  1096. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1097. {
  1098. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1099. }
  1100. }
  1101. if (ComponentVisible[fcCustomCommandsBand])
  1102. {
  1103. UpdateCustomCommandsToolbar();
  1104. }
  1105. // show only when keeping queue items forever,
  1106. // otherwise, it's enough to have it in the context menu
  1107. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1108. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1109. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1110. {
  1111. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1112. FFileColorsCurrent = WinConfiguration->FileColors;
  1113. FileColorsChanged();
  1114. }
  1115. }
  1116. //---------------------------------------------------------------------------
  1117. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1118. {
  1119. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1120. DirView->Invalidate();
  1121. }
  1122. //---------------------------------------------------------------------------
  1123. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1124. {
  1125. DoFileColorsChanged(RemoteDirView);
  1126. }
  1127. //---------------------------------------------------------------------------
  1128. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1129. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1130. void * /*Arg*/)
  1131. {
  1132. if (Token != NULL)
  1133. {
  1134. TForm * Editor = dynamic_cast<TForm*>(Token);
  1135. DebugAssert(Editor != NULL);
  1136. ReconfigureEditorForm(Editor);
  1137. }
  1138. }
  1139. //---------------------------------------------------------------------------
  1140. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1141. {
  1142. WinConfiguration->DDTransferConfirmation = asOn;
  1143. }
  1144. //---------------------------------------------------------------------------
  1145. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1146. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1147. {
  1148. // noop
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1152. {
  1153. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1157. {
  1158. if (DoNotShowAgain)
  1159. {
  1160. if (DragDrop)
  1161. {
  1162. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1163. {
  1164. PopupTrayBalloon(
  1165. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1166. }
  1167. WinConfiguration->DDTransferConfirmation = asOff;
  1168. }
  1169. else
  1170. {
  1171. WinConfiguration->ConfirmTransferring = false;
  1172. }
  1173. }
  1174. else
  1175. {
  1176. // User explicitly unchecked "do not show again",
  1177. // so show him the dialog the next time
  1178. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1179. {
  1180. WinConfiguration->DDTransferConfirmation = asOn;
  1181. }
  1182. }
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1186. TTransferDirection Direction, TTransferType Type, bool Temp,
  1187. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1188. bool Confirm, bool DragDrop, int Options)
  1189. {
  1190. bool Result = true;
  1191. DebugAssert(HasActiveTerminal());
  1192. // these parameters are known in advance
  1193. int Params =
  1194. FLAGMASK(Type == ttMove, cpDelete);
  1195. bool ToTemp = (Temp && (Direction == tdToLocal));
  1196. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1197. {
  1198. bool DisableNewerOnly =
  1199. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1200. ToTemp;
  1201. Options |=
  1202. FLAGMASK(ToTemp, coTemp) |
  1203. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1204. coDoNotShowAgain;
  1205. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1206. int CopyParamAttrs = (Direction == tdToRemote ?
  1207. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1208. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1209. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1210. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1211. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1212. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1213. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1214. if (Result)
  1215. {
  1216. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1217. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1218. }
  1219. }
  1220. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1221. {
  1222. Configuration->Usage->Inc(L"TransfersOnBackground");
  1223. // these parameter are known only after transfer dialog
  1224. Params |=
  1225. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1226. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1227. Result = false;
  1228. ClearTransferSourceSelection(Direction);
  1229. }
  1230. return Result;
  1231. }
  1232. //---------------------------------------------------------------------------
  1233. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1234. {
  1235. if (FOnFileOperationFinished != NULL)
  1236. {
  1237. FOnFileOperationFinished(Side, UnicodeString(), true);
  1238. }
  1239. else
  1240. {
  1241. if (HasDirView[Side])
  1242. {
  1243. DirView(Side)->SelectAll(smNone);
  1244. }
  1245. }
  1246. }
  1247. //---------------------------------------------------------------------------
  1248. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1249. {
  1250. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1251. ClearOperationSelection(Side);
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1255. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1256. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1257. int Params)
  1258. {
  1259. DebugAssert(Queue != NULL);
  1260. bool SingleFile = false;
  1261. if (FileList->Count == 1)
  1262. {
  1263. if (Direction == tdToRemote)
  1264. {
  1265. UnicodeString FileName = FileList->Strings[0];
  1266. SingleFile = FileExists(ApiPath(FileName));
  1267. }
  1268. else
  1269. {
  1270. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1271. SingleFile = !File->IsDirectory;
  1272. }
  1273. }
  1274. TQueueItem * QueueItem;
  1275. if (Direction == tdToRemote)
  1276. {
  1277. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1278. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1279. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1280. }
  1281. else
  1282. {
  1283. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1284. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1285. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1286. }
  1287. AddQueueItem(Queue, QueueItem, Terminal);
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1291. {
  1292. if (Queue->IsEmpty)
  1293. {
  1294. Terminal->QueueOperationStart = Now();
  1295. }
  1296. Queue->AddItem(QueueItem);
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1300. {
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. void __fastcall TCustomScpExplorerForm::InitControls()
  1304. {
  1305. DebugAssert(FDocks != NULL);
  1306. for (int Index = 0; Index < ComponentCount; Index++)
  1307. {
  1308. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1309. if ((Dock != NULL) && (Dock->Tag == 0))
  1310. {
  1311. FDocks->Add(Dock);
  1312. }
  1313. }
  1314. CollectItemsWithTextDisplayMode(this);
  1315. }
  1316. //---------------------------------------------------------------------------
  1317. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1318. {
  1319. ConfigurationChanged();
  1320. QueuePanel->Height =
  1321. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1322. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1323. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1324. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1325. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1326. QueueFileList->Height =
  1327. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1328. if (QueueFileList->Visible)
  1329. {
  1330. AdjustQueueLayout();
  1331. }
  1332. UpdateCustomCommandsToolbar();
  1333. }
  1334. //---------------------------------------------------------------------------
  1335. void __fastcall TCustomScpExplorerForm::StoreParams()
  1336. {
  1337. int APixelsPerInch = GetControlPixelsPerInch(this);
  1338. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1339. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1340. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1341. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1342. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1343. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1344. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1345. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1346. }
  1347. //---------------------------------------------------------------------------
  1348. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1349. {
  1350. if (!FFormRestored)
  1351. {
  1352. FFormRestored = true;
  1353. RestoreFormParams();
  1354. }
  1355. TForm::CreateParams(Params);
  1356. }
  1357. //---------------------------------------------------------------------------
  1358. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1359. {
  1360. DebugAssert(FDocks != NULL);
  1361. for (int Index = 0; Index < FDocks->Count; Index++)
  1362. {
  1363. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1364. }
  1365. }
  1366. //---------------------------------------------------------------------------
  1367. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1368. {
  1369. SetDockAllowDrag(true);
  1370. while (!ButtonsStr.IsEmpty())
  1371. {
  1372. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1373. UnicodeString Name = CutToChar(S, L'=', true);
  1374. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1375. {
  1376. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1377. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1378. {
  1379. while (!S.IsEmpty())
  1380. {
  1381. UnicodeString S2 = CutToChar(S, L',', true);
  1382. UnicodeString Name = CutToChar(S2, L':', true);
  1383. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1384. {
  1385. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1386. if (SameText(GetToolbarItemName(Item), Name))
  1387. {
  1388. // forward compatibility
  1389. UnicodeString S3 = CutToChar(S2, L':', true);
  1390. bool Visible = StrToIntDef(S3, 0);
  1391. Item->Visible = Visible;
  1392. }
  1393. }
  1394. }
  1395. }
  1396. }
  1397. }
  1398. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1399. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1400. }
  1401. //---------------------------------------------------------------------------
  1402. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1403. {
  1404. UnicodeString Result;
  1405. SetDockAllowDrag(true);
  1406. Result = ::GetToolbarsLayoutStr(this);
  1407. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1408. return Result;
  1409. }
  1410. //---------------------------------------------------------------------------
  1411. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1412. {
  1413. UnicodeString Result;
  1414. if (Item->Action != NULL)
  1415. {
  1416. Result = Item->Action->Name;
  1417. Result = RemoveSuffix(Result, L"Action", true);
  1418. }
  1419. else
  1420. {
  1421. Result = Item->Name;
  1422. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1423. Result = RemoveSuffix(Result, L"Item", true);
  1424. }
  1425. return Result;
  1426. }
  1427. //---------------------------------------------------------------------------
  1428. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1429. {
  1430. UnicodeString Result;
  1431. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1432. {
  1433. UnicodeString ToolbarStr;
  1434. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1435. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1436. {
  1437. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1438. {
  1439. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1440. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1441. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1442. // and save the changes here only.
  1443. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1444. {
  1445. UnicodeString Name = GetToolbarItemName(Item);
  1446. DebugAssert(Name.Pos(L"TBX") == 0);
  1447. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1448. }
  1449. }
  1450. }
  1451. if (!ToolbarStr.IsEmpty())
  1452. {
  1453. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1454. }
  1455. }
  1456. return Result;
  1457. }
  1458. //---------------------------------------------------------------------------
  1459. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1460. {
  1461. DebugAssert(FProgressForm == NULL);
  1462. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1463. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1464. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1465. FProgressForm->DeleteLocalToRecycleBin =
  1466. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1467. FProgressForm->DeleteRemoteToRecycleBin =
  1468. HasActiveTerminal() &&
  1469. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1470. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1471. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1472. LockWindow();
  1473. // Actually, do not know what hides the progress once the operation finishes
  1474. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1475. SetTaskbarListProgressState(TBPF_NORMAL);
  1476. }
  1477. //---------------------------------------------------------------------------
  1478. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1479. {
  1480. UnlockWindow();
  1481. SAFE_DESTROY(FProgressForm);
  1482. SetQueueProgress();
  1483. }
  1484. //---------------------------------------------------------------------------
  1485. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1486. TFileOperationProgressType & ProgressData)
  1487. {
  1488. // Download to temporary local directory
  1489. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1490. {
  1491. bool Continue = true;
  1492. FPendingTempSpaceWarn = false;
  1493. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1494. if (!Continue)
  1495. {
  1496. Abort();
  1497. }
  1498. }
  1499. // operation is being executed and we still didn't show up progress form
  1500. if (ProgressData.InProgress && !FProgressForm)
  1501. {
  1502. CreateProgressForm(NULL);
  1503. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1504. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1505. }
  1506. // operation is finished (or terminated), so we hide progress form
  1507. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1508. {
  1509. DestroyProgressForm();
  1510. if (ProgressData.Operation == foCalculateSize)
  1511. {
  1512. // When calculating size before transfer, the abort caused by
  1513. // cancel flag set due to "MoveToQueue" below,
  1514. // is not propagated back to us in ExecuteFileOperation,
  1515. // as it is silently swallowed.
  1516. // So we explicitly (re)throw it here.
  1517. if (FMoveToQueue)
  1518. {
  1519. Abort();
  1520. }
  1521. }
  1522. else
  1523. {
  1524. if ((ProgressData.Cancel == csContinue) &&
  1525. !FAutoOperation)
  1526. {
  1527. OperationComplete(ProgressData.StartTime);
  1528. }
  1529. }
  1530. }
  1531. if (FProgressForm &&
  1532. // Can happen only during synchronization, when ending one of the operations
  1533. ProgressData.InProgress)
  1534. {
  1535. FProgressForm->SetProgressData(ProgressData);
  1536. DebugAssert(ProgressData.InProgress);
  1537. SetTaskbarListProgressValue(&ProgressData);
  1538. if (FProgressForm->Cancel > csContinue)
  1539. {
  1540. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1541. if (FProgressForm->Cancel == csCancelFile)
  1542. {
  1543. FProgressForm->ClearCancel();
  1544. }
  1545. // cancel cancels even the move
  1546. FMoveToQueue = false;
  1547. }
  1548. else if (FProgressForm->MoveToQueue)
  1549. {
  1550. FMoveToQueue = true;
  1551. ProgressData.SetCancelAtLeast(csCancel);
  1552. }
  1553. if ((FTransferResumeList != NULL) &&
  1554. ProgressData.InProgress &&
  1555. ProgressData.IsTransfer() &&
  1556. !ProgressData.FullFileName.IsEmpty())
  1557. {
  1558. if ((FTransferResumeList->Count == 0) ||
  1559. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1560. {
  1561. // note that we do not recognize directories from files here
  1562. FTransferResumeList->Add(ProgressData.FullFileName);
  1563. }
  1564. }
  1565. }
  1566. }
  1567. //---------------------------------------------------------------------------
  1568. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1569. const TDateTime & StartTime)
  1570. {
  1571. if (GUIConfiguration->BeepOnFinish &&
  1572. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1573. {
  1574. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1575. DWORD Sound;
  1576. if (!ExtractFileExt(BeepSound).IsEmpty())
  1577. {
  1578. Sound = SND_FILENAME;
  1579. }
  1580. else
  1581. {
  1582. Sound = SND_ALIAS;
  1583. }
  1584. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1585. }
  1586. }
  1587. //---------------------------------------------------------------------------
  1588. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1589. TFileOperationProgressType & ProgressData)
  1590. {
  1591. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1592. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1593. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1594. FileOperationProgress(ProgressData);
  1595. }
  1596. //---------------------------------------------------------------------------
  1597. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1598. {
  1599. UnicodeString Result;
  1600. if (FProgressForm != NULL)
  1601. {
  1602. Result = FProgressForm->ProgressStr();
  1603. }
  1604. return Result;
  1605. }
  1606. //---------------------------------------------------------------------------
  1607. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1608. bool DragDrop)
  1609. {
  1610. return (!DragDrop && (DropSourceControl == NULL)) ||
  1611. (DropSourceControl == DirView(osOther));
  1612. }
  1613. //---------------------------------------------------------------------------
  1614. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1615. {
  1616. TCustomDirView * ADirView = DirView(Side);
  1617. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1618. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1619. // this can happen when local drive is unplugged in the middle of the operation
  1620. if (Item != NULL)
  1621. {
  1622. if (Unselect)
  1623. {
  1624. Item->Selected = false;
  1625. }
  1626. ADirView->MakeProgressVisible(Item);
  1627. }
  1628. return Item;
  1629. }
  1630. //---------------------------------------------------------------------------
  1631. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1632. TFileOperation Operation, TOperationSide Side,
  1633. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1634. TOnceDoneOperation & OnceDoneOperation)
  1635. {
  1636. if (!FAutoOperation)
  1637. {
  1638. // no selection on "/upload", form serves only as event handler
  1639. // (it is not displayed)
  1640. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1641. ((Operation == FPrimaryOperation) ||
  1642. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1643. {
  1644. TOperationSide DViewSide;
  1645. if ((FProgressSide != osCurrent) &&
  1646. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1647. {
  1648. // assume the operation is over the focused panel
  1649. DViewSide = FProgressSide;
  1650. }
  1651. else
  1652. {
  1653. DViewSide = Side;
  1654. }
  1655. if (FOnFileOperationFinished != NULL)
  1656. {
  1657. FOnFileOperationFinished(DViewSide, FileName, Success);
  1658. }
  1659. else
  1660. {
  1661. VisualiseOperationFinished(DViewSide, FileName, Success);
  1662. }
  1663. }
  1664. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1665. {
  1666. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1667. {
  1668. if (Side == osLocal)
  1669. {
  1670. Configuration->Usage->Inc(L"UploadedFiles");
  1671. }
  1672. else
  1673. {
  1674. Configuration->Usage->Inc(L"DownloadedFiles");
  1675. }
  1676. }
  1677. }
  1678. }
  1679. if (Success && (FSynchronizeController != NULL))
  1680. {
  1681. DebugAssert(!IsSideLocalBrowser(osRemote));
  1682. if (Operation == foCopy)
  1683. {
  1684. DebugAssert(Side == osLocal);
  1685. FSynchronizeController->LogOperation(soUpload, FileName);
  1686. }
  1687. else if (Operation == foDelete)
  1688. {
  1689. DebugAssert(Side == osRemote);
  1690. FSynchronizeController->LogOperation(soDelete, FileName);
  1691. }
  1692. }
  1693. if (FProgressForm)
  1694. {
  1695. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1696. }
  1697. }
  1698. //---------------------------------------------------------------------------
  1699. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1700. TFileOperation Operation, TOperationSide Side,
  1701. bool Temp, const UnicodeString & FileName, Boolean Success,
  1702. TOnceDoneOperation & OnceDoneOperation)
  1703. {
  1704. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1705. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1706. OnceDoneOperation);
  1707. }
  1708. //---------------------------------------------------------------------------
  1709. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1710. {
  1711. return false;
  1712. }
  1713. //---------------------------------------------------------------------------
  1714. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1715. {
  1716. return false;
  1717. }
  1718. //---------------------------------------------------------------------------
  1719. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1720. {
  1721. return false;
  1722. }
  1723. //---------------------------------------------------------------------------
  1724. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1725. {
  1726. return NULL;
  1727. }
  1728. //---------------------------------------------------------------------------
  1729. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1730. {
  1731. DebugAssert(GetSide(Side) == osRemote);
  1732. DebugUsedParam(Side);
  1733. return RemoteDirView;
  1734. }
  1735. //---------------------------------------------------------------------------
  1736. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1737. {
  1738. DebugAssert(GetSide(Side) == osRemote);
  1739. DebugUsedParam(Side);
  1740. return RemoteDriveView;
  1741. }
  1742. //---------------------------------------------------------------------------
  1743. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1744. {
  1745. DebugAssert(GetSide(Side) == osRemote);
  1746. DebugUsedParam(Side);
  1747. return HasActiveTerminal();
  1748. }
  1749. //---------------------------------------------------------------------------
  1750. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1751. TOperationSide Side, int FilesOnly)
  1752. {
  1753. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1754. }
  1755. //---------------------------------------------------------------------------
  1756. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1757. TOperationSide Side, int FilesOnly)
  1758. {
  1759. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1760. }
  1761. //---------------------------------------------------------------------------
  1762. struct THistoryItemData
  1763. {
  1764. short int Side;
  1765. short int Index;
  1766. };
  1767. //---------------------------------------------------------------------------
  1768. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1769. {
  1770. DirView(Side)->HistoryGo(Index);
  1771. }
  1772. //---------------------------------------------------------------------------
  1773. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1774. {
  1775. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1776. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1777. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1781. bool Back)
  1782. {
  1783. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1784. {
  1785. TCustomDirView * DView = DirView(Side);
  1786. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1787. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1788. if (ICount > 10)
  1789. {
  1790. ICount = 10;
  1791. }
  1792. Menu->Items->Clear();
  1793. THistoryItemData Data;
  1794. Data.Side = Side;
  1795. for (short int i = 1; i <= ICount; i++)
  1796. {
  1797. TTBCustomItem * Item = new TTBXItem(Menu);
  1798. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1799. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1800. Item->Hint = DView->HistoryPath[Data.Index];
  1801. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1802. Item->Tag = *reinterpret_cast<int*>(&Data);
  1803. Item->OnClick = HistoryItemClick;
  1804. Menu->Items->Add(Item);
  1805. }
  1806. }
  1807. }
  1808. //---------------------------------------------------------------------------
  1809. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1810. TOperationSide Side, bool Back)
  1811. {
  1812. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1813. {
  1814. // workaround
  1815. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1816. // operator new allocates memory in Pascal code, but calls inline
  1817. // contructor in C++, leading in problems, the function does
  1818. // both in Pascal code
  1819. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1820. UpdateHistoryMenu(Side, Back);
  1821. }
  1822. return FHistoryMenu[Side == osLocal][Back];
  1823. }
  1824. //---------------------------------------------------------------------------
  1825. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1826. TCustomDirView *Sender)
  1827. {
  1828. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1829. UpdateHistoryMenu(Side, true);
  1830. UpdateHistoryMenu(Side, false);
  1831. }
  1832. //---------------------------------------------------------------------------
  1833. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1834. {
  1835. // remote custom commands can be executed only if the server supports shell commands
  1836. // or have secondary shell
  1837. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1841. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1842. {
  1843. // -1 = hidden, 0 = disabled, 1 = enabled
  1844. int Result;
  1845. TFileCustomCommand RemoteCustomCommand;
  1846. TLocalCustomCommand LocalCustomCommand;
  1847. TFileCustomCommand * NonInteractiveCustomCommand =
  1848. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1849. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1850. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1851. if (FLAGCLEAR(Command.Params, ccLocal))
  1852. {
  1853. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1854. // custom command that does not operate with files can be executed anytime ...
  1855. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1856. {
  1857. // ... but do not show such command in remote file menu
  1858. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1859. {
  1860. Result = AllowedState;
  1861. }
  1862. else
  1863. {
  1864. Result = -1;
  1865. }
  1866. }
  1867. else
  1868. {
  1869. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1870. {
  1871. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1872. }
  1873. else
  1874. {
  1875. Result = -1;
  1876. }
  1877. }
  1878. }
  1879. else
  1880. {
  1881. // custom command that does not operate with files can be executed anytime
  1882. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1883. {
  1884. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1885. }
  1886. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1887. {
  1888. if ((ListType == ccltAll) || (ListType == ccltFile))
  1889. {
  1890. // special case is "diff"-style command that can be executed over any side,
  1891. // if we have both sides
  1892. Result =
  1893. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1894. // directly (instead of EnableSelectedOperation) to pass
  1895. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1896. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1897. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1898. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1899. }
  1900. else if (ListType == ccltBoth)
  1901. {
  1902. DebugAssert(!IsLocalBrowserMode());
  1903. Result = 1;
  1904. }
  1905. else
  1906. {
  1907. Result = -1;
  1908. }
  1909. }
  1910. else
  1911. {
  1912. if ((ListType == ccltAll) ||
  1913. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1914. {
  1915. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1916. }
  1917. else
  1918. {
  1919. Result = -1;
  1920. }
  1921. }
  1922. if ((Result > 0) &&
  1923. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1924. !HasActiveTerminal())
  1925. {
  1926. Result = 0;
  1927. }
  1928. }
  1929. return Result;
  1930. }
  1931. //---------------------------------------------------------------------------
  1932. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1933. TStrings * FileList, const TCustomCommandType & ACommand,
  1934. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1935. {
  1936. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1937. {
  1938. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1939. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1940. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1941. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1942. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1943. bool Capture =
  1944. FLAGSET(ACommand.Params, ccShowResults) ||
  1945. FLAGSET(ACommand.Params, ccCopyResults) ||
  1946. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1947. TCaptureOutputEvent OutputEvent = NULL;
  1948. DebugAssert(FCapturedLog == NULL);
  1949. if (Capture)
  1950. {
  1951. FCapturedLog = new TStringList();
  1952. OutputEvent = TerminalCaptureLog;
  1953. }
  1954. try
  1955. {
  1956. if (!RemoteCustomCommand.IsFileCommand(Command))
  1957. {
  1958. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1959. OutputEvent);
  1960. }
  1961. else
  1962. {
  1963. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1964. }
  1965. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1966. {
  1967. if (FLAGSET(ACommand.Params, ccCopyResults))
  1968. {
  1969. CopyToClipboard(FCapturedLog);
  1970. }
  1971. if (FLAGSET(ACommand.Params, ccShowResults))
  1972. {
  1973. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1974. }
  1975. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1976. {
  1977. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1978. }
  1979. }
  1980. }
  1981. __finally
  1982. {
  1983. SAFE_DESTROY(FCapturedLog);
  1984. }
  1985. }
  1986. }
  1987. //---------------------------------------------------------------------------
  1988. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1989. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1990. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1991. {
  1992. DebugAssert(!IsLocalBrowserMode());
  1993. TStrings * LocalFileList = NULL;
  1994. TStrings * RemoteFileList = NULL;
  1995. TStrings * RemoteFileListFull = NULL;
  1996. try
  1997. {
  1998. if (LocalFileCommand)
  1999. {
  2000. if (ALocalFileList == NULL)
  2001. {
  2002. DebugAssert(HasDirView[osLocal]);
  2003. // Cannot have focus on both panels, so we have to call AnyFileSelected
  2004. // directly (instead of EnableSelectedOperation) to pass
  2005. // false to FocusedFileOnlyWhenFocused
  2006. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  2007. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  2008. }
  2009. else
  2010. {
  2011. LocalFileList = ALocalFileList;
  2012. }
  2013. if (FileListCommand)
  2014. {
  2015. if (LocalFileList->Count != 1)
  2016. {
  2017. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2018. }
  2019. }
  2020. else
  2021. {
  2022. if ((LocalFileList->Count != 1) &&
  2023. (FileList->Count != 1) &&
  2024. (LocalFileList->Count != FileList->Count))
  2025. {
  2026. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2027. }
  2028. }
  2029. }
  2030. UnicodeString RootTempDir;
  2031. UnicodeString TempDir;
  2032. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2033. if (!RemoteFiles)
  2034. {
  2035. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true, true);
  2036. }
  2037. try
  2038. {
  2039. TDateTimes RemoteFileTimes;
  2040. if (RemoteFiles)
  2041. {
  2042. RemoteFileList = FileList;
  2043. }
  2044. else
  2045. {
  2046. RemoteFileList = new TStringList();
  2047. TMakeLocalFileListParams MakeFileListParam;
  2048. MakeFileListParam.FileList = RemoteFileList;
  2049. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2050. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2051. MakeFileListParam.Recursive =
  2052. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2053. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2054. if (!MakeFileListParam.Recursive)
  2055. {
  2056. RemoteFileTimes.clear();
  2057. RemoteFileListFull = new TStringList();
  2058. MakeFileListParam.FileList = RemoteFileListFull;
  2059. MakeFileListParam.Recursive = true;
  2060. MakeFileListParam.IncludeDirs = false;
  2061. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2062. }
  2063. else
  2064. {
  2065. RemoteFileListFull = RemoteFileList;
  2066. }
  2067. }
  2068. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2069. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2070. if (!NonBlocking)
  2071. {
  2072. int Count;
  2073. if (FileListCommand)
  2074. {
  2075. Count = 1;
  2076. }
  2077. else if (LocalFileCommand)
  2078. {
  2079. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2080. }
  2081. else
  2082. {
  2083. Count = RemoteFileList->Count;
  2084. }
  2085. Progress.Start(foCustomCommand, osRemote, Count);
  2086. DebugAssert(FProgressForm != NULL);
  2087. FProgressForm->ReadOnly = true;
  2088. }
  2089. try
  2090. {
  2091. if (FileListCommand)
  2092. {
  2093. UnicodeString LocalFile;
  2094. // MakeFileList does not delimit filenames
  2095. UnicodeString FileList = MakeFileList(RemoteFileList);
  2096. if (LocalFileCommand)
  2097. {
  2098. DebugAssert(LocalFileList->Count == 1);
  2099. LocalFile = LocalFileList->Strings[0];
  2100. }
  2101. TLocalCustomCommand CustomCommand(Data,
  2102. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2103. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2104. if (NonBlocking)
  2105. {
  2106. DebugAssert(!POutput);
  2107. ExecuteShellChecked(ShellCommand);
  2108. }
  2109. else
  2110. {
  2111. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2112. }
  2113. }
  2114. else if (LocalFileCommand)
  2115. {
  2116. if (LocalFileList->Count == 1)
  2117. {
  2118. UnicodeString LocalFile = LocalFileList->Strings[0];
  2119. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2120. {
  2121. UnicodeString FileName = RemoteFileList->Strings[Index];
  2122. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2123. Progress.SetFile(FileNameForProgress);
  2124. TLocalCustomCommand CustomCommand(Data,
  2125. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2126. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2127. TOnceDoneOperation OnceDoneOperation;
  2128. // Do not unselect anything, as it won't work with two panels anyway
  2129. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2130. }
  2131. }
  2132. else if (RemoteFileList->Count == 1)
  2133. {
  2134. UnicodeString FileName = RemoteFileList->Strings[0];
  2135. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2136. {
  2137. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2138. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2139. Progress.SetFile(LocalFileNameOnly);
  2140. TLocalCustomCommand CustomCommand(
  2141. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2142. FileName, LocalFileName, L"");
  2143. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2144. TOnceDoneOperation OnceDoneOperation;
  2145. // Do not unselect anything, as it won't work with two panels anyway
  2146. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2147. }
  2148. }
  2149. else
  2150. {
  2151. if (LocalFileList->Count != RemoteFileList->Count)
  2152. {
  2153. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2154. }
  2155. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2156. {
  2157. UnicodeString FileName = RemoteFileList->Strings[Index];
  2158. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2159. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2160. Progress.SetFile(LocalFileNameOnly); // sic
  2161. TLocalCustomCommand CustomCommand(
  2162. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2163. FileName, LocalFileName, L"");
  2164. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2165. TOnceDoneOperation OnceDoneOperation;
  2166. // Do not unselect anything, as it won't work with two panels anyway
  2167. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2168. }
  2169. }
  2170. }
  2171. else
  2172. {
  2173. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2174. {
  2175. UnicodeString FileName = RemoteFileList->Strings[Index];
  2176. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2177. Progress.SetFile(FileNameForProgress);
  2178. TLocalCustomCommand CustomCommand(Data,
  2179. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2180. FileName, L"", L"");
  2181. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2182. TOnceDoneOperation OnceDoneOperation;
  2183. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2184. }
  2185. }
  2186. }
  2187. __finally
  2188. {
  2189. if (!NonBlocking)
  2190. {
  2191. Progress.Stop();
  2192. }
  2193. }
  2194. DebugAssert(!FAutoOperation);
  2195. if (!RemoteFiles)
  2196. {
  2197. TempDir = IncludeTrailingBackslash(TempDir);
  2198. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2199. {
  2200. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2201. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2202. // Skip directories, process only nested files.
  2203. // The check is redundant as FileAge fails for directories anyway.
  2204. !DirectoryExists(FileName))
  2205. {
  2206. UnicodeString RemoteDir =
  2207. UnixExtractFileDir(
  2208. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2209. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2210. TDateTime NewTime;
  2211. if (FileAge(FileName, NewTime) &&
  2212. (NewTime != RemoteFileTimes[Index]))
  2213. {
  2214. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2215. TemporaryFileCopyParam(CopyParam);
  2216. CopyParam.FileMask = L"";
  2217. FAutoOperation = true;
  2218. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2219. TemporaryFilesList->Add(FileName);
  2220. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2221. }
  2222. }
  2223. }
  2224. }
  2225. }
  2226. __finally
  2227. {
  2228. FAutoOperation = false;
  2229. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2230. {
  2231. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2232. }
  2233. }
  2234. }
  2235. __finally
  2236. {
  2237. if (RemoteFileList != FileList)
  2238. {
  2239. delete RemoteFileList;
  2240. }
  2241. if (LocalFileList != ALocalFileList)
  2242. {
  2243. delete LocalFileList;
  2244. }
  2245. if (RemoteFileListFull != RemoteFileList)
  2246. {
  2247. delete RemoteFileListFull;
  2248. }
  2249. }
  2250. }
  2251. //---------------------------------------------------------------------------
  2252. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2253. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2254. bool FileListCommand, UnicodeString * POutput)
  2255. {
  2256. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2257. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2258. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2259. {
  2260. UnicodeString FileName = SelectedFileList->Strings[Index];
  2261. if (DirectoryExists(FileName))
  2262. {
  2263. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2264. {
  2265. LocalFileList->Add(FileName);
  2266. }
  2267. if (FLAGSET(ACommand.Params, ccRecursive))
  2268. {
  2269. TMakeLocalFileListParams MakeFileListParam;
  2270. MakeFileListParam.FileList = LocalFileList.get();
  2271. MakeFileListParam.FileTimes = NULL;
  2272. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2273. MakeFileListParam.Recursive = true;
  2274. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2275. }
  2276. }
  2277. else
  2278. {
  2279. LocalFileList->Add(FileName);
  2280. }
  2281. }
  2282. UnicodeString RemotePath;
  2283. if (Terminal != NULL)
  2284. {
  2285. RemotePath = Terminal->CurrentDirectory;
  2286. }
  2287. if (FileListCommand)
  2288. {
  2289. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2290. TLocalCustomCommand CustomCommand(
  2291. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2292. L"", L"", FileList);
  2293. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2294. }
  2295. else
  2296. {
  2297. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2298. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2299. DebugAssert(FProgressForm != NULL);
  2300. FProgressForm->ReadOnly = true;
  2301. try
  2302. {
  2303. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2304. {
  2305. UnicodeString FileName = LocalFileList->Strings[Index];
  2306. Progress.SetFile(FileName);
  2307. TLocalCustomCommand CustomCommand(
  2308. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2309. FileName, L"", L"");
  2310. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2311. TOnceDoneOperation OnceDoneOperation;
  2312. Progress.Finish(FileName, true, OnceDoneOperation);
  2313. }
  2314. }
  2315. __finally
  2316. {
  2317. Progress.Stop();
  2318. }
  2319. }
  2320. }
  2321. //---------------------------------------------------------------------------
  2322. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2323. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2324. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2325. {
  2326. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2327. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2328. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2329. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2330. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2331. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2332. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2333. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2334. std::unique_ptr<UnicodeString> POutput;
  2335. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2336. FLAGSET(ACommand.Params, ccCopyResults))
  2337. {
  2338. POutput.reset(new UnicodeString());
  2339. }
  2340. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  2341. FProgressSide = FCurrentSide;
  2342. if (!LocalCustomCommand.IsFileCommand(Command))
  2343. {
  2344. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2345. }
  2346. // remote files?
  2347. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2348. {
  2349. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2350. }
  2351. // local files
  2352. else
  2353. {
  2354. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2355. }
  2356. if (POutput.get() != NULL)
  2357. {
  2358. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2359. int P = POutput->Pos(sLineBreak);
  2360. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2361. {
  2362. POutput->SetLength(P - 1);
  2363. }
  2364. // Copy even empty output to clipboard
  2365. if (FLAGSET(ACommand.Params, ccCopyResults))
  2366. {
  2367. CopyToClipboard(*POutput);
  2368. }
  2369. // But do not show an empty message box.
  2370. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2371. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2372. !POutput->IsEmpty())
  2373. {
  2374. TClipboardHandler ClipboardHandler;
  2375. ClipboardHandler.Text = *POutput;
  2376. TMessageParams Params;
  2377. TQueryButtonAlias Aliases[1];
  2378. Aliases[0].Button = qaRetry;
  2379. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2380. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2381. Params.Aliases = Aliases;
  2382. Params.AliasesCount = LENOF(Aliases);
  2383. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2384. }
  2385. }
  2386. }
  2387. //---------------------------------------------------------------------------
  2388. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2389. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2390. {
  2391. TCustomCommandData Data;
  2392. UnicodeString Site;
  2393. UnicodeString RemotePath;
  2394. if (HasActiveTerminal())
  2395. {
  2396. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2397. Data = TCustomCommandData(SessionData.get());
  2398. Site = Terminal->SessionData->SessionKey;
  2399. RemotePath = Terminal->CurrentDirectory;
  2400. }
  2401. UnicodeString HelpKeyword = ACommand.HomePage;
  2402. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2403. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2404. {
  2405. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2406. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2407. {
  2408. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2409. }
  2410. else
  2411. {
  2412. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2413. }
  2414. if (!DoCustomCommandOptionsDialog(
  2415. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2416. {
  2417. Abort();
  2418. }
  2419. }
  2420. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2421. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2422. {
  2423. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2424. }
  2425. else
  2426. {
  2427. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2428. }
  2429. }
  2430. //---------------------------------------------------------------------------
  2431. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2432. const TCustomCommandType & Command)
  2433. {
  2434. DebugAssert(FCustomCommandLocalFileList != NULL);
  2435. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2436. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2437. TStrings * LocalFileList = new TStringList();
  2438. TStrings * RemoteFileList = new TStringList();
  2439. try
  2440. {
  2441. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2442. {
  2443. LocalFileList->Clear();
  2444. LocalFileList->AddObject(
  2445. FCustomCommandLocalFileList->Strings[Index],
  2446. FCustomCommandLocalFileList->Objects[Index]);
  2447. RemoteFileList->Clear();
  2448. RemoteFileList->AddObject(
  2449. FCustomCommandRemoteFileList->Strings[Index],
  2450. FCustomCommandRemoteFileList->Objects[Index]);
  2451. CustomCommand(RemoteFileList, Command, LocalFileList);
  2452. }
  2453. }
  2454. __finally
  2455. {
  2456. delete LocalFileList;
  2457. delete RemoteFileList;
  2458. }
  2459. }
  2460. //---------------------------------------------------------------------------
  2461. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2462. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2463. {
  2464. delete FCustomCommandLocalFileList;
  2465. delete FCustomCommandRemoteFileList;
  2466. // takeover ownership,
  2467. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2468. FCustomCommandLocalFileList = LocalFileList;
  2469. FCustomCommandRemoteFileList = RemoteFileList;
  2470. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2471. if (Button != NULL)
  2472. {
  2473. FCustomCommandMenu->Items->Clear();
  2474. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2475. MenuPopup(FCustomCommandMenu, Button);
  2476. }
  2477. else
  2478. {
  2479. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2480. }
  2481. }
  2482. //---------------------------------------------------------------------------
  2483. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2484. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2485. {
  2486. DebugAssert(FCapturedLog != NULL);
  2487. if ((OutputType == cotOutput) || (OutputType == cotError))
  2488. {
  2489. FCapturedLog->Add(AddedLine);
  2490. }
  2491. }
  2492. //---------------------------------------------------------------------------
  2493. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2494. TOperationSide Side)
  2495. {
  2496. return
  2497. (Side == osOther) &&
  2498. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2499. }
  2500. //---------------------------------------------------------------------------
  2501. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2502. TOperationSide Side, TTBXCustomItem * Item,
  2503. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2504. {
  2505. TCustomDirView * DView = DirView(Side);
  2506. bool IsDefault = false;
  2507. if (DView->ItemFocused != NULL)
  2508. {
  2509. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2510. TResolvedDoubleClickAction DefaultAction =
  2511. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2512. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2513. }
  2514. TTBItemOptions O = Item->Options;
  2515. if (IsDefault)
  2516. {
  2517. Item->Options = O << tboDefault;
  2518. }
  2519. else
  2520. {
  2521. Item->Options = O >> tboDefault;
  2522. }
  2523. }
  2524. //---------------------------------------------------------------------------
  2525. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2526. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2527. {
  2528. TCustomDirView * DView = DirView(Side);
  2529. TListItem * Item = DView->ItemFocused;
  2530. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2531. EnableFocusedOperation[Side])
  2532. {
  2533. TPoint ClientPoint;
  2534. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2535. TPoint(0, 0) : MousePos;
  2536. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2537. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2538. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2539. }
  2540. }
  2541. //---------------------------------------------------------------------------
  2542. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2543. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2544. {
  2545. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2546. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2547. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2548. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2549. Handled = true;
  2550. }
  2551. //---------------------------------------------------------------------------
  2552. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2553. {
  2554. }
  2555. //---------------------------------------------------------------------------
  2556. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2557. {
  2558. DebugAssert(FErrorList == NULL);
  2559. if (WinConfiguration->ContinueOnError)
  2560. {
  2561. FErrorList = new TStringList();
  2562. Configuration->Usage->Inc(L"ContinuationsOnError");
  2563. }
  2564. NonVisualDataModule->StartBusy();
  2565. }
  2566. //---------------------------------------------------------------------------
  2567. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2568. {
  2569. NonVisualDataModule->EndBusy();
  2570. if (FErrorList)
  2571. {
  2572. HandleErrorList(FErrorList);
  2573. }
  2574. }
  2575. //---------------------------------------------------------------------------
  2576. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2577. const TCopyParamType & CopyParam)
  2578. {
  2579. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2580. {
  2581. Configuration->Usage->Inc(L"FileMaskUses");
  2582. }
  2583. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2584. {
  2585. Configuration->Usage->Inc(L"OperationMaskUses");
  2586. }
  2587. }
  2588. //---------------------------------------------------------------------------
  2589. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2590. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2591. {
  2592. DebugAssert(!IsLocalBrowserMode());
  2593. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2594. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2595. TTransferOperationParam DefaultParam;
  2596. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2597. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2598. switch (Param.Queue)
  2599. {
  2600. case asOn:
  2601. CopyParam.Queue = true;
  2602. break;
  2603. case asOff:
  2604. CopyParam.Queue = false;
  2605. break;
  2606. case asAuto:
  2607. default:
  2608. // keep default
  2609. break;
  2610. }
  2611. bool Result =
  2612. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2613. if (Result)
  2614. {
  2615. DebugAssert(Terminal);
  2616. bool SelectionRestored = false;
  2617. TCustomDirView * DView = NULL;
  2618. if (HasDirView[Side])
  2619. {
  2620. DView = DirView(Side);
  2621. DView->SaveSelection();
  2622. DView->SaveSelectedNames();
  2623. }
  2624. UpdateCopyParamCounters(CopyParam);
  2625. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2626. DebugAssert(FTransferResumeList == NULL);
  2627. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2628. FMoveToQueue = false;
  2629. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2630. try
  2631. {
  2632. TStrings * PermanentFileList;
  2633. std::unique_ptr<TStrings> PermanentFileListOwner;
  2634. try
  2635. {
  2636. if (Side == osLocal)
  2637. {
  2638. PermanentFileList = FileList;
  2639. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2640. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2641. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2642. if (Operation == foMove)
  2643. {
  2644. ReloadLocalDirectory();
  2645. if (DView != NULL)
  2646. {
  2647. DView->RestoreSelection();
  2648. }
  2649. SelectionRestored = true;
  2650. }
  2651. }
  2652. else
  2653. {
  2654. // Clone the file list as it may refer to current directory files,
  2655. // which get destroyed, when the source directory is reloaded after foMove operation.
  2656. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2657. // But for a hotfix, we are not going to do such a big change.
  2658. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2659. PermanentFileList = PermanentFileListOwner.get();
  2660. try
  2661. {
  2662. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2663. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2664. }
  2665. __finally
  2666. {
  2667. if (Operation == foMove)
  2668. {
  2669. if (DView != NULL)
  2670. {
  2671. DView->RestoreSelection();
  2672. }
  2673. SelectionRestored = true;
  2674. }
  2675. ReloadLocalDirectory(Param.TargetDirectory);
  2676. }
  2677. }
  2678. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2679. if (FMoveToQueue)
  2680. {
  2681. Abort();
  2682. }
  2683. }
  2684. catch (EAbort &)
  2685. {
  2686. if (FMoveToQueue)
  2687. {
  2688. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2689. DebugAssert(CopyParam.TransferSkipList == NULL);
  2690. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2691. if (TransferResumeList->Count > 0)
  2692. {
  2693. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2694. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2695. }
  2696. CopyParam.TransferSkipList = TransferResumeList.release();
  2697. // not really needed, just to keep it consistent with TransferResumeList
  2698. FTransferResumeList = NULL;
  2699. FMoveToQueue = false;
  2700. Configuration->Usage->Inc("MovesToBackground");
  2701. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2702. ClearTransferSourceSelection(Direction);
  2703. }
  2704. throw;
  2705. }
  2706. }
  2707. __finally
  2708. {
  2709. if (!SelectionRestored && (DView != NULL))
  2710. {
  2711. DView->DiscardSavedSelection();
  2712. }
  2713. FTransferResumeList = NULL;
  2714. }
  2715. }
  2716. return Result;
  2717. }
  2718. //---------------------------------------------------------------------------
  2719. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2720. TOperationSide Side, TStrings * FileList, void * Param)
  2721. {
  2722. DebugAssert(FileList->Count);
  2723. // We deliberately do not toggle alternative flag (Param), but use OR,
  2724. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2725. // shortcut of CurrentDeleteAlternativeAction
  2726. bool Alternative =
  2727. bool(Param) || UseAlternativeFunction();
  2728. bool Recycle;
  2729. if (IsSideLocalBrowser(Side))
  2730. {
  2731. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2732. }
  2733. else
  2734. {
  2735. Recycle =
  2736. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2737. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2738. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2739. }
  2740. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2741. if (!Result)
  2742. {
  2743. UnicodeString Query;
  2744. if (FileList->Count == 1)
  2745. {
  2746. if (IsSideLocalBrowser(Side))
  2747. {
  2748. Query = ExtractFileName(FileList->Strings[0]);
  2749. }
  2750. else
  2751. {
  2752. Query = UnixExtractFileName(FileList->Strings[0]);
  2753. }
  2754. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2755. }
  2756. else
  2757. {
  2758. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2759. }
  2760. TMessageParams Params(mpNeverAskAgainCheck);
  2761. Params.ImageName = L"Delete file";
  2762. unsigned int Answer =
  2763. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2764. if (Answer == qaNeverAskAgain)
  2765. {
  2766. Result = true;
  2767. if (Recycle)
  2768. {
  2769. WinConfiguration->ConfirmRecycling = false;
  2770. }
  2771. else
  2772. {
  2773. WinConfiguration->ConfirmDeleting = false;
  2774. }
  2775. }
  2776. else
  2777. {
  2778. Result = (Answer == qaOK);
  2779. }
  2780. }
  2781. if (Result)
  2782. {
  2783. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2784. }
  2785. return Result;
  2786. }
  2787. //---------------------------------------------------------------------------
  2788. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2789. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2790. {
  2791. TAutoBatch AutoBatch(this);
  2792. bool Result;
  2793. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2794. {
  2795. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2796. }
  2797. else if (Operation == foRename)
  2798. {
  2799. DebugAssert(DirView(Side)->ItemFocused);
  2800. DirView(Side)->ItemFocused->EditCaption();
  2801. Result = true;
  2802. }
  2803. else if (Operation == foDelete)
  2804. {
  2805. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2806. }
  2807. else if (Operation == foSetProperties)
  2808. {
  2809. DirView(osRemote)->SaveSelectedNames();
  2810. Result = SetProperties(Side, FileList);
  2811. }
  2812. else if (Operation == foCustomCommand)
  2813. {
  2814. DebugAssert(Param);
  2815. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2816. DirView(osRemote)->SaveSelectedNames();
  2817. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2818. CustomCommand(FileList, *Command, NULL);
  2819. Result = true;
  2820. }
  2821. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2822. {
  2823. DebugAssert(!IsSideLocalBrowser(Side));
  2824. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2825. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2826. }
  2827. else if (Operation == foLock)
  2828. {
  2829. DebugAssert(!IsSideLocalBrowser(Side));
  2830. LockFiles(FileList, true);
  2831. Result = true;
  2832. }
  2833. else if (Operation == foUnlock)
  2834. {
  2835. DebugAssert(!IsSideLocalBrowser(Side));
  2836. LockFiles(FileList, false);
  2837. Result = true;
  2838. }
  2839. else
  2840. {
  2841. DebugFail();
  2842. }
  2843. return Result;
  2844. }
  2845. //---------------------------------------------------------------------------
  2846. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2847. {
  2848. if (Side == osCurrent)
  2849. {
  2850. Side = FCurrentSide;
  2851. }
  2852. return Side;
  2853. }
  2854. //---------------------------------------------------------------------------
  2855. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2856. {
  2857. TOperationSide Result;
  2858. switch (GetSide(Side))
  2859. {
  2860. case osLocal:
  2861. Result = osOther;
  2862. break;
  2863. case osOther:
  2864. Result = osLocal;
  2865. break;
  2866. default:
  2867. DebugFail();
  2868. Abort();
  2869. }
  2870. return Result;
  2871. }
  2872. //---------------------------------------------------------------------------
  2873. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2874. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2875. {
  2876. Side = GetSide(Side);
  2877. bool FullPath = IsSideLocalBrowser(Side);
  2878. TCustomDirView * ADirView = DirView(Side);
  2879. std::unique_ptr<TStringList> FileList(new TStringList());
  2880. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2881. bool ReloadProperties =
  2882. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2883. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2884. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2885. if (Result && ReloadProperties)
  2886. {
  2887. std::unique_ptr<TStringList> FileList2(new TStringList());
  2888. FileList->CaseSensitive = true;
  2889. FileList->Sort();
  2890. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2891. {
  2892. TListItem * Item = ADirView->Items->Item[Index];
  2893. UnicodeString FileName = ADirView->ItemFileName(Item);
  2894. int Index2;
  2895. if (FileList->Find(FileName, Index2))
  2896. {
  2897. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2898. }
  2899. }
  2900. LoadFilesProperties(FileList2.get());
  2901. }
  2902. return Result;
  2903. }
  2904. //---------------------------------------------------------------------------
  2905. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2906. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2907. bool NoConfirmation, void * Param)
  2908. {
  2909. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2910. {
  2911. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2912. {
  2913. DebugAssert(!IsLocalBrowserMode());
  2914. if (GetSide(Side) == osLocal)
  2915. {
  2916. Configuration->Usage->Inc(L"UploadsCommand");
  2917. }
  2918. else
  2919. {
  2920. Configuration->Usage->Inc(L"DownloadsCommand");
  2921. }
  2922. }
  2923. }
  2924. }
  2925. //---------------------------------------------------------------------------
  2926. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2927. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2928. {
  2929. TTransferOperationParam Param;
  2930. if ((WinConfiguration->Interface != ifCommander) ||
  2931. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2932. {
  2933. Flags &= ~cocShortCutHint;
  2934. }
  2935. TCustomDirView * DView = DirView(Side);
  2936. Param.Options =
  2937. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2938. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2939. if (FLAGSET(Flags, cocQueue))
  2940. {
  2941. Param.Queue = asOn;
  2942. }
  2943. else if (FLAGSET(Flags, cocNonQueue))
  2944. {
  2945. Param.Queue = asOff;
  2946. }
  2947. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2948. }
  2949. //---------------------------------------------------------------------------
  2950. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2951. {
  2952. int Count = ErrorList->Count;
  2953. try
  2954. {
  2955. if (ErrorList->Count)
  2956. {
  2957. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2958. if (MessageDialog(Message, qtError,
  2959. qaOK | qaCancel, HELP_NONE) == qaOK)
  2960. {
  2961. unsigned int Answer;
  2962. int Index = 0;
  2963. do
  2964. {
  2965. DebugAssert(Index >= 0 && Index < Count);
  2966. TQueryButtonAlias Aliases[2];
  2967. Aliases[0].Button = qaYes;
  2968. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2969. Aliases[1].Button = qaNo;
  2970. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2971. TMessageParams Params;
  2972. Params.Aliases = Aliases;
  2973. Params.AliasesCount = LENOF(Aliases);
  2974. int No = Index + 1;
  2975. UnicodeString Message = ErrorList->Strings[Index];
  2976. UnicodeString AMainInstructions;
  2977. UnicodeString Details;
  2978. if (ExtractMainInstructions(Message, AMainInstructions))
  2979. {
  2980. Details = Message;
  2981. Message = AMainInstructions;
  2982. }
  2983. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2984. Answer = MoreMessageDialog(
  2985. Message,
  2986. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2987. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2988. qaOK, HELP_NONE, &Params);
  2989. if (Answer == qaNo)
  2990. {
  2991. Index++;
  2992. }
  2993. if (Answer == qaYes)
  2994. {
  2995. Index--;
  2996. }
  2997. }
  2998. while (Answer != qaOK);
  2999. }
  3000. }
  3001. }
  3002. __finally
  3003. {
  3004. TStrings * List = ErrorList;
  3005. ErrorList = NULL;
  3006. for (int i = 0; i < Count; i++)
  3007. {
  3008. delete List->Objects[i];
  3009. }
  3010. delete List;
  3011. }
  3012. }
  3013. //---------------------------------------------------------------------------
  3014. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3015. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3016. {
  3017. // needed for checking filemasks, as there's no directory object
  3018. // associated with the file object
  3019. File->FullFileName = FullFileName;
  3020. TFileMasks::TParams MaskParams;
  3021. MaskParams.Size = File->Size;
  3022. MaskParams.Modification = File->Modification;
  3023. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3024. }
  3025. //---------------------------------------------------------------------------
  3026. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3027. {
  3028. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3029. Side = GetSide(Side);
  3030. TCustomDirView * DView = DirView(Side);
  3031. TListItem * FocusedItem = DView->ItemFocused;
  3032. UnicodeString Name;
  3033. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3034. {
  3035. Name = DView->ItemFileName(FocusedItem);
  3036. }
  3037. else
  3038. {
  3039. Name = LoadStr(NEW_FILE);
  3040. }
  3041. UnicodeString Names = Name;
  3042. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3043. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3044. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  3045. {
  3046. while (!Names.IsEmpty())
  3047. {
  3048. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3049. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3050. UnicodeString TargetFileName;
  3051. UnicodeString LocalFileName;
  3052. UnicodeString RootTempDir;
  3053. UnicodeString TempDir;
  3054. UnicodeString RemoteDirectory;
  3055. bool ExistingFile = false;
  3056. if (!IsSideLocalBrowser(Side))
  3057. {
  3058. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3059. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3060. if ((File.get() != NULL) &&
  3061. !File->IsDirectory)
  3062. {
  3063. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3064. ExistingFile = true;
  3065. }
  3066. File.reset(NULL);
  3067. if (!ExistingFile)
  3068. {
  3069. RemoteDirectory = UnixExtractFilePath(Name);
  3070. TemporaryDirectoryForRemoteFiles(
  3071. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3072. TargetFileName = UnixExtractFileName(Name);
  3073. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3074. LocalFileName = TempDir +
  3075. // We probably do not want to trim the VMS version here
  3076. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3077. }
  3078. }
  3079. else
  3080. {
  3081. if (ExtractFilePath(Name).IsEmpty())
  3082. {
  3083. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3084. }
  3085. else
  3086. {
  3087. LocalFileName = ExpandFileName(Name);
  3088. }
  3089. TargetFileName = ExtractFileName(Name);
  3090. }
  3091. if (!ExistingFile)
  3092. {
  3093. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3094. if (NewFile)
  3095. {
  3096. int File = FileCreate(ApiPath(LocalFileName));
  3097. if (File < 0)
  3098. {
  3099. if (!RootTempDir.IsEmpty())
  3100. {
  3101. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3102. }
  3103. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3104. }
  3105. else
  3106. {
  3107. FileClose(File);
  3108. }
  3109. }
  3110. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3111. const TEditorData * ExternalEditor = NULL;
  3112. TFileMasks::TParams MaskParams; // size not known
  3113. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3114. false, MaskParams);
  3115. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3116. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3117. }
  3118. }
  3119. }
  3120. }
  3121. //---------------------------------------------------------------------------
  3122. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3123. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3124. {
  3125. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3126. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3127. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3128. return
  3129. ((ExecuteFileBy == efInternalEditor)) ||
  3130. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3131. }
  3132. //---------------------------------------------------------------------------
  3133. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3134. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3135. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3136. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3137. {
  3138. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3139. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3140. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3141. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3142. Side = GetSide(Side);
  3143. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3144. if (!IsSideLocalBrowser(Side))
  3145. {
  3146. Data->Terminal = Terminal;
  3147. Data->Queue = Queue;
  3148. Data->SessionData = CloneCurrentSessionData();
  3149. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3150. Data->RemoteDirectory = RemoteDirectory;
  3151. Data->SessionName = Terminal->SessionData->SessionName;
  3152. Data->LocalRootDirectory = LocalRootDirectory;
  3153. Data->OriginalFileName = OriginalFileName;
  3154. Data->Command = L""; // will be changed later for external editor
  3155. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3156. if (WinConfiguration->EditorCheckNotModified)
  3157. {
  3158. Data->SourceTimestamp = SourceTimestamp;
  3159. }
  3160. }
  3161. if (ExecuteFileBy == efInternalEditor)
  3162. {
  3163. if (!IsSideLocalBrowser(Side))
  3164. {
  3165. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3166. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3167. TForm * Editor;
  3168. try
  3169. {
  3170. Editor =
  3171. ShowEditorForm(
  3172. FileName, this,
  3173. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3174. SaveAllInternalEditors, AnyInternalEditorModified,
  3175. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3176. }
  3177. catch(...)
  3178. {
  3179. if (!LocalRootDirectory.IsEmpty())
  3180. {
  3181. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3182. }
  3183. throw;
  3184. }
  3185. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3186. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3187. }
  3188. else
  3189. {
  3190. DebugAssert(!StandaloneOperation);
  3191. TForm * Editor =
  3192. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3193. SaveAllInternalEditors, AnyInternalEditorModified,
  3194. L"", false, SessionColor, -1, NewFile);
  3195. FLocalEditors->Add(Editor);
  3196. }
  3197. }
  3198. else
  3199. {
  3200. HANDLE Process;
  3201. if (ExecuteFileBy == efExternalEditor)
  3202. {
  3203. UnicodeString Program, Params, Dir;
  3204. Data->Command = ExternalEditor->ExternalEditor;
  3205. ReformatFileNameCommand(Data->Command);
  3206. SplitCommand(Data->Command, Program, Params, Dir);
  3207. Params = ExpandFileNameCommand(Params, FileName);
  3208. Program = ExpandEnvironmentVariables(Program);
  3209. if (!ExecuteShell(Program, Params, Process))
  3210. {
  3211. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3212. }
  3213. }
  3214. else
  3215. {
  3216. DebugAssert(!IsSideLocalBrowser(Side));
  3217. if (!ExecuteShell(FileName, L"", Process))
  3218. {
  3219. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3220. }
  3221. }
  3222. if (IsSideLocalBrowser(Side) ||
  3223. ((ExecuteFileBy == efShell) &&
  3224. !WinConfiguration->Editor.SDIShellEditor) ||
  3225. ((ExecuteFileBy == efExternalEditor) &&
  3226. !ExternalEditor->SDIExternalEditor))
  3227. {
  3228. // no need for handle
  3229. if (Process != NULL)
  3230. {
  3231. DebugCheck(CloseHandle(Process));
  3232. }
  3233. Process = INVALID_HANDLE_VALUE;
  3234. }
  3235. else
  3236. {
  3237. if (Process == NULL)
  3238. {
  3239. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3240. }
  3241. }
  3242. if (!IsSideLocalBrowser(Side))
  3243. {
  3244. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3245. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3246. }
  3247. }
  3248. }
  3249. //---------------------------------------------------------------------------
  3250. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3251. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3252. void * /*Arg*/)
  3253. {
  3254. if (Token != NULL)
  3255. {
  3256. EditorFormFileSave(static_cast<TForm *>(Token));
  3257. }
  3258. }
  3259. //---------------------------------------------------------------------------
  3260. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3261. {
  3262. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3263. {
  3264. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3265. }
  3266. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3267. }
  3268. //---------------------------------------------------------------------------
  3269. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3270. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3271. void * Arg)
  3272. {
  3273. if ((Token != NULL) &&
  3274. IsEditorFormModified(static_cast<TForm *>(Token)))
  3275. {
  3276. *static_cast<bool *>(Arg) = true;
  3277. }
  3278. }
  3279. //---------------------------------------------------------------------------
  3280. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3281. TObject * /*Sender*/, bool & Modified)
  3282. {
  3283. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3284. {
  3285. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3286. {
  3287. Modified = true;
  3288. }
  3289. }
  3290. if (!Modified)
  3291. {
  3292. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3293. }
  3294. }
  3295. //---------------------------------------------------------------------------
  3296. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3297. {
  3298. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3299. }
  3300. //---------------------------------------------------------------------------
  3301. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3302. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3303. UnicodeString & Result, UnicodeString & RootDirectory)
  3304. {
  3305. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3306. {
  3307. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3308. Result = RootDirectory;
  3309. }
  3310. else
  3311. {
  3312. RootDirectory = L"";
  3313. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3314. Result = IncludeTrailingBackslash(Result);
  3315. }
  3316. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3317. {
  3318. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3319. }
  3320. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3321. {
  3322. UnicodeString ARemoteDirectory = RemoteDirectory;
  3323. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3324. {
  3325. ARemoteDirectory.Delete(1, 1);
  3326. }
  3327. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3328. }
  3329. if (!ForceDirectories(ApiPath(Result)))
  3330. {
  3331. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3332. }
  3333. }
  3334. //---------------------------------------------------------------------------
  3335. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3336. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3337. bool GetTargetNames, bool AutoOperation, bool SimpleTempDir)
  3338. {
  3339. DebugAssert(!IsLocalBrowserMode());
  3340. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3341. if (ForceText)
  3342. {
  3343. CopyParam.TransferMode = tmAscii;
  3344. }
  3345. TemporaryFileCopyParam(CopyParam);
  3346. if (TempDir.IsEmpty())
  3347. {
  3348. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3349. }
  3350. DebugAssert(!FAutoOperation);
  3351. FAutoOperation = AutoOperation;
  3352. Terminal->ExceptionOnFail = true;
  3353. try
  3354. {
  3355. try
  3356. {
  3357. // turn off confirmations, as for MDI editors we may possibly download
  3358. // the same file over
  3359. Terminal->CopyToLocal(
  3360. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3361. if (GetTargetNames)
  3362. {
  3363. for (int i = 0; i < FileList->Count; i++)
  3364. {
  3365. FileList->Strings[i] =
  3366. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3367. }
  3368. }
  3369. }
  3370. catch(...)
  3371. {
  3372. if (!RootTempDir.IsEmpty())
  3373. {
  3374. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3375. }
  3376. throw;
  3377. }
  3378. }
  3379. __finally
  3380. {
  3381. FAutoOperation = false;
  3382. Terminal->ExceptionOnFail = false;
  3383. }
  3384. }
  3385. //---------------------------------------------------------------------------
  3386. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3387. {
  3388. // Do not waste time checking for default editor list the next time,
  3389. // or testing if default editor is not notepad.
  3390. bool TryNextTime = false;
  3391. UnicodeString UsageState;
  3392. if (!WinConfiguration->EditorList->IsDefaultList())
  3393. {
  3394. UsageState = "H";
  3395. }
  3396. else
  3397. {
  3398. UnicodeString Executable;
  3399. UnicodeString ExecutableDescription;
  3400. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3401. {
  3402. UnicodeString Message =
  3403. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3404. unsigned int Answer =
  3405. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3406. if (Answer != qaOK)
  3407. {
  3408. UsageState = "R";
  3409. }
  3410. else
  3411. {
  3412. UsageState = "A";
  3413. TEditorData EditorData;
  3414. EditorData.Editor = edExternal;
  3415. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3416. EditorData.ExternalEditorOptionsAutodetect();
  3417. TEditorList EditorList;
  3418. EditorList = *WinConfiguration->EditorList;
  3419. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3420. WinConfiguration->EditorList = &EditorList;
  3421. }
  3422. }
  3423. }
  3424. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3425. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3426. }
  3427. //---------------------------------------------------------------------------
  3428. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3429. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3430. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3431. {
  3432. if (ExecuteFileBy == efDefaultEditor)
  3433. {
  3434. if (!WinConfiguration->OfferedEditorAutoConfig)
  3435. {
  3436. EditorAutoConfig();
  3437. }
  3438. const TEditorPreferences * Editor =
  3439. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3440. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3441. {
  3442. ExecuteFileBy = efInternalEditor;
  3443. ExternalEditor = NULL;
  3444. }
  3445. else if (Editor->Data->Editor == edOpen)
  3446. {
  3447. ExecuteFileBy = efShell;
  3448. ExternalEditor = NULL;
  3449. }
  3450. else
  3451. {
  3452. ExecuteFileBy = efExternalEditor;
  3453. ExternalEditor = Editor->Data;
  3454. }
  3455. }
  3456. }
  3457. //---------------------------------------------------------------------------
  3458. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3459. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3460. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3461. {
  3462. UnicodeString OriginalFileName;
  3463. UnicodeString LocalRootDirectory;
  3464. UnicodeString RemoteDirectory;
  3465. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3466. IsSideLocalBrowser(Side), MaskParams);
  3467. UnicodeString Counter;
  3468. UnicodeString LocalFileName;
  3469. bool Handled = false;
  3470. if (!IsSideLocalBrowser(Side))
  3471. {
  3472. // We need to trim VMS version here, so that we use name without version
  3473. // when uploading back to create a new version of the file
  3474. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3475. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3476. TObject * Token = NULL;
  3477. UnicodeString LocalDirectory;
  3478. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3479. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3480. LocalDirectory))
  3481. {
  3482. if (Token != NULL)
  3483. {
  3484. TForm * Form = dynamic_cast<TForm *>(Token);
  3485. if (Form->WindowState == wsMinimized)
  3486. {
  3487. ShowWindow(Form->Handle, SW_RESTORE);
  3488. }
  3489. else
  3490. {
  3491. Form->SetFocus();
  3492. }
  3493. Handled = true;
  3494. }
  3495. else
  3496. {
  3497. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3498. }
  3499. }
  3500. if (!Handled)
  3501. {
  3502. TStringList * FileList1 = new TStringList();
  3503. try
  3504. {
  3505. FileList1->AddObject(FullFileName, Object);
  3506. TemporarilyDownloadFiles(FileList1,
  3507. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3508. LocalRootDirectory, LocalDirectory, true, true, false);
  3509. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3510. }
  3511. __finally
  3512. {
  3513. delete FileList1;
  3514. }
  3515. switch (ExecuteFileBy)
  3516. {
  3517. case efShell:
  3518. Counter = "RemoteFilesExecuted";
  3519. break;
  3520. case efInternalEditor:
  3521. Counter = "RemoteFilesOpenedInInternalEditor";
  3522. break;
  3523. case efExternalEditor:
  3524. Counter = "RemoteFilesOpenedInExternalEditor";
  3525. break;
  3526. default:
  3527. DebugFail();
  3528. }
  3529. }
  3530. }
  3531. else
  3532. {
  3533. LocalFileName = FullFileName;
  3534. OriginalFileName = ExtractFileName(FullFileName);
  3535. switch (ExecuteFileBy)
  3536. {
  3537. case efShell:
  3538. Counter = "LocalFilesExecuted";
  3539. break;
  3540. case efInternalEditor:
  3541. Counter = "LocalFilesOpenedInInternalEditor";
  3542. break;
  3543. case efExternalEditor:
  3544. Counter = "LocalFilesOpenedInExternalEditor";
  3545. break;
  3546. default:
  3547. DebugFail();
  3548. }
  3549. }
  3550. if (!Handled)
  3551. {
  3552. Configuration->Usage->Inc(Counter);
  3553. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3554. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3555. }
  3556. }
  3557. //---------------------------------------------------------------------------
  3558. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3559. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3560. bool AllSelected, bool OnFocused)
  3561. {
  3562. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3563. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3564. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3565. Side = GetSide(Side);
  3566. TCustomDirView * DView = DirView(Side);
  3567. TStrings * FileList =
  3568. AllSelected ?
  3569. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3570. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3571. try
  3572. {
  3573. DebugAssert(AllSelected || (FileList->Count == 1));
  3574. for (int i = 0; i < FileList->Count; i++)
  3575. {
  3576. UnicodeString ListFileName = FileList->Strings[i];
  3577. UnicodeString FileNameOnly =
  3578. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3579. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3580. if (!DView->ItemIsDirectory(Item))
  3581. {
  3582. UnicodeString FullFileName;
  3583. if (!IsSideLocalBrowser(Side))
  3584. {
  3585. FullFileName = DirView(Side)->Path + ListFileName;
  3586. }
  3587. else
  3588. {
  3589. FullFileName = ListFileName;
  3590. }
  3591. TObject * Object = FileList->Objects[i];
  3592. TFileMasks::TParams MaskParams;
  3593. MaskParams.Size = DView->ItemFileSize(Item);
  3594. TDateTimePrecision Precision;
  3595. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3596. std::unique_ptr<TRemoteFile> File;
  3597. if (!IsSideLocalBrowser(Side))
  3598. {
  3599. File.reset(Terminal->TryReadFile(FullFileName));
  3600. if (File.get() != NULL)
  3601. {
  3602. File->FullFileName = FullFileName;
  3603. Object = File.get();
  3604. MaskParams.Size = File->Size;
  3605. MaskParams.Modification = File->Modification;
  3606. }
  3607. }
  3608. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3609. }
  3610. }
  3611. }
  3612. __finally
  3613. {
  3614. delete FileList;
  3615. }
  3616. }
  3617. //---------------------------------------------------------------------------
  3618. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3619. {
  3620. CopyParam.FileNameCase = ncNoChange;
  3621. CopyParam.PreserveRights = false;
  3622. CopyParam.PreserveReadOnly = false;
  3623. CopyParam.ReplaceInvalidChars = true;
  3624. CopyParam.IncludeFileMask = TFileMasks();
  3625. CopyParam.NewerOnly = false;
  3626. CopyParam.FileMask = L"";
  3627. }
  3628. //---------------------------------------------------------------------------
  3629. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3630. {
  3631. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3632. }
  3633. //---------------------------------------------------------------------------
  3634. class TEditorUploadQueueItem : public TUploadQueueItem
  3635. {
  3636. public:
  3637. __fastcall TEditorUploadQueueItem(
  3638. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3639. const TCopyParamType * CopyParam, int Params) :
  3640. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, true, false)
  3641. {
  3642. }
  3643. protected:
  3644. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3645. {
  3646. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3647. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3648. }
  3649. };
  3650. //---------------------------------------------------------------------------
  3651. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3652. {
  3653. if (WinConfiguration->EditorCheckNotModified) // optimization
  3654. {
  3655. UnicodeString RemoteFilePath;
  3656. {
  3657. TGuard Guard(FEditorManager->Section);
  3658. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3659. if (DebugAlwaysTrue(Data != NULL) &&
  3660. EditorCheckNotModified(Data))
  3661. {
  3662. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3663. }
  3664. }
  3665. if (!RemoteFilePath.IsEmpty())
  3666. {
  3667. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3668. if (File.get() != NULL)
  3669. {
  3670. TGuard Guard(FEditorManager->Section);
  3671. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3672. if (DebugAlwaysTrue(Data != NULL))
  3673. {
  3674. Data->SourceTimestamp = File->Modification;
  3675. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3676. }
  3677. }
  3678. }
  3679. }
  3680. }
  3681. //---------------------------------------------------------------------------
  3682. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3683. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3684. {
  3685. TTerminalManager * Manager = TTerminalManager::Instance();
  3686. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3687. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3688. {
  3689. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3690. Retry = true;
  3691. }
  3692. else if (!IsActiveTerminal(Data->Terminal))
  3693. {
  3694. if (!NonVisualDataModule->Busy)
  3695. {
  3696. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3697. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3698. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3699. if (Data->Terminal == NULL)
  3700. {
  3701. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3702. if (SameSiteTerminal != NULL)
  3703. {
  3704. UnicodeString Message =
  3705. FMTLOAD(EDIT_SESSION_REATTACH,
  3706. (FileNameOnly, Data->SessionName, FileNameOnly));
  3707. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3708. {
  3709. Data->Terminal = SameSiteTerminal;
  3710. Data->Queue = Manager->FindQueueForTerminal(SameSiteTerminal);
  3711. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3712. // We might also overwrite session data
  3713. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3714. }
  3715. else
  3716. {
  3717. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3718. Abort();
  3719. }
  3720. }
  3721. }
  3722. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3723. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3724. {
  3725. UnicodeString Message =
  3726. MainInstructions(
  3727. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3728. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3729. {
  3730. if (Terminal->Disconnected)
  3731. {
  3732. Manager->ActiveSession = Terminal;
  3733. ReconnectSession();
  3734. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3735. if (IsActiveTerminal(Data->Terminal) && (Terminal == Data->Terminal))
  3736. {
  3737. Data->Queue = Manager->FindQueueForTerminal(Terminal);
  3738. }
  3739. else
  3740. {
  3741. Abort();
  3742. }
  3743. }
  3744. else
  3745. {
  3746. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3747. }
  3748. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3749. }
  3750. else
  3751. {
  3752. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3753. Abort();
  3754. }
  3755. }
  3756. }
  3757. if (!IsActiveTerminal(Data->Terminal))
  3758. {
  3759. Configuration->Usage->Inc(L"EditInactiveSession");
  3760. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3761. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3762. (ExtractFileName(FileName), Data->SessionName)));
  3763. }
  3764. }
  3765. if (!Retry && EditorCheckNotModified(Data))
  3766. {
  3767. if (NonVisualDataModule->Busy)
  3768. {
  3769. Retry = true;
  3770. }
  3771. else
  3772. {
  3773. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3774. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3775. if (File.get() != NULL)
  3776. {
  3777. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3778. if (File->Modification != Data->SourceTimestamp)
  3779. {
  3780. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3781. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3782. {
  3783. Abort();
  3784. }
  3785. }
  3786. }
  3787. }
  3788. }
  3789. if (!Retry)
  3790. {
  3791. TStrings * FileList = new TStringList();
  3792. try
  3793. {
  3794. FileList->Add(FileName);
  3795. // Consider using the same settings (preset) as when the file was downloaded.
  3796. // More over this does not reflect the actual session that will do the upload.
  3797. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3798. TemporaryFileCopyParam(CopyParam);
  3799. if (Data->ForceText)
  3800. {
  3801. CopyParam.TransferMode = tmAscii;
  3802. }
  3803. // so i do not need to worry if masking algorithm works in all cases
  3804. // ("" means "copy file name", no masking is actually done)
  3805. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3806. {
  3807. CopyParam.FileMask = L"";
  3808. }
  3809. else
  3810. {
  3811. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3812. }
  3813. int Params = cpNoConfirmation | cpTemporary;
  3814. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3815. {
  3816. if (DebugAlwaysFalse(Data->Queue == NULL))
  3817. {
  3818. throw EInvalidOperation(L"Transfer queue invalidated");
  3819. }
  3820. if (DebugAlwaysFalse(Data->Queue != Manager->FindQueueForTerminal(Data->Terminal)))
  3821. {
  3822. throw EInvalidOperation(L"Transfer queue does not match session");
  3823. }
  3824. TQueueItem * QueueItem =
  3825. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3826. QueueItem->CompleteEvent = UploadCompleteEvent;
  3827. AddQueueItem(Data->Queue, QueueItem, Data->Terminal);
  3828. }
  3829. else
  3830. {
  3831. if (NonVisualDataModule->Busy)
  3832. {
  3833. Retry = true;
  3834. }
  3835. else
  3836. {
  3837. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3838. SetEvent(UploadCompleteEvent);
  3839. }
  3840. }
  3841. }
  3842. __finally
  3843. {
  3844. delete FileList;
  3845. }
  3846. }
  3847. }
  3848. //---------------------------------------------------------------------------
  3849. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3850. const UnicodeString & FileName, TEditedFileData * Data)
  3851. {
  3852. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3853. DebugAssert(!NonVisualDataModule->Busy);
  3854. if (!IsActiveTerminal(Data->Terminal))
  3855. {
  3856. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3857. (ExtractFileName(FileName), Data->SessionName)));
  3858. }
  3859. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3860. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3861. NonVisualDataModule->StartBusy();
  3862. try
  3863. {
  3864. std::unique_ptr<TRemoteFile> File;
  3865. UnicodeString RemoteFileName =
  3866. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3867. Terminal->ExceptionOnFail = true;
  3868. try
  3869. {
  3870. File.reset(Terminal->ReadFile(RemoteFileName));
  3871. if (!File->HaveFullFileName)
  3872. {
  3873. File->FullFileName = RemoteFileName;
  3874. }
  3875. }
  3876. __finally
  3877. {
  3878. Terminal->ExceptionOnFail = false;
  3879. }
  3880. std::unique_ptr<TStrings> FileList(new TStringList());
  3881. FileList->AddObject(RemoteFileName, File.get());
  3882. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3883. UnicodeString TempDir = ExtractFilePath(FileName);
  3884. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true, false);
  3885. if (EditorCheckNotModified(Data))
  3886. {
  3887. Data->SourceTimestamp = File->Modification;
  3888. }
  3889. // sanity check, the target file name should be still the same
  3890. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3891. }
  3892. __finally
  3893. {
  3894. NonVisualDataModule->EndBusy();
  3895. // it actually may not exist anymore...
  3896. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3897. }
  3898. }
  3899. //---------------------------------------------------------------------------
  3900. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3901. const TEditedFileData * Data, bool & KeepOpen)
  3902. {
  3903. // Command is set for external editors only (not for "shell" open).
  3904. if (!Data->Command.IsEmpty())
  3905. {
  3906. bool AnyFound = false;
  3907. bool AnyMDI = false;
  3908. bool AnyNonMDI = false;
  3909. bool AnyDetect = false;
  3910. TEditorList * EditorList = new TEditorList();
  3911. try
  3912. {
  3913. *EditorList = *WinConfiguration->EditorList;
  3914. for (int i = 0; i < EditorList->Count; i++)
  3915. {
  3916. const TEditorPreferences * Editor = EditorList->Editors[i];
  3917. if ((Editor->Data->Editor == edExternal) &&
  3918. (Editor->Data->ExternalEditor == Data->Command))
  3919. {
  3920. AnyFound = true;
  3921. if (Editor->Data->SDIExternalEditor)
  3922. {
  3923. AnyNonMDI = true;
  3924. if (Editor->Data->DetectMDIExternalEditor)
  3925. {
  3926. AnyDetect = true;
  3927. }
  3928. }
  3929. else
  3930. {
  3931. AnyMDI = true;
  3932. }
  3933. }
  3934. }
  3935. bool EnableMDI = false;
  3936. bool DisableDetect = false;
  3937. if (AnyMDI)
  3938. {
  3939. KeepOpen = true;
  3940. if (AnyNonMDI)
  3941. {
  3942. // there is at least one instance of the editor with MDI support enabled,
  3943. // and one with disabled, enable it for all instances
  3944. EnableMDI = true;
  3945. }
  3946. }
  3947. else if (AnyFound && !AnyDetect)
  3948. {
  3949. // at least once instance found but all have MDI autodetection disabled
  3950. // => close the file (default action)
  3951. }
  3952. else
  3953. {
  3954. // no instance of the editor has MDI support enabled
  3955. TMessageParams Params;
  3956. if (AnyFound)
  3957. {
  3958. // there is at least one instance of the editor
  3959. Params.Params |= mpNeverAskAgainCheck;
  3960. }
  3961. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3962. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3963. switch (Answer)
  3964. {
  3965. case qaNeverAskAgain:
  3966. DisableDetect = true;
  3967. break;
  3968. case qaNo:
  3969. EnableMDI = true;
  3970. KeepOpen = true;
  3971. break;
  3972. }
  3973. }
  3974. if (AnyFound && (EnableMDI || DisableDetect))
  3975. {
  3976. bool Changed = false;
  3977. for (int i = 0; i < EditorList->Count; i++)
  3978. {
  3979. const TEditorPreferences * Editor = EditorList->Editors[i];
  3980. if ((Editor->Data->Editor == edExternal) &&
  3981. (Editor->Data->ExternalEditor == Data->Command) &&
  3982. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3983. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3984. {
  3985. Changed = true;
  3986. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3987. if (EnableMDI)
  3988. {
  3989. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3990. }
  3991. if (DisableDetect)
  3992. {
  3993. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3994. }
  3995. EditorList->Change(i, UpdatedEditor);
  3996. }
  3997. }
  3998. if (Changed)
  3999. {
  4000. WinConfiguration->EditorList = EditorList;
  4001. }
  4002. }
  4003. }
  4004. __finally
  4005. {
  4006. delete EditorList;
  4007. }
  4008. }
  4009. else
  4010. {
  4011. // "open" case
  4012. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4013. qaOK, HELP_APP_EARLY_CLOSED);
  4014. }
  4015. }
  4016. //---------------------------------------------------------------------------
  4017. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4018. {
  4019. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4020. }
  4021. //---------------------------------------------------------------------------
  4022. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4023. {
  4024. SideEnter(osRemote);
  4025. }
  4026. //---------------------------------------------------------------------------
  4027. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4028. {
  4029. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4030. SideEnter(osRemote);
  4031. }
  4032. //---------------------------------------------------------------------------
  4033. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4034. {
  4035. FCurrentSide = Side;
  4036. if (Visible)
  4037. {
  4038. UpdateControls();
  4039. }
  4040. }
  4041. //---------------------------------------------------------------------------
  4042. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  4043. {
  4044. VisualiseOperationFinished(Side, FileName, Success);
  4045. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4046. {
  4047. FDeletedFiles->Add(FileName);
  4048. }
  4049. }
  4050. //---------------------------------------------------------------------------
  4051. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4052. TStrings * FileList, bool Alternative)
  4053. {
  4054. TCustomDirView * DView = DirView(Side);
  4055. DView->SaveSelection();
  4056. DView->SaveSelectedNames();
  4057. DebugAssert(!FAlternativeDelete);
  4058. FAlternativeDelete = Alternative;
  4059. try
  4060. {
  4061. if (!IsSideLocalBrowser(Side))
  4062. {
  4063. DebugAssert(Terminal != NULL);
  4064. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4065. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  4066. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  4067. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  4068. int Params = FLAGMASK(Alternative, dfAlternative);
  4069. try
  4070. {
  4071. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles);
  4072. DebugAssert(FDeletedFiles == NULL);
  4073. FDeletedFiles = DeletedFiles.get();
  4074. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4075. FOnFileOperationFinished = FileDeleted;
  4076. FMoveToQueue = false;
  4077. Terminal->DeleteFiles(FileList, Params);
  4078. // Probably not needed for deleting, just for consistency with transfer code
  4079. if (FMoveToQueue)
  4080. {
  4081. Abort();
  4082. }
  4083. }
  4084. catch (EAbort &)
  4085. {
  4086. if (FMoveToQueue)
  4087. {
  4088. DeletedFiles->Sorted = true;
  4089. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4090. {
  4091. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4092. {
  4093. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4094. DebugAssert(Index == 0);
  4095. PermanentFileList->Delete(Index);
  4096. Index--;
  4097. }
  4098. }
  4099. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4100. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4101. AddQueueItem(Queue, QueueItem, Terminal);
  4102. ClearOperationSelection(osRemote);
  4103. }
  4104. }
  4105. }
  4106. else
  4107. {
  4108. if (IsLocalBrowserMode())
  4109. {
  4110. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4111. }
  4112. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  4113. FProgressSide = FCurrentSide;
  4114. try
  4115. {
  4116. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  4117. }
  4118. __finally
  4119. {
  4120. ReloadLocalDirectory();
  4121. }
  4122. }
  4123. FAlternativeDelete = false;
  4124. }
  4125. catch(...)
  4126. {
  4127. FAlternativeDelete = false;
  4128. DView->DiscardSavedSelection();
  4129. throw;
  4130. }
  4131. DView->RestoreSelection();
  4132. }
  4133. //---------------------------------------------------------------------------
  4134. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4135. {
  4136. DebugAssert(Terminal);
  4137. DebugAssert(!IsLocalBrowserMode());
  4138. RemoteDirView->SaveSelection();
  4139. RemoteDirView->SaveSelectedNames();
  4140. try
  4141. {
  4142. if (Lock)
  4143. {
  4144. Terminal->LockFiles(FileList);
  4145. }
  4146. else
  4147. {
  4148. Terminal->UnlockFiles(FileList);
  4149. }
  4150. }
  4151. catch(...)
  4152. {
  4153. RemoteDirView->DiscardSavedSelection();
  4154. throw;
  4155. }
  4156. RemoteDirView->RestoreSelection();
  4157. }
  4158. //---------------------------------------------------------------------------
  4159. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4160. {
  4161. bool Result = false;
  4162. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4163. if (IsActiveTerminal(ATerminal))
  4164. {
  4165. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(Directory));
  4166. Result = File && File->IsDirectory;
  4167. }
  4168. return Result;
  4169. }
  4170. //---------------------------------------------------------------------------
  4171. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4172. {
  4173. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4174. return
  4175. !Terminal->IsCapable[fcRemoteCopy] ||
  4176. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4177. }
  4178. //---------------------------------------------------------------------------
  4179. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4180. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4181. bool NoConfirmation, bool Move)
  4182. {
  4183. DebugAssert(Terminal != NULL);
  4184. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4185. DebugAssert(!IsLocalBrowserMode());
  4186. if (Session == NULL)
  4187. {
  4188. Session = Terminal;
  4189. }
  4190. bool TargetConfirmed = false;
  4191. if (Session == Terminal)
  4192. {
  4193. if (RemoteDriveView->DropTarget != NULL)
  4194. {
  4195. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4196. TargetConfirmed = true;
  4197. }
  4198. else if (RemoteDirView->DropTarget != NULL)
  4199. {
  4200. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4201. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4202. TargetConfirmed = true;
  4203. }
  4204. else
  4205. {
  4206. Target = RemoteDirView->Path;
  4207. }
  4208. }
  4209. else
  4210. {
  4211. Target = GetSessionPath(Session, osRemote);
  4212. }
  4213. Target = UnixIncludeTrailingBackslash(Target);
  4214. if (FileList->Count == 1)
  4215. {
  4216. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4217. }
  4218. else
  4219. {
  4220. FileMask = AnyMask;
  4221. }
  4222. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4223. bool Result = true;
  4224. if (!NoConfirmation)
  4225. {
  4226. bool Multi = (FileList->Count > 1);
  4227. if (Move)
  4228. {
  4229. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4230. }
  4231. else
  4232. {
  4233. std::unique_ptr<TStrings> Sessions(new TStringList);
  4234. std::unique_ptr<TStrings> Directories(new TStringList);
  4235. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4236. for (int Index = 0; Index < SessionList->Count; Index++)
  4237. {
  4238. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4239. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4240. {
  4241. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4242. Directories->Add(GetSessionPath(ASession, osRemote));
  4243. }
  4244. }
  4245. bool AnyDirectory = false;
  4246. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4247. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4248. {
  4249. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4250. {
  4251. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4252. }
  4253. }
  4254. TDirectRemoteCopy AllowDirectCopy;
  4255. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4256. {
  4257. DebugAssert(DirectCopy);
  4258. AllowDirectCopy = drcAllow;
  4259. }
  4260. else if (Terminal->IsCapable[fcSecondaryShell])
  4261. {
  4262. DebugAssert(DirectCopy);
  4263. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4264. }
  4265. else
  4266. {
  4267. DebugAssert(!DirectCopy);
  4268. AllowDirectCopy = drcDisallow;
  4269. }
  4270. void * ASession = Session;
  4271. Result = DoRemoteCopyDialog(
  4272. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4273. DoDirectoryExists, TargetConfirmed);
  4274. Session = static_cast<TManagedTerminal *>(ASession);
  4275. }
  4276. }
  4277. return Result;
  4278. }
  4279. //---------------------------------------------------------------------------
  4280. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4281. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4282. {
  4283. DebugAssert(!IsLocalBrowserMode());
  4284. bool DirectCopy;
  4285. UnicodeString Target, FileMask;
  4286. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4287. if (Result)
  4288. {
  4289. if (!Move && !DirectCopy)
  4290. {
  4291. Configuration->Usage->Inc("RemoteCopyTemp");
  4292. UnicodeString RootTempDir;
  4293. UnicodeString TempDir;
  4294. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  4295. TStrings * TemporaryFilesList = new TStringList();
  4296. try
  4297. {
  4298. TMakeLocalFileListParams MakeFileListParam;
  4299. MakeFileListParam.FileList = TemporaryFilesList;
  4300. MakeFileListParam.FileTimes = NULL;
  4301. MakeFileListParam.IncludeDirs = true;
  4302. MakeFileListParam.Recursive = false;
  4303. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4304. TTerminalManager::Instance()->ActiveSession = Session;
  4305. if (TemporaryFilesList->Count > 0)
  4306. {
  4307. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4308. CopyParam.FileMask = FileMask;
  4309. DebugAssert(!FAutoOperation);
  4310. FAutoOperation = true;
  4311. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4312. }
  4313. }
  4314. __finally
  4315. {
  4316. delete TemporaryFilesList;
  4317. FAutoOperation = false;
  4318. if (!RootTempDir.IsEmpty())
  4319. {
  4320. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4321. }
  4322. }
  4323. }
  4324. else
  4325. {
  4326. RemoteDirView->SaveSelection();
  4327. RemoteDirView->SaveSelectedNames();
  4328. try
  4329. {
  4330. if (Move)
  4331. {
  4332. Configuration->Usage->Inc("RemoteMove");
  4333. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4334. }
  4335. else
  4336. {
  4337. Configuration->Usage->Inc("RemoteCopyDirect");
  4338. DebugAssert(DirectCopy);
  4339. DebugAssert(Session == Terminal);
  4340. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4341. Terminal->CommandSessionOpened ||
  4342. CommandSessionFallback())
  4343. {
  4344. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4345. }
  4346. }
  4347. }
  4348. catch(...)
  4349. {
  4350. RemoteDirView->DiscardSavedSelection();
  4351. throw;
  4352. }
  4353. RemoteDirView->RestoreSelection();
  4354. }
  4355. }
  4356. return Result;
  4357. }
  4358. //---------------------------------------------------------------------------
  4359. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4360. const UnicodeString & Path, TRemoteProperties & Properties)
  4361. {
  4362. DebugAssert(!IsLocalBrowserMode());
  4363. Properties.Valid = Properties.Valid << vpEncrypt;
  4364. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4365. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4366. }
  4367. //---------------------------------------------------------------------------
  4368. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4369. {
  4370. Side = GetSide(Side);
  4371. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4372. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4373. UnicodeString Name = LoadStr(NEW_FOLDER);
  4374. int AllowedChanges =
  4375. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4376. bool SaveSettings = false;
  4377. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4378. {
  4379. TWindowLock Lock(this);
  4380. if (!IsSideLocalBrowser(Side))
  4381. {
  4382. if (SaveSettings)
  4383. {
  4384. GUIConfiguration->NewDirectoryProperties = Properties;
  4385. }
  4386. CreateRemoteDirectory(Name, Properties);
  4387. }
  4388. else
  4389. {
  4390. DirView(Side)->CreateDirectory(Name);
  4391. }
  4392. }
  4393. }
  4394. //---------------------------------------------------------------------------
  4395. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4396. {
  4397. TWindowLock Lock(this);
  4398. DirView(Side)->ExecuteHomeDirectory();
  4399. }
  4400. //---------------------------------------------------------------------------
  4401. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4402. {
  4403. DoOpenDirectoryDialog(odBrowse, Side);
  4404. }
  4405. //---------------------------------------------------------------------------
  4406. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4407. {
  4408. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4409. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4410. bool Result = !Path.IsEmpty();
  4411. if (Result)
  4412. {
  4413. TryOpenDirectory(Side, Path);
  4414. }
  4415. return Result;
  4416. }
  4417. //---------------------------------------------------------------------------
  4418. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4419. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4420. bool & Close)
  4421. {
  4422. // terminal can be already closed (e.g. dropped connection)
  4423. if (Terminal != NULL)
  4424. {
  4425. try
  4426. {
  4427. TCalculateSizeParams Params;
  4428. Params.Stats = &Stats;
  4429. Terminal->CalculateFilesSize(FileList, Size, Params);
  4430. }
  4431. catch(...)
  4432. {
  4433. if (!Terminal->Active)
  4434. {
  4435. Close = true;
  4436. }
  4437. throw;
  4438. }
  4439. }
  4440. }
  4441. //---------------------------------------------------------------------------
  4442. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4443. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4444. bool & Close)
  4445. {
  4446. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4447. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4448. {
  4449. Configuration->Usage->Inc(L"ChecksumCalculated");
  4450. try
  4451. {
  4452. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4453. }
  4454. catch(...)
  4455. {
  4456. if (!Terminal->Active)
  4457. {
  4458. Close = true;
  4459. }
  4460. throw;
  4461. }
  4462. }
  4463. }
  4464. //---------------------------------------------------------------------------
  4465. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4466. {
  4467. if (Terminal->LoadFilesProperties(FileList))
  4468. {
  4469. RemoteDirView->Invalidate();
  4470. }
  4471. }
  4472. //---------------------------------------------------------------------------
  4473. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4474. {
  4475. return
  4476. Terminal->IsCapable[fcCalculatingChecksum] ||
  4477. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4478. }
  4479. //---------------------------------------------------------------------------
  4480. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4481. {
  4482. bool Result;
  4483. if (!IsSideLocalBrowser(Side))
  4484. {
  4485. TRemoteTokenList * GroupList = NULL;
  4486. TRemoteTokenList * UserList = NULL;
  4487. try
  4488. {
  4489. TRemoteProperties CurrentProperties;
  4490. LoadFilesProperties(FileList);
  4491. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4492. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4493. if (CapableGroupChanging || CapableOwnerChanging)
  4494. {
  4495. if (CapableGroupChanging)
  4496. {
  4497. GroupList = Terminal->Groups->Duplicate();
  4498. }
  4499. if (CapableOwnerChanging)
  4500. {
  4501. UserList = Terminal->Users->Duplicate();
  4502. }
  4503. TRemoteDirectory * Files = Terminal->Files;
  4504. int Count = Files->Count;
  4505. if (Count > 100)
  4506. {
  4507. Count = 100;
  4508. }
  4509. for (int Index = 0; Index < Count; Index++)
  4510. {
  4511. TRemoteFile * File = Files->Files[Index];
  4512. if (CapableGroupChanging)
  4513. {
  4514. GroupList->AddUnique(File->Group);
  4515. }
  4516. if (CapableOwnerChanging)
  4517. {
  4518. UserList->AddUnique(File->Owner);
  4519. }
  4520. }
  4521. // if we haven't collected tokens for all files in current directory,
  4522. // make sure we collect them at least for all selected files.
  4523. // (note that so far the files in FileList has to be from current direcotry)
  4524. if (Count < Files->Count)
  4525. {
  4526. for (int Index = 0; Index < FileList->Count; Index++)
  4527. {
  4528. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4529. if (CapableGroupChanging)
  4530. {
  4531. GroupList->AddUnique(File->Group);
  4532. }
  4533. if (CapableOwnerChanging)
  4534. {
  4535. UserList->AddUnique(File->Owner);
  4536. }
  4537. }
  4538. }
  4539. }
  4540. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4541. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4542. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4543. {
  4544. CapableAclChanging = false;
  4545. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4546. }
  4547. int Flags = 0;
  4548. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4549. if (CapableAclChanging) Flags |= cpAcl;
  4550. if (CapableOwnerChanging) Flags |= cpOwner;
  4551. if (CapableGroupChanging) Flags |= cpGroup;
  4552. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4553. if (CanCalculateChecksum())
  4554. {
  4555. CalculateChecksumEvent = CalculateChecksum;
  4556. }
  4557. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4558. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4559. TRemoteProperties NewProperties = CurrentProperties;
  4560. Result =
  4561. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4562. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4563. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4564. CalculateSize, CalculateChecksumEvent);
  4565. if (Result)
  4566. {
  4567. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4568. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4569. }
  4570. }
  4571. __finally
  4572. {
  4573. delete GroupList;
  4574. delete UserList;
  4575. }
  4576. }
  4577. else
  4578. {
  4579. DirView(Side)->DisplayPropertiesMenu();
  4580. Result = true;
  4581. }
  4582. return Result;
  4583. }
  4584. //---------------------------------------------------------------------------
  4585. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4586. {
  4587. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4588. {
  4589. FIgnoreNextDialogChar = Key;
  4590. }
  4591. Key = 0;
  4592. }
  4593. //---------------------------------------------------------------------------
  4594. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4595. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4596. {
  4597. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4598. if (Command != NULL)
  4599. {
  4600. KeyProcessed(Key, Shift);
  4601. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4602. {
  4603. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4604. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4605. false, false, const_cast<TCustomCommandType *>(Command));
  4606. }
  4607. }
  4608. }
  4609. //---------------------------------------------------------------------------
  4610. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4611. {
  4612. if (!NonVisualDataModule->Busy)
  4613. {
  4614. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4615. {
  4616. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4617. }
  4618. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4619. {
  4620. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4621. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4622. {
  4623. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4624. // But so far it's not a problem, as it does what we want.
  4625. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4626. if (((Action->ShortCut == KeyShortCut) ||
  4627. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4628. AllowedAction(Action, aaShortCut))
  4629. {
  4630. // Has to be called before the action as the dialog char is already in queue.
  4631. // So when the action consumes message queue, we already need to have the
  4632. // FIgnoreNextDialogChar set
  4633. KeyProcessed(Key, Shift);
  4634. // Reset reference to previous component (when menu/toolbar was clicked).
  4635. // Needed to detect that action was invoked by keyboard shortcut
  4636. // in TNonVisualDataModule::ExplorerActionsExecute
  4637. Action->ActionComponent = NULL;
  4638. Action->Execute();
  4639. return;
  4640. }
  4641. }
  4642. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4643. {
  4644. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4645. {
  4646. KeyProcessed(Key, Shift);
  4647. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4648. return;
  4649. }
  4650. }
  4651. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4652. {
  4653. KeyProcessed(Key, Shift);
  4654. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4655. }
  4656. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4657. if (IsCustomShortCut(CustomShortCut))
  4658. {
  4659. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4660. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4661. if (WinConfiguration->SharedBookmarks != NULL)
  4662. {
  4663. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4664. if ((Bookmark != NULL) &&
  4665. OpenBookmark(FCurrentSide, Bookmark))
  4666. {
  4667. KeyProcessed(Key, Shift);
  4668. }
  4669. }
  4670. }
  4671. }
  4672. }
  4673. TForm::KeyDown(Key, Shift);
  4674. }
  4675. //---------------------------------------------------------------------------
  4676. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4677. {
  4678. bool OpenedTerminal = false;
  4679. UnicodeString ProtocolName;
  4680. UnicodeString ProtocolNameHint;
  4681. UnicodeString SecurityProtocolName;
  4682. UnicodeString DurationHint;
  4683. // See the comment in TScpCommanderForm::UpdateControls()
  4684. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4685. if (ActiveTerminal != NULL)
  4686. {
  4687. // Active is not enough here
  4688. if (ActiveTerminal->Status == ssOpened)
  4689. {
  4690. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4691. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4692. if (FileSystemInfo.ProtocolName.IsEmpty())
  4693. {
  4694. ProtocolName = SessionInfo.ProtocolName;
  4695. }
  4696. else
  4697. {
  4698. ProtocolName = FileSystemInfo.ProtocolName;
  4699. }
  4700. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4701. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4702. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4703. OpenedTerminal = true;
  4704. }
  4705. else if (ActiveTerminal->Status > ssClosed)
  4706. {
  4707. ProtocolName = LoadStr(STATUS_CONNECTING);
  4708. }
  4709. else
  4710. {
  4711. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4712. }
  4713. }
  4714. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4715. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4716. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4717. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4718. if (ProtocolStatusPanel->Caption != ProtocolName)
  4719. {
  4720. ProtocolStatusPanel->Caption = ProtocolName;
  4721. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4722. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4723. }
  4724. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4725. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4726. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4727. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4728. SecurityStatusPanel->Enabled = SecurityEnabled;
  4729. UnicodeString SecurityProtocolHint;
  4730. if (SecurityEnabled)
  4731. {
  4732. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4733. }
  4734. else
  4735. {
  4736. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4737. }
  4738. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4739. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4740. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4741. DurationStatusPanel->Hint = DurationHint;
  4742. UpdateStatusBar();
  4743. }
  4744. //---------------------------------------------------------------------------
  4745. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4746. {
  4747. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4748. DebugAssert(SessionStatusBar != NULL);
  4749. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4750. if (!FNote.IsEmpty())
  4751. {
  4752. NoteStatusPanel->Caption = FNote;
  4753. }
  4754. else
  4755. {
  4756. UpdateStatusPanelText(NoteStatusPanel);
  4757. }
  4758. NoteStatusPanel->Hint = FNoteHints;
  4759. UnicodeString LoginTime;
  4760. // See the comment in TScpCommanderForm::UpdateControls()
  4761. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4762. // Active is not enough here
  4763. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4764. {
  4765. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4766. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4767. }
  4768. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4769. DurationStatusPanel->Caption = LoginTime;
  4770. }
  4771. //---------------------------------------------------------------------------
  4772. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4773. {
  4774. Panel->Caption = L"";
  4775. }
  4776. //---------------------------------------------------------------------------
  4777. void __fastcall TCustomScpExplorerForm::Idle()
  4778. {
  4779. if (FShowing ||
  4780. // Particularly for
  4781. // - Standalone editing
  4782. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4783. // while "keeping remote directory up to date".
  4784. StandaloneOperation)
  4785. {
  4786. FEditorManager->Check();
  4787. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4788. // that needs to know if queue view is visible (and it may be closed after queue update)
  4789. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4790. }
  4791. if (FShowing)
  4792. {
  4793. if (!NonVisualDataModule->Busy &&
  4794. // Menu is opened or drag&drop is going on
  4795. (Mouse->Capture == NULL))
  4796. {
  4797. if (FRefreshRemoteDirectory)
  4798. {
  4799. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4800. {
  4801. Terminal->RefreshDirectory();
  4802. }
  4803. FRefreshRemoteDirectory = false;
  4804. }
  4805. if (FRefreshLocalDirectory)
  4806. {
  4807. ReloadLocalDirectory();
  4808. FRefreshLocalDirectory = false;
  4809. }
  4810. if (WinConfiguration->RefreshRemotePanel)
  4811. {
  4812. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4813. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4814. {
  4815. RemoteDirView->ReloadDirectory();
  4816. }
  4817. }
  4818. }
  4819. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4820. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4821. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4822. // 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.
  4823. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4824. MenuToolbar->Idle();
  4825. }
  4826. if (FShowing || StandaloneOperation)
  4827. {
  4828. if (FQueueStatusInvalidated)
  4829. {
  4830. UpdateQueueStatus(false);
  4831. }
  4832. RefreshQueueItems();
  4833. }
  4834. if (FShowing)
  4835. {
  4836. UpdateStatusBar();
  4837. }
  4838. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4839. {
  4840. FClipboardFakeMonitorsPendingReset = false;
  4841. FClipboardFakeMonitors.reset(NULL);
  4842. }
  4843. FIgnoreNextDialogChar = 0;
  4844. }
  4845. //---------------------------------------------------------------------------
  4846. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4847. {
  4848. try
  4849. {
  4850. FUserActionTimer->Enabled = false;
  4851. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4852. {
  4853. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4854. {
  4855. FPendingQueueActionItem->ProcessUserAction();
  4856. }
  4857. }
  4858. }
  4859. __finally
  4860. {
  4861. FPendingQueueActionItem = NULL;
  4862. }
  4863. }
  4864. //---------------------------------------------------------------------------
  4865. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4866. {
  4867. if (WinConfiguration->MinimizeToTray)
  4868. {
  4869. UpdateTrayIcon();
  4870. FTrayIcon->Visible = true;
  4871. if (Visible)
  4872. {
  4873. ShowWindow(Handle, SW_HIDE);
  4874. }
  4875. }
  4876. }
  4877. //---------------------------------------------------------------------------
  4878. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4879. {
  4880. // WORKAROUND
  4881. // When restoring maximized window from minimization,
  4882. // rarely some controls do not align properly.
  4883. // Two instances seen (both for Commander):
  4884. // - When restoring, window is temporarily narrower (not maximized),
  4885. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4886. // Once maximized already, top dock shinks back, but the session PageControl,
  4887. // do not align up, leaving space between TopDock and PageControl.
  4888. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4889. for (int Index = 0; Index < ControlCount; Index++)
  4890. {
  4891. RealignControl(Controls[Index]);
  4892. }
  4893. if (FTrayIcon->Visible)
  4894. {
  4895. FTrayIcon->Visible = false;
  4896. if (Visible)
  4897. {
  4898. ShowWindow(Handle, SW_SHOW);
  4899. }
  4900. }
  4901. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4902. {
  4903. FNeedSession = false;
  4904. NonVisualDataModule->StartBusy();
  4905. try
  4906. {
  4907. NeedSession(true);
  4908. }
  4909. __finally
  4910. {
  4911. NonVisualDataModule->EndBusy();
  4912. }
  4913. }
  4914. }
  4915. //---------------------------------------------------------------------------
  4916. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4917. {
  4918. FTrayIcon->Hint = GetMainForm()->Caption;
  4919. }
  4920. //---------------------------------------------------------------------------
  4921. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4922. {
  4923. UpdateTrayIcon();
  4924. }
  4925. //---------------------------------------------------------------------------
  4926. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4927. {
  4928. // workaround
  4929. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4930. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4931. // But WM_ACTIVATEAPP message can be received even when
  4932. // the main window is minimized to the tray and internal editor window is focused
  4933. // (after another application was previously active)
  4934. if (::IsIconic(Handle))
  4935. {
  4936. if (!IsAppIconic())
  4937. {
  4938. SetAppIconic(true);
  4939. }
  4940. }
  4941. ::ApplicationRestore();
  4942. Application->BringToFront();
  4943. }
  4944. //---------------------------------------------------------------------------
  4945. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4946. {
  4947. RestoreApp();
  4948. }
  4949. //---------------------------------------------------------------------------
  4950. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4951. {
  4952. if (OpenInNewWindow())
  4953. {
  4954. ExecuteNewInstance(SessionUrl);
  4955. }
  4956. else
  4957. {
  4958. TTerminalManager::Instance()->NewSession(SessionUrl);
  4959. }
  4960. }
  4961. //---------------------------------------------------------------------------
  4962. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4963. {
  4964. NewSession();
  4965. }
  4966. //---------------------------------------------------------------------------
  4967. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4968. {
  4969. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4970. StoredSessions->NewSession(SessionName, SessionData);
  4971. // modified only, explicit
  4972. StoredSessions->Save(false, true);
  4973. // encode session name because of slashes in hierarchical sessions
  4974. return EncodeUrlString(SessionName);
  4975. }
  4976. //---------------------------------------------------------------------------
  4977. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4978. {
  4979. // current working directories become defaults here, what is not right
  4980. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4981. return SaveHiddenDuplicateSession(SessionData.get());
  4982. }
  4983. //---------------------------------------------------------------------------
  4984. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  4985. {
  4986. if (OpenInNewWindow())
  4987. {
  4988. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4989. }
  4990. else
  4991. {
  4992. // current working directories become defaults here, what is not right
  4993. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4994. TTerminalManager * Manager = TTerminalManager::Instance();
  4995. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4996. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4997. // We definitelly want these
  4998. ASession->Disconnected = ManagedSession->Disconnected;
  4999. // Not sure about these two
  5000. ASession->Permanent = ManagedSession->Permanent;
  5001. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  5002. Manager->ActiveSession = ASession;
  5003. }
  5004. }
  5005. //---------------------------------------------------------------------------
  5006. void __fastcall TCustomScpExplorerForm::RenameTab()
  5007. {
  5008. UnicodeString Name = ManagedSession->SessionData->SessionName;
  5009. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  5010. // When submitting the default name, do not fix it
  5011. (Name != ManagedSession->SessionData->SessionName))
  5012. {
  5013. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5014. TSessionData::ValidateName(Name);
  5015. // This is inconsistent with how color (for example) is handled.
  5016. ManagedSession->SessionData->Name = Name;
  5017. UpdateControls();
  5018. // Add/Remove distinguishing paths from sessions of the same name.
  5019. SessionListChanged();
  5020. }
  5021. }
  5022. //---------------------------------------------------------------------------
  5023. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5024. {
  5025. DebugAssert(Queue != NULL);
  5026. bool Result = Queue->IsEmpty;
  5027. if (!Result)
  5028. {
  5029. SetFocus();
  5030. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5031. }
  5032. return Result;
  5033. }
  5034. //---------------------------------------------------------------------------
  5035. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5036. {
  5037. return CanCloseQueue(FQueue);
  5038. }
  5039. //---------------------------------------------------------------------------
  5040. void __fastcall TCustomScpExplorerForm::CloseTab()
  5041. {
  5042. if (CanCloseQueue())
  5043. {
  5044. TTerminalManager::Instance()->FreeActiveTerminal();
  5045. }
  5046. }
  5047. //---------------------------------------------------------------------------
  5048. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5049. {
  5050. if (CanCloseQueue())
  5051. {
  5052. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5053. }
  5054. }
  5055. //---------------------------------------------------------------------------
  5056. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5057. {
  5058. DetachTerminal(Terminal);
  5059. RemoteDirView->Terminal = Terminal;
  5060. UpdateRemotePathComboBox(false);
  5061. InitStatusBar();
  5062. UpdateControls();
  5063. }
  5064. //---------------------------------------------------------------------------
  5065. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5066. {
  5067. InitStatusBar();
  5068. }
  5069. //---------------------------------------------------------------------------
  5070. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5071. {
  5072. if (DebugAlwaysTrue(!Terminal->Active))
  5073. {
  5074. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5075. }
  5076. }
  5077. //---------------------------------------------------------------------------
  5078. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5079. {
  5080. if (OpenInNewWindow())
  5081. {
  5082. // encode session name because of slashes in hierarchical sessions
  5083. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5084. }
  5085. else
  5086. {
  5087. TTerminalManager * Manager = TTerminalManager::Instance();
  5088. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5089. Manager->ActiveSession = Terminal;
  5090. }
  5091. }
  5092. //---------------------------------------------------------------------------
  5093. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5094. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5095. {
  5096. TTerminalManager * Manager = TTerminalManager::Instance();
  5097. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5098. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5099. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5100. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5101. {
  5102. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5103. // FirstSession can be null, if none of the workspace sites exist anymore
  5104. // or if all workspace sessions are not suported by the interface
  5105. // (when trying to open all local-local workspace in "explorer" interface)
  5106. if (FirstSession != NULL)
  5107. {
  5108. if (!ConnectFirstTerminal)
  5109. {
  5110. FirstSession->Disconnected = true;
  5111. FirstSession->DisconnectedTemporarily = true;
  5112. }
  5113. Manager->ActiveSession = FirstSession;
  5114. }
  5115. }
  5116. }
  5117. //---------------------------------------------------------------------------
  5118. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5119. {
  5120. if (OpenInNewWindow())
  5121. {
  5122. ExecuteNewInstance(Name);
  5123. }
  5124. else
  5125. {
  5126. DoOpenFolderOrWorkspace(Name, true, false);
  5127. }
  5128. }
  5129. //---------------------------------------------------------------------------
  5130. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5131. bool &CanClose)
  5132. {
  5133. AppLog(L"Windows close query");
  5134. // See the comment in CloseApp()
  5135. if (NonVisualDataModule->Busy)
  5136. {
  5137. CanClose = false;
  5138. }
  5139. else
  5140. {
  5141. TTerminalManager * Manager = TTerminalManager::Instance();
  5142. int ActiveSessions = 0;
  5143. for (int Index = 0; Index < Manager->Count; Index++)
  5144. {
  5145. if (Manager->Sessions[Index]->Active)
  5146. {
  5147. ActiveSessions++;
  5148. }
  5149. }
  5150. // Confirm, when there's at least one active remote session or
  5151. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5152. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5153. WinConfiguration->ConfirmClosingSession)
  5154. {
  5155. unsigned int Result;
  5156. TMessageParams Params(mpNeverAskAgainCheck);
  5157. UnicodeString Message;
  5158. int Answers = qaOK | qaCancel;
  5159. // The current session is the only active session
  5160. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5161. {
  5162. if (!WinConfiguration->AutoSaveWorkspace)
  5163. {
  5164. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5165. }
  5166. else
  5167. {
  5168. Message = LoadStr(CLOSE_SESSION);
  5169. }
  5170. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5171. }
  5172. // Multiple active sessions or one active session, but it's not the current one
  5173. else if (ActiveSessions > 0)
  5174. {
  5175. if (!WinConfiguration->AutoSaveWorkspace)
  5176. {
  5177. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5178. }
  5179. else
  5180. {
  5181. Message = LoadStr(CLOSE_SESSIONS);
  5182. }
  5183. }
  5184. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5185. else
  5186. {
  5187. DebugAlwaysTrue(Manager->Count > 1);
  5188. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5189. Message = LoadStr(CLOSE_WORKSPACE);
  5190. }
  5191. UnicodeString Note;
  5192. if (WinConfiguration->AutoSaveWorkspace)
  5193. {
  5194. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5195. }
  5196. else
  5197. {
  5198. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5199. Answers = qaYes | qaNo | qaCancel;
  5200. }
  5201. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5202. SetFocus();
  5203. Result = MessageDialog(Message, qtConfirmation,
  5204. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5205. if (Result == qaNeverAskAgain)
  5206. {
  5207. WinConfiguration->ConfirmClosingSession = false;
  5208. }
  5209. if (Result == qaNo)
  5210. {
  5211. CanClose = SaveWorkspace(true);
  5212. // note that the workspace will be saved redundatly again from FormClose
  5213. }
  5214. else
  5215. {
  5216. CanClose =
  5217. (Result == qaOK) ||
  5218. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5219. (Result == qaNeverAskAgain);
  5220. }
  5221. }
  5222. if (CanClose && HasActiveTerminal())
  5223. {
  5224. CanClose = CanCloseQueue();
  5225. }
  5226. }
  5227. if (CanClose)
  5228. {
  5229. CanClose =
  5230. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5231. FEditorManager->CloseExternalFilesWithoutProcess();
  5232. if (CanClose)
  5233. {
  5234. while (CanClose && (FLocalEditors->Count > 0))
  5235. {
  5236. int PrevCount = FLocalEditors->Count;
  5237. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5238. CanClose = (FLocalEditors->Count < PrevCount);
  5239. }
  5240. if (CanClose)
  5241. {
  5242. CanClose = FEditorManager->Empty(true);
  5243. if (!CanClose)
  5244. {
  5245. SetFocus();
  5246. CanClose =
  5247. (MessageDialog(
  5248. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5249. }
  5250. }
  5251. }
  5252. }
  5253. }
  5254. //---------------------------------------------------------------------------
  5255. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5256. {
  5257. TForm * Form = dynamic_cast<TForm *>(Sender);
  5258. DebugAssert(Form != NULL);
  5259. Form->Close();
  5260. }
  5261. //---------------------------------------------------------------------------
  5262. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5263. {
  5264. TForm * Form = dynamic_cast<TForm *>(Sender);
  5265. delete Form;
  5266. }
  5267. //---------------------------------------------------------------------------
  5268. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5269. {
  5270. while (FLocalEditors->Count > 0)
  5271. {
  5272. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5273. }
  5274. }
  5275. //---------------------------------------------------------------------------
  5276. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5277. TObject *Sender)
  5278. {
  5279. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5280. try
  5281. {
  5282. SetProperties(osRemote, FileList);
  5283. }
  5284. __finally
  5285. {
  5286. delete FileList;
  5287. }
  5288. }
  5289. //---------------------------------------------------------------------------
  5290. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5291. {
  5292. if (value)
  5293. {
  5294. if (Component == fcCustomCommandsBand)
  5295. {
  5296. UpdateCustomCommandsToolbar();
  5297. }
  5298. if (Component == fcQueueFileList)
  5299. {
  5300. DebugAssert(!QueueFileListSplitter->Visible);
  5301. AdjustQueueLayout();
  5302. UpdateQueueFileList();
  5303. }
  5304. }
  5305. }
  5306. //---------------------------------------------------------------------------
  5307. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5308. {
  5309. int MinHeightLimit =
  5310. GetStaticQueuePanelComponentsHeight() +
  5311. QueueFileListSplitter->Height +
  5312. QueueFileList->Height +
  5313. GetMinQueueViewHeight();
  5314. if (QueuePanel->ClientHeight < MinHeightLimit)
  5315. {
  5316. QueuePanel->ClientHeight = MinHeightLimit;
  5317. }
  5318. }
  5319. //---------------------------------------------------------------------------
  5320. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5321. {
  5322. TControl * Control = GetComponent(Component);
  5323. DebugAssert(Control);
  5324. bool Changed = (Control->Visible != value);
  5325. if (Changed)
  5326. {
  5327. ComponentShowing(Component, value);
  5328. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5329. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5330. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5331. if (value)
  5332. {
  5333. int RemainingHeight = Control->Parent->ClientHeight;
  5334. int RemainingWidth = Control->Parent->ClientWidth;
  5335. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5336. {
  5337. TControl * ChildControl = Control->Parent->Controls[i];
  5338. if (ChildControl->Visible)
  5339. {
  5340. switch (ChildControl->Align)
  5341. {
  5342. case alTop:
  5343. case alBottom:
  5344. RemainingHeight -= ChildControl->Height;
  5345. break;
  5346. case alLeft:
  5347. case alRight:
  5348. RemainingWidth -= ChildControl->Width;
  5349. break;
  5350. }
  5351. }
  5352. }
  5353. int Reserve = ScaleByTextHeight(this, 32);
  5354. // queue in explorer, trees in commander
  5355. if (Control->Height > RemainingHeight - Reserve)
  5356. {
  5357. Control->Height = RemainingHeight / 2;
  5358. }
  5359. if (Control->Width > RemainingWidth - Reserve)
  5360. {
  5361. Control->Width = RemainingWidth / 2;
  5362. }
  5363. }
  5364. Control->Visible = value;
  5365. if (WasFocused && Visible)
  5366. {
  5367. DirView(osCurrent)->SetFocus();
  5368. }
  5369. FixControlsPlacement();
  5370. }
  5371. }
  5372. //---------------------------------------------------------------------------
  5373. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5374. {
  5375. TControl * Control = GetComponent(Component);
  5376. if (Control == NULL)
  5377. {
  5378. return false;
  5379. }
  5380. else
  5381. {
  5382. return Control->Visible;
  5383. }
  5384. }
  5385. //---------------------------------------------------------------------------
  5386. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5387. {
  5388. bool Result;
  5389. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5390. {
  5391. Result = !IsUWP();
  5392. }
  5393. else
  5394. {
  5395. Result = true;
  5396. }
  5397. return Result;
  5398. }
  5399. //---------------------------------------------------------------------------
  5400. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5401. {
  5402. if (DirView->ItemFocused != NULL)
  5403. {
  5404. DirView->ItemFocused->MakeVisible(false);
  5405. }
  5406. }
  5407. //---------------------------------------------------------------------------
  5408. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5409. {
  5410. MakeFocusedItemVisible(RemoteDirView);
  5411. QueueSplitter->Visible = QueuePanel->Visible;
  5412. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5413. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5414. TControl * TopControlsOrder[] =
  5415. { TopDock, MessageDock, SessionsPageControl };
  5416. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5417. TControl * QueueControlsOrder[] =
  5418. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5419. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5420. }
  5421. //---------------------------------------------------------------------------
  5422. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5423. {
  5424. switch (Component) {
  5425. case fcStatusBar: return RemoteStatusBar;
  5426. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5427. case fcQueueView: return QueuePanel;
  5428. case fcQueueToolbar: return QueueDock;
  5429. case fcRemoteTree: return RemoteDrivePanel;
  5430. case fcSessionsTabs: return SessionsPageControl;
  5431. case fcQueueFileList: return QueueFileList;
  5432. default: return NULL;
  5433. }
  5434. }
  5435. //---------------------------------------------------------------------------
  5436. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5437. TObject *Sender, TListColumn *Column, TPoint &Point)
  5438. {
  5439. DebugAssert(NonVisualDataModule && Column && Sender);
  5440. NonVisualDataModule->ListColumn = Column;
  5441. TPopupMenu * DirViewColumnMenu;
  5442. if (Sender == DirView(osOther))
  5443. {
  5444. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5445. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5446. bool SizeColumn = (Column->Index == uvSize);
  5447. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5448. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5449. }
  5450. else
  5451. {
  5452. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5453. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5454. bool SizeColumn = (Column->Index == dvSize);
  5455. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5456. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5457. }
  5458. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5459. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5460. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5461. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5462. }
  5463. //---------------------------------------------------------------------------
  5464. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5465. TObject *Sender, TListItem *Item, bool &AllowExec)
  5466. {
  5467. DoDirViewExecFile(Sender, Item, AllowExec);
  5468. }
  5469. //---------------------------------------------------------------------------
  5470. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5471. TListItem * Item, bool & AllowExec)
  5472. {
  5473. DebugAssert(Sender && Item && Configuration);
  5474. DebugAssert(AllowExec);
  5475. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5476. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5477. bool Remote = !IsSideLocalBrowser(Side);
  5478. DebugAssert(Item == ADirView->ItemFocused);
  5479. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5480. TResolvedDoubleClickAction Action;
  5481. if (FForceExecution)
  5482. {
  5483. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5484. }
  5485. else
  5486. {
  5487. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5488. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5489. }
  5490. if (Action == rdcaCopy)
  5491. {
  5492. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5493. UnlockWindow();
  5494. try
  5495. {
  5496. if (IsLocalBrowserMode())
  5497. {
  5498. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5499. }
  5500. else
  5501. {
  5502. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5503. }
  5504. }
  5505. __finally
  5506. {
  5507. LockWindow();
  5508. }
  5509. AllowExec = false;
  5510. }
  5511. else if (Action == rdcaEdit)
  5512. {
  5513. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5514. {
  5515. ExecuteFile(Side, efDefaultEditor);
  5516. AllowExec = false;
  5517. }
  5518. }
  5519. else if (Action == rdcaOpen)
  5520. {
  5521. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5522. {
  5523. ExecuteFile(osRemote, efShell);
  5524. AllowExec = false;
  5525. }
  5526. }
  5527. }
  5528. //---------------------------------------------------------------------------
  5529. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5530. {
  5531. return ((Side == osRemote) || (Side == osCurrent));
  5532. }
  5533. //---------------------------------------------------------------------------
  5534. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5535. {
  5536. DebugFail();
  5537. }
  5538. //---------------------------------------------------------------------------
  5539. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5540. {
  5541. DebugFail();
  5542. }
  5543. //---------------------------------------------------------------------------
  5544. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5545. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5546. {
  5547. TSynchronizeParamType Params;
  5548. Params.LocalDirectory = LocalDirectory;
  5549. Params.RemoteDirectory = RemoteDirectory;
  5550. int UnusedParams =
  5551. (GUIConfiguration->SynchronizeParams &
  5552. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5553. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5554. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5555. Params.Options = GUIConfiguration->SynchronizeOptions;
  5556. bool SaveSettings = false;
  5557. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5558. &DoSynchronizeTooManyDirectories);
  5559. DebugAssert(FSynchronizeController == NULL);
  5560. FSynchronizeController = &Controller;
  5561. bool Result;
  5562. try
  5563. {
  5564. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5565. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5566. int Options =
  5567. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5568. DebugAssert(FOnFeedSynchronizeError == NULL);
  5569. DebugAssert(FOnSynchronizeAbort == NULL);
  5570. DebugAssert(FSynchronizeTerminal == NULL);
  5571. FSynchronizeTerminal = Terminal;
  5572. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5573. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5574. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5575. if (Result)
  5576. {
  5577. if (SaveSettings)
  5578. {
  5579. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5580. GUIConfiguration->SynchronizeOptions = Params.Options;
  5581. }
  5582. else
  5583. {
  5584. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5585. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5586. FLAGSET(Params.Options, soSynchronize))
  5587. {
  5588. GUIConfiguration->SynchronizeOptions =
  5589. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5590. soSynchronize;
  5591. }
  5592. }
  5593. LocalDirectory = Params.LocalDirectory;
  5594. RemoteDirectory = Params.RemoteDirectory;
  5595. }
  5596. }
  5597. __finally
  5598. {
  5599. FSynchronizeController = NULL;
  5600. DebugAssert(FOnFeedSynchronizeError == NULL);
  5601. FOnFeedSynchronizeError = NULL;
  5602. DebugAssert(FOnSynchronizeAbort == NULL);
  5603. FOnSynchronizeAbort = NULL;
  5604. FSynchronizeTerminal = NULL;
  5605. }
  5606. return Result;
  5607. }
  5608. //---------------------------------------------------------------------------
  5609. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5610. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5611. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5612. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5613. TSynchronizeOptions * Options, bool Full)
  5614. {
  5615. // Keep-up-to-date mode
  5616. if (Terminal->Status == ssOpened)
  5617. {
  5618. try
  5619. {
  5620. int PParams = Params.Params;
  5621. if (!Full)
  5622. {
  5623. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5624. if (FLAGSET(Params.Options, soRecurse))
  5625. {
  5626. PParams |= TTerminal::spSubDirs;
  5627. }
  5628. }
  5629. else
  5630. {
  5631. // if keepuptodate is non-recursive,
  5632. // full sync before has to be non-recursive as well
  5633. if (FLAGCLEAR(Params.Options, soRecurse))
  5634. {
  5635. PParams |= TTerminal::spNoRecurse;
  5636. }
  5637. }
  5638. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5639. PParams, Checklist, Options);
  5640. }
  5641. catch (Exception & E)
  5642. {
  5643. if (!Terminal->Active)
  5644. {
  5645. ShowExtendedExceptionEx(Terminal, &E);
  5646. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5647. if (!Terminal->Active)
  5648. {
  5649. throw;
  5650. }
  5651. }
  5652. else
  5653. {
  5654. if (FLAGSET(Params.Options, soContinueOnError) &&
  5655. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5656. {
  5657. // noop, already logged in MoreMessageDialog
  5658. }
  5659. else
  5660. {
  5661. // We get mostly EAbort here, so this is noop.
  5662. // Exception is an error when listing directories while looking for differences.
  5663. ShowExtendedExceptionEx(Terminal, &E);
  5664. throw;
  5665. }
  5666. }
  5667. }
  5668. }
  5669. }
  5670. //---------------------------------------------------------------------------
  5671. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5672. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5673. const UnicodeString ErrorStr)
  5674. {
  5675. if (!Directory.IsEmpty())
  5676. {
  5677. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5678. }
  5679. else
  5680. {
  5681. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5682. }
  5683. }
  5684. //---------------------------------------------------------------------------
  5685. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5686. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5687. {
  5688. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5689. {
  5690. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5691. }
  5692. else
  5693. {
  5694. TMessageParams Params(mpNeverAskAgainCheck);
  5695. unsigned int Result = MessageDialog(
  5696. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5697. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5698. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5699. {
  5700. MaxDirectories *= 2;
  5701. if (Result == qaNeverAskAgain)
  5702. {
  5703. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5704. }
  5705. }
  5706. else
  5707. {
  5708. Abort();
  5709. }
  5710. }
  5711. }
  5712. //---------------------------------------------------------------------------
  5713. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5714. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5715. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5716. TSynchronizeOptions * Options)
  5717. {
  5718. // Keep-up-to-date mode
  5719. DebugAssert(!FAutoOperation);
  5720. void * BatchStorage;
  5721. BatchStart(BatchStorage);
  5722. FAutoOperation = true;
  5723. bool AnyOperation = false;
  5724. TDateTime StartTime = Now();
  5725. TSynchronizeChecklist * AChecklist = NULL;
  5726. try
  5727. {
  5728. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5729. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5730. {
  5731. FSynchronizeProgressForm->Start();
  5732. }
  5733. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5734. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5735. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5736. Options);
  5737. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5738. SAFE_DESTROY(FSynchronizeProgressForm);
  5739. AnyOperation = (AChecklist->CheckedCount > 0);
  5740. if (AnyOperation)
  5741. {
  5742. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5743. CreateProgressForm(&SynchronizeProgress);
  5744. try
  5745. {
  5746. Terminal->SynchronizeApply(
  5747. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5748. SynchronizeProcessedItem, NULL, NULL, NULL);
  5749. }
  5750. __finally
  5751. {
  5752. DestroyProgressForm();
  5753. }
  5754. }
  5755. }
  5756. __finally
  5757. {
  5758. if (Checklist == NULL)
  5759. {
  5760. delete AChecklist;
  5761. }
  5762. else
  5763. {
  5764. *Checklist = AChecklist;
  5765. }
  5766. FAutoOperation = false;
  5767. SAFE_DESTROY(FSynchronizeProgressForm);
  5768. BatchEnd(BatchStorage);
  5769. ReloadLocalDirectory();
  5770. if (AnyOperation)
  5771. {
  5772. OperationComplete(StartTime);
  5773. }
  5774. }
  5775. }
  5776. //---------------------------------------------------------------------------
  5777. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5778. {
  5779. // can be called from command line
  5780. return Visible &&
  5781. ((DirView(osRemote)->SelCount > 0) ||
  5782. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5783. }
  5784. //---------------------------------------------------------------------------
  5785. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5786. {
  5787. LogSynchronizeEvent(Terminal, Message);
  5788. }
  5789. //---------------------------------------------------------------------------
  5790. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5791. int Params, TSynchronizeOptions & Options)
  5792. {
  5793. DebugAssert(!IsLocalBrowserMode());
  5794. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5795. {
  5796. Options.Filter = new TStringList();
  5797. Options.Filter->CaseSensitive = false;
  5798. Options.Filter->Duplicates = Types::dupAccept;
  5799. if (DirView(osRemote)->SelCount > 0)
  5800. {
  5801. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5802. }
  5803. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5804. {
  5805. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5806. }
  5807. Options.Filter->Sort();
  5808. }
  5809. }
  5810. //---------------------------------------------------------------------------
  5811. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5812. {
  5813. TCopyParamType Defaults;
  5814. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5815. ConfigStorage->AccessMode = smRead;
  5816. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5817. {
  5818. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5819. }
  5820. ConfigStorage.reset(NULL);
  5821. std::unique_ptr<TStringList> Options(new TStringList());
  5822. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5823. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5824. UnicodeString Result;
  5825. if (Options->Count > 0)
  5826. {
  5827. Result =
  5828. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5829. }
  5830. return Result;
  5831. }
  5832. //---------------------------------------------------------------------------
  5833. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5834. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5835. {
  5836. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5837. UnicodeString AdditionalParams =
  5838. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5839. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5840. SerializeCopyParamForCommandLine(CopyParams),
  5841. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5842. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5843. ExecuteNewInstance(SessionName, AdditionalParams);
  5844. }
  5845. //---------------------------------------------------------------------------
  5846. struct TSynchronizeParams
  5847. {
  5848. UnicodeString LocalDirectory;
  5849. UnicodeString RemoteDirectory;
  5850. TSynchronizeMode Mode;
  5851. TSynchronizeChecklist * Checklist;
  5852. int Params;
  5853. TCopyParamType * CopyParam;
  5854. TDateTime CollectElapsed;
  5855. TDateTime * StartTime;
  5856. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5857. };
  5858. //---------------------------------------------------------------------------
  5859. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5860. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5861. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5862. {
  5863. DebugAssert(!FAutoOperation);
  5864. void * BatchStorage;
  5865. BatchStart(BatchStorage);
  5866. FAutoOperation = true;
  5867. TFileOperationStatistics Statistics;
  5868. TDateTime Start = Now();
  5869. try
  5870. {
  5871. Params.OnProcessedItem = OnProcessedItem;
  5872. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5873. CreateProgressForm(&SynchronizeProgress);
  5874. Terminal->SynchronizeApply(
  5875. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5876. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5877. &Statistics);
  5878. }
  5879. __finally
  5880. {
  5881. Params.OnProcessedItem = NULL;
  5882. FAutoOperation = false;
  5883. DestroyProgressForm();
  5884. BatchEnd(BatchStorage);
  5885. ReloadLocalDirectory();
  5886. }
  5887. if (WinConfiguration->SynchronizeSummary)
  5888. {
  5889. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5890. // The statistics should be 0 anyway in this case
  5891. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5892. {
  5893. Message += L"\n";
  5894. if (Statistics.FilesUploaded > 0)
  5895. {
  5896. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5897. }
  5898. if (Statistics.FilesDownloaded > 0)
  5899. {
  5900. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5901. }
  5902. if (Statistics.FilesDeletedLocal > 0)
  5903. {
  5904. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5905. }
  5906. if (Statistics.FilesDeletedRemote > 0)
  5907. {
  5908. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5909. }
  5910. }
  5911. TDateTime Elapsed = (Now() - Start);
  5912. Message +=
  5913. L"\n" +
  5914. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5915. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5916. TMessageParams Params(mpNeverAskAgainCheck);
  5917. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5918. if (Result == qaNeverAskAgain)
  5919. {
  5920. WinConfiguration->SynchronizeSummary = false;
  5921. }
  5922. }
  5923. }
  5924. //---------------------------------------------------------------------------
  5925. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5926. {
  5927. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5928. {
  5929. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5930. }
  5931. // Not set in keep-up-to-date mode - Synchronize() method
  5932. if (Token != NULL)
  5933. {
  5934. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5935. if (Params.OnProcessedItem != NULL)
  5936. {
  5937. Params.OnProcessedItem(NULL, ChecklistItem);
  5938. }
  5939. }
  5940. }
  5941. //---------------------------------------------------------------------------
  5942. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5943. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5944. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5945. {
  5946. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5947. *Params.StartTime = Now();
  5948. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5949. }
  5950. //---------------------------------------------------------------------------
  5951. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5952. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5953. {
  5954. // terminal can be already closed (e.g. dropped connection)
  5955. if (Terminal != NULL)
  5956. {
  5957. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5958. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5959. }
  5960. }
  5961. //---------------------------------------------------------------------------
  5962. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5963. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5964. {
  5965. DebugAssert(!IsLocalBrowserMode());
  5966. TAutoBatch AutoBatch(this);
  5967. TAutoFlag AutoOperationFlag(FAutoOperation);
  5968. if (Side == osRemote)
  5969. {
  5970. std::unique_ptr<TStrings> FileList(new TStringList());
  5971. FileList->AddObject(FileName, RemoteFile);
  5972. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5973. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5974. RemoteDirView->SaveSelection();
  5975. RemoteDirView->SaveSelectedNames();
  5976. try
  5977. {
  5978. Terminal->MoveFiles(FileList.get(), Target, FileMask, false);
  5979. }
  5980. catch(...)
  5981. {
  5982. RemoteDirView->DiscardSavedSelection();
  5983. throw;
  5984. }
  5985. RemoteDirView->RestoreSelection();
  5986. }
  5987. else if (DebugAlwaysTrue(Side == osLocal))
  5988. {
  5989. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5990. {
  5991. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5992. }
  5993. UnicodeString Directory = ExtractFileDir(FileName);
  5994. ReloadLocalDirectory(Directory);
  5995. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5996. if (!SamePaths(Directory, NewDirectory))
  5997. {
  5998. ReloadLocalDirectory(NewDirectory);
  5999. }
  6000. }
  6001. }
  6002. //---------------------------------------------------------------------------
  6003. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  6004. {
  6005. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  6006. if (Side == osLocal)
  6007. {
  6008. if (Action == TSynchronizeChecklist::saDownloadNew)
  6009. {
  6010. OpenFolderInExplorer(LocalPath);
  6011. }
  6012. else
  6013. {
  6014. OpenFileInExplorer(TPath::Combine(LocalPath, Item->GetFileName()));
  6015. }
  6016. }
  6017. else if (DebugAlwaysTrue(Side == osRemote))
  6018. {
  6019. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6020. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6021. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6022. if (!LocalPath.IsEmpty())
  6023. {
  6024. SessionData->LocalDirectory = LocalPath;
  6025. }
  6026. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6027. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  6028. }
  6029. }
  6030. //---------------------------------------------------------------------------
  6031. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6032. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6033. const TCopyParamType * CopyParams)
  6034. {
  6035. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6036. UnicodeString AdditionalParams =
  6037. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6038. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6039. SerializeCopyParamForCommandLine(CopyParams),
  6040. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6041. LocalDirectory, RemoteDirectory, Mode, Params));
  6042. ExecuteNewInstance(SessionName, AdditionalParams);
  6043. }
  6044. //---------------------------------------------------------------------------
  6045. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6046. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6047. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6048. {
  6049. int Result;
  6050. bool SaveSettings = false;
  6051. int Options =
  6052. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6053. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6054. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6055. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6056. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6057. bool Continue =
  6058. ((UseDefaults == 0) ||
  6059. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6060. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6061. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6062. if (Continue)
  6063. {
  6064. Configuration->Usage->Inc(L"Synchronizations");
  6065. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6066. UpdateCopyParamCounters(CopyParam);
  6067. TSynchronizeOptions SynchronizeOptions;
  6068. GetSynchronizeOptions(Params, SynchronizeOptions);
  6069. if (SaveSettings)
  6070. {
  6071. GUIConfiguration->SynchronizeParams = Params;
  6072. }
  6073. else
  6074. {
  6075. SaveMode = false;
  6076. }
  6077. TDateTime StartTime = Now();
  6078. TSynchronizeChecklist * Checklist = NULL;
  6079. try
  6080. {
  6081. DebugAssert(!FAutoOperation);
  6082. FAutoOperation = true;
  6083. try
  6084. {
  6085. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6086. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6087. int Files = -1;
  6088. if (DataList->Count >= 1)
  6089. {
  6090. Files = StrToIntDef(DataList->Strings[0], Files);
  6091. }
  6092. else
  6093. {
  6094. DataList->Add(UnicodeString());
  6095. }
  6096. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6097. FSynchronizeProgressForm->Start();
  6098. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6099. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6100. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6101. &SynchronizeOptions);
  6102. if (Terminal->SessionData->CacheDirectories)
  6103. {
  6104. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6105. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6106. }
  6107. }
  6108. __finally
  6109. {
  6110. FAutoOperation = false;
  6111. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6112. SAFE_DESTROY(FSynchronizeProgressForm);
  6113. }
  6114. TSynchronizeParams SynchronizeParams;
  6115. SynchronizeParams.LocalDirectory = LocalDirectory;
  6116. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6117. SynchronizeParams.Mode = Mode;
  6118. SynchronizeParams.CopyParam = &CopyParam;
  6119. SynchronizeParams.Params = Params;
  6120. SynchronizeParams.Checklist = Checklist;
  6121. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6122. SynchronizeParams.StartTime = &StartTime;
  6123. SynchronizeParams.OnProcessedItem = NULL;
  6124. Result = Checklist->Count;
  6125. if (Checklist->Count > 0)
  6126. {
  6127. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6128. {
  6129. if (!DoSynchronizeChecklistDialog(
  6130. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6131. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  6132. {
  6133. Result = -1;
  6134. }
  6135. }
  6136. else
  6137. {
  6138. FullSynchronize(SynchronizeParams, NULL, NULL);
  6139. }
  6140. }
  6141. else
  6142. {
  6143. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6144. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6145. }
  6146. }
  6147. __finally
  6148. {
  6149. delete Checklist;
  6150. }
  6151. OperationComplete(StartTime);
  6152. }
  6153. else
  6154. {
  6155. Result = -1;
  6156. }
  6157. return Result;
  6158. }
  6159. //---------------------------------------------------------------------------
  6160. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6161. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6162. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6163. {
  6164. if (Collect)
  6165. {
  6166. DebugAssert(FSynchronizeProgressForm != NULL);
  6167. if (!FSynchronizeProgressForm->Started)
  6168. {
  6169. FSynchronizeProgressForm->Start();
  6170. }
  6171. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6172. SetTaskbarListProgressValue(CompareProgress);
  6173. }
  6174. else
  6175. {
  6176. DebugAssert(FSynchronizeProgressForm == NULL);
  6177. DebugAssert(FProgressForm != NULL);
  6178. }
  6179. }
  6180. //---------------------------------------------------------------------------
  6181. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6182. {
  6183. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6184. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6185. if (File.get() != NULL)
  6186. {
  6187. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6188. Application->ShowMainForm = false;
  6189. Application->Run();
  6190. }
  6191. }
  6192. //---------------------------------------------------------------------------
  6193. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6194. {
  6195. DebugFail();
  6196. }
  6197. //---------------------------------------------------------------------------
  6198. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6199. {
  6200. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6201. SessionData->Assign(ManagedSession->SessionData);
  6202. UpdateSessionData(SessionData.get());
  6203. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6204. if (IsActiveTerminal(ManagedSession))
  6205. {
  6206. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6207. }
  6208. if (!ManagedSession->SessionData->HasSessionName())
  6209. {
  6210. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6211. // once IsWorkspace is cleared
  6212. SessionData->Name = UnicodeString();
  6213. }
  6214. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6215. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6216. SessionData->IsWorkspace = false;
  6217. return SessionData.release();
  6218. }
  6219. //---------------------------------------------------------------------------
  6220. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6221. {
  6222. TSessionData * SessionData = CloneCurrentSessionData();
  6223. try
  6224. {
  6225. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6226. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6227. }
  6228. __finally
  6229. {
  6230. delete SessionData;
  6231. }
  6232. }
  6233. //---------------------------------------------------------------------------
  6234. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6235. {
  6236. TTerminalManager * Manager = TTerminalManager::Instance();
  6237. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6238. if (DebugAlwaysTrue(ManagedSession != NULL))
  6239. {
  6240. // Update ManagedSession->StateData
  6241. UpdateSession(ManagedSession);
  6242. }
  6243. Manager->SaveWorkspace(DataList.get());
  6244. return DataList.release();
  6245. }
  6246. //---------------------------------------------------------------------------
  6247. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6248. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6249. {
  6250. WinConfiguration->LastWorkspace = Name;
  6251. if (!SavePasswords)
  6252. {
  6253. for (int Index = 0; Index < DataList->Count; Index++)
  6254. {
  6255. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6256. if (SessionData->Link.IsEmpty())
  6257. {
  6258. SessionData->ClearSessionPasswords();
  6259. }
  6260. }
  6261. }
  6262. StoredSessions->NewWorkspace(Name, DataList);
  6263. // modified only
  6264. StoredSessions->Save(false, Explicit);
  6265. }
  6266. //---------------------------------------------------------------------------
  6267. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6268. {
  6269. return
  6270. DefaultStr(WinConfiguration->LastWorkspace,
  6271. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6272. }
  6273. //---------------------------------------------------------------------------
  6274. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6275. {
  6276. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6277. bool AnyNonStoredSessionWithPassword = false;
  6278. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6279. bool AllNonStoredSessionsAnonymous = true;
  6280. TTerminalManager * Manager = TTerminalManager::Instance();
  6281. for (int Index = 0; Index < DataList->Count; Index++)
  6282. {
  6283. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6284. if (SessionData->Link.IsEmpty())
  6285. {
  6286. if (SessionData->HasAnySessionPassword())
  6287. {
  6288. AnyNonStoredSessionWithPassword = true;
  6289. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6290. {
  6291. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6292. }
  6293. }
  6294. if (!SameText(SessionData->UserName, AnonymousUserName))
  6295. {
  6296. AllNonStoredSessionsAnonymous = false;
  6297. }
  6298. }
  6299. }
  6300. bool SavePasswords;
  6301. bool * PSavePasswords;
  6302. bool NotRecommendedSavingPasswords =
  6303. !CustomWinConfiguration->UseMasterPassword &&
  6304. !AllNonStoredSessionsAnonymous;
  6305. if (Configuration->DisablePasswordStoring ||
  6306. !AnyNonStoredSessionWithPassword)
  6307. {
  6308. PSavePasswords = NULL;
  6309. SavePasswords = false;
  6310. }
  6311. else
  6312. {
  6313. PSavePasswords = &SavePasswords;
  6314. SavePasswords =
  6315. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6316. !NotRecommendedSavingPasswords;
  6317. }
  6318. UnicodeString Name = WorkspaceName();
  6319. bool CreateShortcut = false;
  6320. bool Result =
  6321. DoSaveWorkspaceDialog(
  6322. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6323. EnableAutoSave);
  6324. if (Result)
  6325. {
  6326. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6327. if (CreateShortcut)
  6328. {
  6329. TOperationVisualizer Visualizer;
  6330. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6331. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6332. }
  6333. if (EnableAutoSave)
  6334. {
  6335. WinConfiguration->AutoSaveWorkspace = true;
  6336. WinConfiguration->AutoWorkspace = Name;
  6337. if (PSavePasswords != NULL)
  6338. {
  6339. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6340. }
  6341. }
  6342. }
  6343. return Result;
  6344. }
  6345. //---------------------------------------------------------------------------
  6346. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6347. {
  6348. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6349. DebugAssert(Session == ManagedSession);
  6350. if (!IsLocalBrowserMode())
  6351. {
  6352. SAFE_DESTROY(Session->RemoteExplorerState);
  6353. if (WinConfiguration->PreservePanelState)
  6354. {
  6355. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6356. }
  6357. }
  6358. UpdateSessionData(Session->StateData);
  6359. }
  6360. //---------------------------------------------------------------------------
  6361. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6362. {
  6363. // Keep in sync with TSessionData::CopyStateData
  6364. DebugAssert(Data != NULL);
  6365. // This is inconsistent with how color (for example) is handled.
  6366. Data->Name = ManagedSession->SessionData->Name;
  6367. if (!IsLocalBrowserMode())
  6368. {
  6369. // cannot use RemoteDirView->Path, because it is empty if connection
  6370. // was already closed
  6371. // also only peek, we may not be connected at all atm
  6372. // so make sure we do not try retrieving current directory from the server
  6373. // (particularly with FTP)
  6374. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6375. if (!ACurrentDirectory.IsEmpty())
  6376. {
  6377. Data->RemoteDirectory = ACurrentDirectory;
  6378. }
  6379. }
  6380. Data->Color = SessionColor;
  6381. }
  6382. //---------------------------------------------------------------------------
  6383. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6384. {
  6385. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6386. DebugAssert(Toolbar != NULL);
  6387. for (int i = 0; i < Toolbar->Items->Count; i++)
  6388. {
  6389. TTBXCustomDropDownItem * DropDownItem;
  6390. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6391. if (DropDownItem != NULL)
  6392. {
  6393. ToolbarItemResize(DropDownItem,
  6394. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6395. Toolbar->NonClientWidth);
  6396. break;
  6397. }
  6398. }
  6399. }
  6400. //---------------------------------------------------------------------------
  6401. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6402. {
  6403. Item->EditWidth = Width;
  6404. }
  6405. //---------------------------------------------------------------------------
  6406. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6407. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6408. {
  6409. for (int i = 0; i < Toolbar->Items->Count; i++)
  6410. {
  6411. TTBXCustomDropDownItem * DropDownItem;
  6412. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6413. if (DropDownItem != NULL)
  6414. {
  6415. ASize.x -= DropDownItem->EditWidth;
  6416. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6417. }
  6418. }
  6419. }
  6420. //---------------------------------------------------------------------------
  6421. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6422. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6423. {
  6424. if (WinConfiguration->DDWarnLackOfTempSpace)
  6425. {
  6426. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6427. if (!ADrive.IsEmpty())
  6428. {
  6429. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6430. DebugAssert(RequiredSpace >= 0);
  6431. __int64 RequiredWithReserve;
  6432. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6433. if (FreeSpace < RequiredWithReserve)
  6434. {
  6435. unsigned int Result;
  6436. TMessageParams Params(mpNeverAskAgainCheck);
  6437. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6438. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6439. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6440. if (Result == qaNeverAskAgain)
  6441. {
  6442. WinConfiguration->DDWarnLackOfTempSpace = false;
  6443. }
  6444. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6445. }
  6446. }
  6447. }
  6448. }
  6449. //---------------------------------------------------------------------------
  6450. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6451. {
  6452. DoOpenDirectoryDialog(odAddBookmark, Side);
  6453. }
  6454. //---------------------------------------------------------------------------
  6455. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6456. {
  6457. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6458. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6459. try
  6460. {
  6461. TCustomDirView * DView = DirView(Side);
  6462. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6463. {
  6464. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6465. }
  6466. }
  6467. catch (...)
  6468. {
  6469. delete VisitedDirectories;
  6470. throw;
  6471. }
  6472. return VisitedDirectories;
  6473. }
  6474. //---------------------------------------------------------------------------
  6475. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6476. TOpenDirectoryMode Mode, TOperationSide Side)
  6477. {
  6478. bool Continue = true;
  6479. if (Mode == odAddBookmark)
  6480. {
  6481. TMessageParams Params(mpNeverAskAgainCheck);
  6482. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6483. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6484. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6485. unsigned int Answer =
  6486. MessageDialog(Message,
  6487. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6488. if (Answer == qaNeverAskAgain)
  6489. {
  6490. Continue = true;
  6491. WinConfiguration->UseSharedBookmarks = true;
  6492. }
  6493. else if (Answer == qaOK)
  6494. {
  6495. Continue = true;
  6496. WinConfiguration->UseSharedBookmarks = false;
  6497. }
  6498. else
  6499. {
  6500. Continue = false;
  6501. }
  6502. }
  6503. if (Continue)
  6504. {
  6505. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6506. try
  6507. {
  6508. UnicodeString Name = DirView(Side)->PathName;
  6509. bool Repeat;
  6510. do
  6511. {
  6512. Repeat = false;
  6513. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6514. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6515. // do not allow switching to location profiles,
  6516. // if we are not connected
  6517. HasDirView[osLocal] && (Terminal != NULL)))
  6518. {
  6519. TWindowLock Lock(this);
  6520. if (!TryOpenDirectory(Side, Name))
  6521. {
  6522. Repeat = true;
  6523. Mode = odBrowse;
  6524. }
  6525. }
  6526. }
  6527. while (Repeat);
  6528. }
  6529. __finally
  6530. {
  6531. delete VisitedDirectories;
  6532. }
  6533. }
  6534. }
  6535. //---------------------------------------------------------------------------
  6536. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6537. {
  6538. DebugAssert(!Terminal->CommandSessionOpened);
  6539. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6540. }
  6541. //---------------------------------------------------------------------------
  6542. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6543. {
  6544. bool Result = Terminal->IsCapable[Capability] ||
  6545. Terminal->CommandSessionOpened;
  6546. if (!Result)
  6547. {
  6548. DebugAssert(Terminal->IsCapable[fcSecondaryShell]);
  6549. if (!GUIConfiguration->ConfirmCommandSession)
  6550. {
  6551. Result = true;
  6552. }
  6553. else
  6554. {
  6555. TMessageParams Params(mpNeverAskAgainCheck);
  6556. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6557. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6558. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6559. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6560. if (Answer == qaNeverAskAgain)
  6561. {
  6562. GUIConfiguration->ConfirmCommandSession = false;
  6563. Result = true;
  6564. }
  6565. else if (Answer == qaOK)
  6566. {
  6567. Result = true;
  6568. }
  6569. }
  6570. if (Result)
  6571. {
  6572. Result = CommandSessionFallback();
  6573. }
  6574. }
  6575. return Result;
  6576. }
  6577. //---------------------------------------------------------------------------
  6578. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6579. {
  6580. if (EnsureCommandSessionFallback(fcAnyCommand))
  6581. {
  6582. DoConsoleDialog(Terminal, Command);
  6583. }
  6584. }
  6585. //---------------------------------------------------------------------------
  6586. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6587. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6588. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6589. {
  6590. if (!IsSideLocalBrowser(osRemote) &&
  6591. IsFileControl(DropSourceControl, osRemote) &&
  6592. (FDDExtMapFile != NULL))
  6593. {
  6594. Accept = true;
  6595. }
  6596. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6597. DebugAssert(FDDTargetControl != NULL);
  6598. }
  6599. //---------------------------------------------------------------------------
  6600. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6601. _di_IDataObject DataObj, int KeyState,
  6602. const TPoint & Point, int & Effect, bool & Accept)
  6603. {
  6604. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6605. }
  6606. //---------------------------------------------------------------------------
  6607. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6608. _di_IDataObject DataObj, int KeyState,
  6609. const TPoint & Point, int & Effect, bool & Accept)
  6610. {
  6611. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6612. }
  6613. //---------------------------------------------------------------------------
  6614. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6615. TObject * Sender)
  6616. {
  6617. DebugUsedParam(Sender);
  6618. DebugAssert(FDDTargetControl == Sender);
  6619. FDDTargetControl = NULL;
  6620. }
  6621. //---------------------------------------------------------------------------
  6622. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6623. {
  6624. FileControlDDDragLeave(SessionsPageControl);
  6625. }
  6626. //---------------------------------------------------------------------------
  6627. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6628. {
  6629. FileControlDDDragLeave(QueueView3);
  6630. }
  6631. //---------------------------------------------------------------------------
  6632. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6633. {
  6634. DebugAssert(!IsSideLocalBrowser(Side));
  6635. DebugUsedParam(Side);
  6636. bool Edit = false;
  6637. TRemoteFile * File = NULL;
  6638. UnicodeString FileName;
  6639. UnicodeString PointTo;
  6640. bool SymbolicLink = true;
  6641. if (RemoteDirView->ItemFocused)
  6642. {
  6643. DebugAssert(RemoteDirView->ItemFocused->Data);
  6644. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6645. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6646. if (Edit)
  6647. {
  6648. FileName = File->FileName;
  6649. PointTo = File->LinkTo;
  6650. }
  6651. else if (!File->IsParentDirectory)
  6652. {
  6653. PointTo = File->FileName;
  6654. }
  6655. }
  6656. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6657. Terminal->IsCapable[fcHardLink]))
  6658. {
  6659. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6660. if (Edit)
  6661. {
  6662. DebugAssert(File->FileName == FileName);
  6663. int Params = dfNoRecursive;
  6664. Terminal->ExceptionOnFail = true;
  6665. try
  6666. {
  6667. Terminal->DeleteFile(L"", File, &Params);
  6668. }
  6669. __finally
  6670. {
  6671. Terminal->ExceptionOnFail = false;
  6672. }
  6673. }
  6674. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6675. }
  6676. }
  6677. //---------------------------------------------------------------------------
  6678. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6679. {
  6680. return
  6681. (IsSideLocalBrowser(Side) ||
  6682. (HasActiveTerminal() &&
  6683. Terminal->ResolvingSymlinks &&
  6684. Terminal->IsCapable[fcSymbolicLink]));
  6685. }
  6686. //---------------------------------------------------------------------------
  6687. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6688. {
  6689. return
  6690. !IsSideLocalBrowser(FCurrentSide) &&
  6691. (RemoteDirView->ItemFocused != NULL) &&
  6692. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6693. Terminal->SessionData->ResolveSymlinks;
  6694. }
  6695. //---------------------------------------------------------------------------
  6696. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6697. {
  6698. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6699. FForceExecution = true;
  6700. try
  6701. {
  6702. DirView(osCurrent)->ExecuteCurrentFile();
  6703. }
  6704. __finally
  6705. {
  6706. FForceExecution = false;
  6707. }
  6708. }
  6709. //---------------------------------------------------------------------------
  6710. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6711. {
  6712. TEditorData ExternalEditor;
  6713. ExternalEditor.Editor = edExternal;
  6714. bool Remember = false;
  6715. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6716. {
  6717. if (Remember)
  6718. {
  6719. TEditorList * EditorList = new TEditorList;
  6720. try
  6721. {
  6722. *EditorList = *WinConfiguration->EditorList;
  6723. bool Found = false;
  6724. int i = 0;
  6725. while (!Found && (i < EditorList->Count))
  6726. {
  6727. const TEditorPreferences * Editor = EditorList->Editors[i];
  6728. if ((Editor->Data->Editor == edExternal) &&
  6729. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6730. {
  6731. Found = true;
  6732. }
  6733. i++;
  6734. }
  6735. if (!Found)
  6736. {
  6737. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6738. WinConfiguration->EditorList = EditorList;
  6739. }
  6740. }
  6741. __finally
  6742. {
  6743. delete EditorList;
  6744. }
  6745. }
  6746. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6747. }
  6748. }
  6749. //---------------------------------------------------------------------------
  6750. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6751. {
  6752. if (FFileFindTerminal == ATerminal)
  6753. {
  6754. FFileFindTerminal = NULL;
  6755. HideFileFindDialog();
  6756. }
  6757. if (FClipboardTerminal == ATerminal)
  6758. {
  6759. ClipboardClear(); // implies ClipboardStop
  6760. }
  6761. if ((FOnSynchronizeAbort != NULL) &&
  6762. (ATerminal == FManagedSession))
  6763. {
  6764. FOnSynchronizeAbort(NULL);
  6765. }
  6766. }
  6767. //---------------------------------------------------------------------------
  6768. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6769. {
  6770. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6771. DetachTerminal(Sender);
  6772. }
  6773. //---------------------------------------------------------------------------
  6774. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6775. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6776. {
  6777. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6778. DebugAssert(Terminal != NULL);
  6779. if (Data->Terminal == Terminal)
  6780. {
  6781. Data->Terminal = NULL;
  6782. }
  6783. }
  6784. //---------------------------------------------------------------------------
  6785. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6786. {
  6787. return NULL;
  6788. }
  6789. //---------------------------------------------------------------------------
  6790. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6791. {
  6792. UpdateControls();
  6793. SessionColor = TColor(0);
  6794. UpdateRemotePathComboBox(false);
  6795. NeedSession(false);
  6796. }
  6797. //---------------------------------------------------------------------------
  6798. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6799. {
  6800. try
  6801. {
  6802. // Cache, as the login dialog can change its value.
  6803. // See also DoShow. Also see TTerminalManager::NewSession.
  6804. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6805. try
  6806. {
  6807. if (ShowLogin)
  6808. {
  6809. bool ReloadSessions = !Startup;
  6810. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6811. }
  6812. }
  6813. __finally
  6814. {
  6815. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6816. // (so there was no chance for the user to open any session yet)
  6817. if ((ShowLogin || !Startup) &&
  6818. !WinConfiguration->KeepOpenWhenNoSession &&
  6819. // this rules out the implicit Commander's local-local browser
  6820. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6821. {
  6822. TerminateApplication();
  6823. }
  6824. }
  6825. }
  6826. catch (EAbort &)
  6827. {
  6828. // swallow
  6829. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6830. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6831. }
  6832. }
  6833. //---------------------------------------------------------------------------
  6834. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6835. {
  6836. TTerminalManager * Manager = TTerminalManager::Instance();
  6837. DebugAssert(!Manager->Updating);
  6838. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6839. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6840. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6841. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6842. try
  6843. {
  6844. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6845. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6846. {
  6847. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6848. }
  6849. for (int Index = 0; Index <= Manager->Count; Index++)
  6850. {
  6851. TThemeTabSheet * TabSheet;
  6852. if (Index >= SessionsPageControl->PageCount)
  6853. {
  6854. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6855. TabSheet->PageControl = SessionsPageControl;
  6856. }
  6857. else
  6858. {
  6859. TabSheet = SessionsPageControl->Pages[Index];
  6860. }
  6861. bool IsSessionTab = (Index < Manager->Count);
  6862. if (IsSessionTab)
  6863. {
  6864. TTerminal * Terminal = Manager->Sessions[Index];
  6865. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6866. TabSheet->CaptionTruncation = tttEllipsis;
  6867. UpdateSessionTab(TabSheet);
  6868. }
  6869. else
  6870. {
  6871. TabSheet->Tag = 0; // not really needed
  6872. TabSheet->Shadowed = false;
  6873. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6874. TabSheet->CaptionTruncation = tttNoText;
  6875. // 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)
  6876. UpdateNewTabTab();
  6877. }
  6878. }
  6879. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6880. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6881. {
  6882. SessionsPageControl->UpdateTabsCaptionTruncation();
  6883. }
  6884. }
  6885. __finally
  6886. {
  6887. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6888. }
  6889. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6890. }
  6891. //---------------------------------------------------------------------------
  6892. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6893. {
  6894. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6895. }
  6896. //---------------------------------------------------------------------------
  6897. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6898. {
  6899. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6900. UnicodeString TabCaption;
  6901. if (WinConfiguration->SelectiveToolbarText)
  6902. {
  6903. TabCaption = GetNewTabTabCaption();
  6904. }
  6905. TabSheet->BaseCaption = TabCaption;
  6906. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6907. }
  6908. //---------------------------------------------------------------------------
  6909. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6910. {
  6911. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6912. }
  6913. //---------------------------------------------------------------------------
  6914. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6915. {
  6916. DebugFail();
  6917. return UnicodeString();
  6918. }
  6919. //---------------------------------------------------------------------------
  6920. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6921. {
  6922. if (DebugAlwaysTrue(TabSheet != NULL))
  6923. {
  6924. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6925. if (DebugAlwaysTrue(ASession != NULL))
  6926. {
  6927. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6928. if (ASession->LocalBrowser)
  6929. {
  6930. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6931. }
  6932. else
  6933. {
  6934. TabSheet->ImageIndex = AddSessionColor(Color);
  6935. }
  6936. TTerminalManager * Manager = TTerminalManager::Instance();
  6937. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6938. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6939. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6940. }
  6941. }
  6942. }
  6943. //---------------------------------------------------------------------------
  6944. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6945. {
  6946. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6947. }
  6948. //---------------------------------------------------------------------------
  6949. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6950. {
  6951. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6952. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6953. bool Result = (Session != NULL);
  6954. if (Result)
  6955. {
  6956. TTerminalManager::Instance()->ActiveSession = Session;
  6957. }
  6958. else
  6959. {
  6960. try
  6961. {
  6962. NewTab();
  6963. }
  6964. __finally
  6965. {
  6966. SessionListChanged();
  6967. }
  6968. FSessionsPageControlNewTabTime = Now();
  6969. }
  6970. return Result;
  6971. }
  6972. //---------------------------------------------------------------------------
  6973. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6974. {
  6975. TWindowLock Lock(this);
  6976. SessionTabSwitched();
  6977. }
  6978. //---------------------------------------------------------------------------
  6979. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6980. {
  6981. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6982. DebugAssert(TransferList != NULL);
  6983. UnicodeString Name;
  6984. if (TransferList->ItemIndex <= 0)
  6985. {
  6986. Name = L"";
  6987. }
  6988. else
  6989. {
  6990. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  6991. }
  6992. if (FCopyParamAutoSelected.IsEmpty())
  6993. {
  6994. // if previous preset was not autoselected, make new preset the "default"
  6995. FCopyParamDefault = Name;
  6996. }
  6997. GUIConfiguration->CopyParamCurrent = Name;
  6998. }
  6999. //---------------------------------------------------------------------------
  7000. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7001. {
  7002. // sanity check
  7003. bool ExistingPreset =
  7004. (FTransferListHoverIndex >= 0) &&
  7005. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7006. DebugAssert(ExistingPreset);
  7007. if (ExistingPreset)
  7008. {
  7009. HDC DC = GetDC(0);
  7010. TCanvas * Canvas = new TCanvas();
  7011. try
  7012. {
  7013. Canvas->Handle = DC;
  7014. Canvas->Font = GetToolbarFont(this);
  7015. UnicodeString Name;
  7016. if (FTransferListHoverIndex == 0)
  7017. {
  7018. Name = L"";
  7019. }
  7020. else
  7021. {
  7022. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7023. }
  7024. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7025. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7026. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7027. static_cast<TObject*>(GetComponent(fcTransferList)));
  7028. UnicodeString InfoStr =
  7029. GUIConfiguration->CopyParamPreset[Name].
  7030. GetInfoStr(L"; ",
  7031. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7032. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7033. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7034. {
  7035. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7036. {
  7037. InfoStr.SetLength(InfoStr.Length() - 1);
  7038. }
  7039. InfoStr += Ellipsis;
  7040. }
  7041. // UpdateCaption does not cause invalidation of whole submenu, while
  7042. // setting Caption property does.
  7043. // also it probably does not resize the label, even if necessary
  7044. // (we do not want that anyway)
  7045. TransferLabel->UpdateCaption(InfoStr);
  7046. }
  7047. __finally
  7048. {
  7049. Canvas->Handle = NULL;
  7050. ReleaseDC(0, DC);
  7051. delete Canvas;
  7052. }
  7053. }
  7054. }
  7055. //---------------------------------------------------------------------------
  7056. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7057. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7058. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7059. {
  7060. if (FTransferListHoverIndex != AHoverIndex)
  7061. {
  7062. FTransferListHoverIndex = AHoverIndex;
  7063. UpdateTransferLabel();
  7064. }
  7065. }
  7066. //---------------------------------------------------------------------------
  7067. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7068. {
  7069. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7070. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7071. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7072. {
  7073. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7074. {
  7075. if (!NonVisualDataModule->Busy)
  7076. {
  7077. OpenDirectory(GetSide(osCurrent));
  7078. }
  7079. Message.Result = 1;
  7080. }
  7081. else
  7082. {
  7083. TForm::Dispatch(&Message);
  7084. }
  7085. }
  7086. else
  7087. {
  7088. TForm::Dispatch(&Message);
  7089. }
  7090. }
  7091. //---------------------------------------------------------------------------
  7092. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7093. {
  7094. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7095. if ((FIgnoreNextDialogChar != 0) &&
  7096. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7097. {
  7098. Message.Result = 1;
  7099. }
  7100. else
  7101. {
  7102. TForm::Dispatch(&Message);
  7103. }
  7104. FIgnoreNextDialogChar = 0;
  7105. }
  7106. //---------------------------------------------------------------------------
  7107. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7108. {
  7109. // The four low-order bits are used internally by Windows
  7110. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7111. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7112. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7113. // 61730 - restore thru double click - undocumented
  7114. // 61490 - maximize thru double click - undocumented
  7115. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7116. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7117. {
  7118. SysResizing(Cmd);
  7119. }
  7120. TForm::Dispatch(&Message);
  7121. }
  7122. //---------------------------------------------------------------------------
  7123. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7124. {
  7125. AppLog(L"Windows session end query");
  7126. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7127. // Also there no point returning TRUE as we are not able to
  7128. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7129. // Hence the process termination might be safer :)
  7130. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7131. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7132. {
  7133. Message.Result = FALSE;
  7134. }
  7135. else
  7136. {
  7137. Message.Result = TRUE;
  7138. }
  7139. // Do not call default handling as that triggers OnCloseQuery,
  7140. // where our implementation will popup confirmation dialogs, what we do not want,
  7141. // as per Vista guidelines:
  7142. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7143. }
  7144. //---------------------------------------------------------------------------
  7145. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7146. {
  7147. AppLog(L"Windows session end");
  7148. if (Message.EndSession && IsApplicationMinimized())
  7149. {
  7150. // WORKAROUND
  7151. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7152. // when it receives WM_ENDSESSION,
  7153. // but that sometimes (particularly when application is minimized) cause crashes.
  7154. // Crash popups message that blocks log off.
  7155. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7156. // so we call ExitProcess() immediately, not even trying to cleanup.
  7157. // It still causes beep, so there's likely some popup, but it does not block
  7158. // log off.
  7159. ExitProcess(0);
  7160. }
  7161. TForm::Dispatch(&Message);
  7162. }
  7163. #ifdef _DEBUG
  7164. //---------------------------------------------------------------------------
  7165. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7166. {
  7167. TForm::Dispatch(&Message);
  7168. }
  7169. #endif
  7170. //---------------------------------------------------------------------------
  7171. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7172. {
  7173. }
  7174. //---------------------------------------------------------------------------
  7175. void __fastcall TCustomScpExplorerForm::DoShow()
  7176. {
  7177. // Called from TCustomScpExplorerForm::CMShowingChanged
  7178. // only now are the controls resized finally, so the size constraints
  7179. // will not conflict with possibly very small window size
  7180. RestoreFormParams();
  7181. // This indicates that the form was rescaled after parameters were loaded and
  7182. // as most probably the parameters were actually saved with the current form scaling
  7183. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7184. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7185. // and no rounding problems will occur.
  7186. // See also RestoreForm.
  7187. // (we should be safe to call RestoreParams unconditionally)
  7188. if (PixelsPerInch != Screen->PixelsPerInch)
  7189. {
  7190. RestoreParams();
  7191. }
  7192. FixControlsPlacement();
  7193. if (Position == poDefaultPosOnly)
  7194. {
  7195. CutFormToDesktop(this);
  7196. }
  7197. TForm::DoShow();
  7198. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7199. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7200. // This was previously in NeedSession, where other related code is.
  7201. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7202. // unpleasantly shows briefly.
  7203. if ((ManagedSession == NULL) &&
  7204. !WinConfiguration->ShowLoginWhenNoSession &&
  7205. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7206. // This detects if workspace was saved the last time the main widow was closed
  7207. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7208. {
  7209. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7210. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7211. }
  7212. // Before main window displays
  7213. if (ManagedSession == NULL)
  7214. {
  7215. StartingWithoutSession();
  7216. }
  7217. UpdatePixelsPerInchMainWindowCounter();
  7218. FShowing = true;
  7219. }
  7220. //---------------------------------------------------------------------------
  7221. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7222. {
  7223. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7224. }
  7225. //---------------------------------------------------------------------------
  7226. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7227. {
  7228. SessionListChanged();
  7229. InitStatusBar();
  7230. UpdateControls();
  7231. }
  7232. //---------------------------------------------------------------------------
  7233. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7234. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7235. TNotifyEvent OnBalloonClick, TObject * UserData)
  7236. {
  7237. bool Do;
  7238. UnicodeString Message;
  7239. if (E == NULL)
  7240. {
  7241. Message = Str;
  7242. Do = true;
  7243. }
  7244. else
  7245. {
  7246. Do = ExceptionMessage(E, Message);
  7247. }
  7248. if (Do && WinConfiguration->BalloonNotifications)
  7249. {
  7250. UnicodeString Title;
  7251. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7252. {
  7253. Message = TrimLeft(Message);
  7254. }
  7255. else
  7256. {
  7257. Message = UnformatMessage(Message);
  7258. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7259. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7260. Title = LoadResourceString(Captions[Type]);
  7261. if (Terminal != NULL)
  7262. {
  7263. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7264. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7265. }
  7266. }
  7267. if (Seconds == 0)
  7268. {
  7269. Seconds = WinConfiguration->NotificationsTimeout;
  7270. }
  7271. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7272. }
  7273. }
  7274. //---------------------------------------------------------------------------
  7275. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7276. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7277. UnicodeString HelpKeyword, const TMessageParams * Params,
  7278. TTerminal * Terminal)
  7279. {
  7280. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7281. (FOnFeedSynchronizeError != NULL)) &&
  7282. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7283. {
  7284. if (FOnFeedSynchronizeError != NULL)
  7285. {
  7286. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7287. }
  7288. else
  7289. {
  7290. DebugAssert(FErrorList != NULL);
  7291. TStringList * MoreMessagesCopy = NULL;
  7292. if (MoreMessages)
  7293. {
  7294. MoreMessagesCopy = new TStringList();
  7295. MoreMessagesCopy->Assign(MoreMessages);
  7296. }
  7297. FErrorList->AddObject(Message, MoreMessagesCopy);
  7298. }
  7299. PopupTrayBalloon(Terminal, Message, Type);
  7300. return ContinueAnswer(Answers);
  7301. }
  7302. else
  7303. {
  7304. bool UseBalloon = FTrayIcon->Visible;
  7305. if (UseBalloon)
  7306. {
  7307. PopupTrayBalloon(Terminal, Message, Type);
  7308. }
  7309. unsigned int Result;
  7310. try
  7311. {
  7312. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7313. }
  7314. __finally
  7315. {
  7316. // cancel only balloon we popped up, otherwise we may cancel notification
  7317. // balloon that was there before the message dialog
  7318. // (such as "dd confirmation opt in balloon)
  7319. if (UseBalloon)
  7320. {
  7321. FTrayIcon->CancelBalloon();
  7322. }
  7323. }
  7324. return Result;
  7325. }
  7326. }
  7327. //---------------------------------------------------------------------------
  7328. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7329. TTerminal * Terminal, Exception * E)
  7330. {
  7331. if (FTrayIcon->Visible)
  7332. {
  7333. PopupTrayBalloon(Terminal, L"", qtError, E);
  7334. }
  7335. // particularly prevent opening new session from jump list,
  7336. // while exception is shown
  7337. NonVisualDataModule->StartBusy();
  7338. try
  7339. {
  7340. ShowExtendedExceptionEx(Terminal, E);
  7341. }
  7342. __finally
  7343. {
  7344. NonVisualDataModule->EndBusy();
  7345. FTrayIcon->CancelBalloon();
  7346. }
  7347. }
  7348. //---------------------------------------------------------------------------
  7349. void __fastcall TCustomScpExplorerForm::SessionReady()
  7350. {
  7351. InitStatusBar();
  7352. // cannot rely on active page being page for active terminal,
  7353. // as it can happen that active page is the "new session" page
  7354. // (e.g. when reconnecting active terminal, while login dialog
  7355. // invoked from "new session" page is modal)
  7356. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7357. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7358. }
  7359. //---------------------------------------------------------------------------
  7360. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7361. TTerminal * Terminal, Exception * E)
  7362. {
  7363. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7364. if (!Terminal->Active)
  7365. {
  7366. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7367. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7368. {
  7369. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7370. }
  7371. }
  7372. }
  7373. //---------------------------------------------------------------------------
  7374. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7375. UnicodeString Message, TQueryType Type,
  7376. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7377. {
  7378. if ((E == NULL) ||
  7379. ExceptionMessage(E, Message))
  7380. {
  7381. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7382. if (Important)
  7383. {
  7384. Seconds *= 5;
  7385. }
  7386. UnicodeString NoteMessage(UnformatMessage(Message));
  7387. if (Terminal != NULL)
  7388. {
  7389. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7390. NoteMessage = FORMAT(L"%s: %s",
  7391. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7392. }
  7393. if (WinConfiguration->BalloonNotifications)
  7394. {
  7395. AddNote(NoteMessage);
  7396. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7397. }
  7398. else
  7399. {
  7400. FlashOnBackground();
  7401. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7402. }
  7403. }
  7404. }
  7405. //---------------------------------------------------------------------------
  7406. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7407. {
  7408. RestoreApp();
  7409. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7410. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7411. !NonVisualDataModule->Busy)
  7412. {
  7413. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7414. TTerminalManager::Instance()->ActiveSession = Terminal;
  7415. if (!ComponentVisible[fcQueueView])
  7416. {
  7417. ToggleQueueVisibility();
  7418. GoToQueue();
  7419. }
  7420. }
  7421. }
  7422. //---------------------------------------------------------------------------
  7423. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7424. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7425. {
  7426. UnicodeString Message;
  7427. TNotifyEvent OnClick = NULL;
  7428. TObject * UserData = NULL;
  7429. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7430. switch (Event)
  7431. {
  7432. case qeEmptyButMonitored:
  7433. if ((ATerminal != Terminal) || QueueInvisible)
  7434. {
  7435. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7436. OnClick = QueueEmptyNoteClicked;
  7437. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7438. TerminalNoteData->Terminal = ATerminal;
  7439. UserData = TerminalNoteData;
  7440. }
  7441. break;
  7442. case qeEmpty:
  7443. OperationComplete(ATerminal->QueueOperationStart);
  7444. break;
  7445. case qePendingUserAction:
  7446. if ((ATerminal != Terminal) ||
  7447. (QueueInvisible && !IsQueueAutoPopup()))
  7448. {
  7449. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7450. }
  7451. break;
  7452. default:
  7453. DebugFail();
  7454. }
  7455. if (!Message.IsEmpty())
  7456. {
  7457. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7458. }
  7459. }
  7460. //---------------------------------------------------------------------------
  7461. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7462. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7463. {
  7464. if (FDDExtMapFile != NULL)
  7465. {
  7466. CloseHandle(FDDExtMapFile);
  7467. FDDExtMapFile = NULL;
  7468. }
  7469. if (WinConfiguration->DDFakeFile)
  7470. {
  7471. DDFakeFileInitDrag(FileList, Created);
  7472. }
  7473. }
  7474. //---------------------------------------------------------------------------
  7475. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7476. {
  7477. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7478. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7479. {
  7480. FFakeFileDropTarget = FileName;
  7481. }
  7482. }
  7483. //---------------------------------------------------------------------------
  7484. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7485. {
  7486. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7487. if (!ForceDirectories(ApiPath(Result)))
  7488. {
  7489. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7490. }
  7491. FileSetAttr(ApiPath(Result), faHidden);
  7492. return Result;
  7493. }
  7494. //---------------------------------------------------------------------------
  7495. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7496. bool & Created)
  7497. {
  7498. FFakeFileDropTarget = UnicodeString();
  7499. FDragFakeDirectory = CreateFakeTransferDirectory();
  7500. FileList->AddItem(NULL, FDragFakeDirectory);
  7501. Created = true;
  7502. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7503. {
  7504. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7505. }
  7506. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7507. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7508. {
  7509. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7510. TDragExtCommStruct* CommStruct;
  7511. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7512. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7513. DebugAssert(CommStruct != NULL);
  7514. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7515. CommStruct->Dragging = true;
  7516. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7517. LENOF(CommStruct->DropDest));
  7518. NULL_TERMINATE(CommStruct->DropDest);
  7519. UnmapViewOfFile(CommStruct);
  7520. }
  7521. }
  7522. //---------------------------------------------------------------------------
  7523. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7524. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7525. {
  7526. bool Result;
  7527. DebugAssert(!IsLocalBrowserMode());
  7528. if (Sender == RemoteDirView)
  7529. {
  7530. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7531. }
  7532. else
  7533. {
  7534. DebugAssert(Sender == RemoteDriveView);
  7535. TStrings * FileList = RemoteDriveView->DragFileList();
  7536. try
  7537. {
  7538. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7539. }
  7540. __finally
  7541. {
  7542. delete FileList;
  7543. }
  7544. }
  7545. if (FDDTargetControl == RemoteDriveView)
  7546. {
  7547. RemoteDriveView->UpdateDropTarget();
  7548. }
  7549. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7550. // or from tree view to dir view.
  7551. // foMove happens when file/dir is dragged from remote tree view outside of
  7552. // application via dragex
  7553. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7554. (DropSourceControl == RemoteDriveView))
  7555. {
  7556. RemoteDriveView->UpdateDropSource();
  7557. }
  7558. return Result;
  7559. }
  7560. //---------------------------------------------------------------------------
  7561. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7562. {
  7563. DebugAssert(!IsLocalBrowserMode());
  7564. // This also handles drops of remote files to queue.
  7565. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7566. SAFE_DESTROY(FDDFileList);
  7567. if (!FFakeFileDropTarget.IsEmpty())
  7568. {
  7569. RemoveDir(ApiPath(FFakeFileDropTarget));
  7570. }
  7571. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7572. {
  7573. try
  7574. {
  7575. TDragResult DDResult = (Sender == RemoteDirView) ?
  7576. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7577. // Focus is moved to the target application,
  7578. // but as we are going to present the UI, we need to steal the focus back.
  7579. // This most likely won't work though (windows does not allow application
  7580. // to steal focus most of the time)
  7581. Application->BringToFront();
  7582. // On older version of Windows we never got drMove here, see also comment below.
  7583. // On Windows 10, we get the "move".
  7584. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7585. {
  7586. UnicodeString TargetDirectory;
  7587. TFileOperation Operation;
  7588. // drInvalid may mean drMove, see comment below
  7589. switch (DDResult)
  7590. {
  7591. case drCopy:
  7592. Operation = foCopy;
  7593. break;
  7594. case drMove:
  7595. Operation = foMove;
  7596. break;
  7597. default:
  7598. DebugFail();
  7599. case drInvalid:
  7600. // prefer "copy" for safety
  7601. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7602. break;
  7603. }
  7604. TTransferOperationParam Param;
  7605. UnicodeString CounterName;
  7606. bool ForceQueue;
  7607. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7608. {
  7609. // we get drInvalid both if d&d was intercepted by ddext,
  7610. // and when users drops on no-drop location.
  7611. // we tell the difference by existence of response from ddext,
  7612. // so we ignore absence of response in this case
  7613. if (DDResult != drInvalid)
  7614. {
  7615. // here we know that the extension is installed,
  7616. // as it is checked as soon as drag&drop starts from
  7617. // RemoteFileControlDDCreateDragFileList
  7618. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7619. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7620. {
  7621. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7622. }
  7623. else
  7624. {
  7625. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7626. }
  7627. }
  7628. }
  7629. else
  7630. {
  7631. // download using fake file
  7632. Param.Temp = false;
  7633. Param.DragDrop = true;
  7634. if (ForceQueue)
  7635. {
  7636. Param.Queue = asOn;
  7637. }
  7638. if (Sender == RemoteDirView)
  7639. {
  7640. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7641. }
  7642. if (RemoteFileControlFileOperation(Sender, Operation,
  7643. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7644. {
  7645. Configuration->Usage->Inc(CounterName);
  7646. }
  7647. }
  7648. }
  7649. }
  7650. __finally
  7651. {
  7652. CloseHandle(FDDExtMapFile);
  7653. FDDExtMapFile = NULL;
  7654. delete FDragFakeMonitors;
  7655. FDragFakeMonitors = NULL;
  7656. RemoveDir(ApiPath(FDragFakeDirectory));
  7657. FDragFakeDirectory = L"";
  7658. FFakeFileDropTarget = UnicodeString();
  7659. }
  7660. }
  7661. if (FDragDropSshTerminate.get() != NULL)
  7662. {
  7663. FDragDropSshTerminate->Rethrow();
  7664. }
  7665. }
  7666. //---------------------------------------------------------------------------
  7667. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7668. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7669. {
  7670. // Remember drop effect so we know (when user drops files), if we copy or move
  7671. FLastDropEffect = dwEffect;
  7672. }
  7673. //---------------------------------------------------------------------------
  7674. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7675. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7676. {
  7677. bool Result;
  7678. if (FDDTargetControl == QueueView3)
  7679. {
  7680. Directory = DefaultDownloadTargetDirectory();
  7681. Result = true;
  7682. CounterName = L"DownloadsDragDropQueue";
  7683. ForceQueue = true;
  7684. }
  7685. else if (!FFakeFileDropTarget.IsEmpty())
  7686. {
  7687. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7688. Result = true;
  7689. ForceQueue = false;
  7690. CounterName = L"DownloadsDragDropFakeFile";
  7691. }
  7692. else
  7693. {
  7694. ForceQueue = false;
  7695. Enabled = false;
  7696. try
  7697. {
  7698. int Timer = 0;
  7699. Result = false;
  7700. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7701. {
  7702. {
  7703. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7704. TDragExtCommStruct* CommStruct;
  7705. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7706. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7707. DebugAssert(CommStruct != NULL);
  7708. Result = !CommStruct->Dragging;
  7709. if (Result)
  7710. {
  7711. Directory = ExtractFilePath(CommStruct->DropDest);
  7712. CounterName = L"DownloadsDragDropExternalExt";
  7713. }
  7714. UnmapViewOfFile(CommStruct);
  7715. }
  7716. if (!Result)
  7717. {
  7718. Sleep(50);
  7719. Timer += 50;
  7720. Application->ProcessMessages();
  7721. }
  7722. }
  7723. }
  7724. __finally
  7725. {
  7726. Enabled = true;
  7727. }
  7728. }
  7729. return Result;
  7730. }
  7731. //---------------------------------------------------------------------------
  7732. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7733. const UnicodeString TempDir, int SecDelay)
  7734. {
  7735. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7736. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7737. if (FDelayedDeletionTimer == NULL)
  7738. {
  7739. DebugAssert(HandleAllocated());
  7740. FDelayedDeletionTimer = new TTimer(this);
  7741. FDelayedDeletionTimer->Interval = 10000;
  7742. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7743. }
  7744. else
  7745. {
  7746. FDelayedDeletionTimer->Enabled = true;
  7747. }
  7748. }
  7749. //---------------------------------------------------------------------------
  7750. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7751. {
  7752. DebugAssert(FDelayedDeletionList != NULL);
  7753. TDateTime N = Now();
  7754. TDateTime Alert;
  7755. UnicodeString Directory;
  7756. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7757. {
  7758. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7759. if ((N >= Alert) || (Sender == NULL))
  7760. {
  7761. Directory = FDelayedDeletionList->Strings[Index];
  7762. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7763. {
  7764. FDelayedDeletionList->Delete(Index);
  7765. }
  7766. }
  7767. }
  7768. if (FDelayedDeletionList->Count == 0)
  7769. {
  7770. FDelayedDeletionTimer->Enabled = false;
  7771. }
  7772. }
  7773. //---------------------------------------------------------------------------
  7774. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7775. {
  7776. DebugAssert(!IsLocalBrowserMode());
  7777. if (IsFileControl(FDDTargetControl, osRemote) ||
  7778. (FDDTargetControl == SessionsPageControl))
  7779. {
  7780. TManagedTerminal * TargetTerminal = NULL;
  7781. TFileOperation Operation = foNone;
  7782. if (FDDTargetControl == SessionsPageControl)
  7783. {
  7784. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7785. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7786. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7787. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7788. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7789. {
  7790. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7791. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7792. {
  7793. Operation = foRemoteMove;
  7794. }
  7795. else
  7796. {
  7797. Operation = foRemoteCopy;
  7798. }
  7799. }
  7800. }
  7801. else
  7802. {
  7803. if (FLastDropEffect == DROPEFFECT_MOVE)
  7804. {
  7805. Operation = foRemoteMove;
  7806. }
  7807. else if (FLastDropEffect == DROPEFFECT_COPY)
  7808. {
  7809. Operation = foRemoteCopy;
  7810. }
  7811. }
  7812. if (Operation != foNone)
  7813. {
  7814. RemoteFileControlFileOperation(DropSourceControl,
  7815. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7816. }
  7817. // abort drag&drop
  7818. Abort();
  7819. }
  7820. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7821. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7822. (FDDTargetControl != QueueView3))
  7823. {
  7824. DebugAssert(!FDragTempDir.IsEmpty());
  7825. TTransferType Type;
  7826. UnicodeString TempDir = FDragTempDir;
  7827. // We clear FDragTempDir before calling
  7828. // just in case it fail (raises exception)
  7829. FDragTempDir = L"";
  7830. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7831. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7832. // empty directory parameter means temp directory -> don't display it!
  7833. UnicodeString TargetDir = L"";
  7834. int Options = 0;
  7835. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7836. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7837. {
  7838. Abort();
  7839. }
  7840. // TargetDir is set when dropped on local file control
  7841. // (this was workaround for legacy dirview event handling, now it should be
  7842. // made prettier)
  7843. if (TargetDir.IsEmpty())
  7844. {
  7845. TargetDir = TempDir;
  7846. if (ForceDirectories(ApiPath(TargetDir)))
  7847. {
  7848. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7849. FPendingTempSpaceWarn = true;
  7850. try
  7851. {
  7852. FDragDropOperation = true;
  7853. int Params = cpTemporary |
  7854. (Type == ttMove ? cpDelete : 0);
  7855. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7856. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7857. }
  7858. __finally
  7859. {
  7860. FDragDropOperation = false;
  7861. FPendingTempSpaceWarn = false;
  7862. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7863. }
  7864. }
  7865. else
  7866. {
  7867. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7868. }
  7869. }
  7870. }
  7871. }
  7872. //---------------------------------------------------------------------------
  7873. void __fastcall TCustomScpExplorerForm::DDDownload(
  7874. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7875. {
  7876. DebugAssert(!IsLocalBrowserMode());
  7877. TAutoBatch AutoBatch(this);
  7878. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7879. UpdateCopyParamCounters(*CopyParam);
  7880. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7881. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7882. {
  7883. RemoteDriveView->UpdateDropSource();
  7884. }
  7885. }
  7886. //---------------------------------------------------------------------------
  7887. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7888. {
  7889. public:
  7890. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7891. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7892. {
  7893. }
  7894. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7895. {
  7896. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7897. TDataObjectFilesEx::AllowData(FormatEtc);
  7898. }
  7899. };
  7900. //---------------------------------------------------------------------------
  7901. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7902. TObject * Sender, TDataObject *& DataObject)
  7903. {
  7904. if (FDDExtMapFile != NULL)
  7905. {
  7906. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7907. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7908. {
  7909. Abort();
  7910. }
  7911. if (FileList->Count > 0)
  7912. {
  7913. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7914. if (!FilesObject->IsValid(true, true))
  7915. {
  7916. FilesObject->_Release();
  7917. }
  7918. else
  7919. {
  7920. DataObject = FilesObject;
  7921. }
  7922. }
  7923. }
  7924. }
  7925. //---------------------------------------------------------------------------
  7926. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7927. {
  7928. DebugFail();
  7929. }
  7930. //---------------------------------------------------------------------------
  7931. void __fastcall TCustomScpExplorerForm::GoToTree()
  7932. {
  7933. ComponentVisible[fcRemoteTree] = true;
  7934. DriveView(osRemote)->SetFocus();
  7935. }
  7936. //---------------------------------------------------------------------------
  7937. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7938. TPanelExport Export)
  7939. {
  7940. TCustomDirView * DirView = this->DirView(Side);
  7941. std::unique_ptr<TStrings> ExportData(new TStringList());
  7942. switch (Export)
  7943. {
  7944. case pePath:
  7945. ExportData->Add(DirView->PathName);
  7946. break;
  7947. case peFileList:
  7948. case peFullFileList:
  7949. {
  7950. bool FullPath = (Export == peFullFileList);
  7951. DirView->CreateFileList(false, FullPath, ExportData.get());
  7952. for (int Index = 0; Index < ExportData->Count; Index++)
  7953. {
  7954. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7955. {
  7956. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7957. }
  7958. }
  7959. }
  7960. break;
  7961. default:
  7962. DebugFail();
  7963. }
  7964. return ExportData.release();
  7965. }
  7966. //---------------------------------------------------------------------------
  7967. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7968. TPanelExport Export, TPanelExportDestination Destination)
  7969. {
  7970. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7971. PanelExportStore(Side, Export, Destination, ExportData.get());
  7972. }
  7973. //---------------------------------------------------------------------------
  7974. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7975. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7976. TStrings * ExportData)
  7977. {
  7978. if (Destination == pedClipboard)
  7979. {
  7980. TInstantOperationVisualizer Visualizer;
  7981. CopyToClipboard(ExportData);
  7982. }
  7983. else
  7984. {
  7985. DebugFail();
  7986. }
  7987. }
  7988. //---------------------------------------------------------------------------
  7989. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  7990. {
  7991. TCustomDirView * DirView = this->DirView(Side);
  7992. UnicodeString Mask = DirView->Mask;
  7993. if (DoFilterMaskDialog(DirView, Mask))
  7994. {
  7995. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  7996. Configuration->Usage->Inc(L"Filters");
  7997. }
  7998. }
  7999. //---------------------------------------------------------------------------
  8000. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8001. {
  8002. return FQueueController->DefaultOperation();
  8003. }
  8004. //---------------------------------------------------------------------------
  8005. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8006. TQueueOperation Operation, void ** Param)
  8007. {
  8008. switch (Operation)
  8009. {
  8010. case qoPreferences:
  8011. return true;
  8012. case qoGoTo:
  8013. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8014. case qoOnceEmpty:
  8015. return IsAnythingQueued();
  8016. default:
  8017. return FQueueController->AllowOperation(Operation, Param);
  8018. }
  8019. }
  8020. //---------------------------------------------------------------------------
  8021. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8022. {
  8023. if (DebugAlwaysTrue(QueueView3->Visible))
  8024. {
  8025. QueueView3->SetFocus();
  8026. }
  8027. }
  8028. //---------------------------------------------------------------------------
  8029. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8030. TQueueOperation Operation, void * Param)
  8031. {
  8032. if (Operation == qoGoTo)
  8033. {
  8034. GoToQueue();
  8035. }
  8036. else if (Operation == qoPreferences)
  8037. {
  8038. PreferencesDialog(pmQueue);
  8039. }
  8040. else
  8041. {
  8042. FQueueController->ExecuteOperation(Operation, Param);
  8043. }
  8044. }
  8045. //---------------------------------------------------------------------------
  8046. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8047. {
  8048. return (Queue != NULL) && Queue->Enabled;
  8049. }
  8050. //---------------------------------------------------------------------------
  8051. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8052. {
  8053. DebugAssert(Queue != NULL);
  8054. if (Queue != NULL)
  8055. {
  8056. Queue->Enabled = !Queue->Enabled;
  8057. }
  8058. }
  8059. //---------------------------------------------------------------------------
  8060. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8061. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8062. {
  8063. FQueueActedItem = QueueView3->ItemFocused;
  8064. }
  8065. //---------------------------------------------------------------------------
  8066. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8067. {
  8068. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8069. }
  8070. //---------------------------------------------------------------------------
  8071. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8072. {
  8073. return
  8074. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8075. (QueueDock->Visible ? QueueDock->Height : 0) +
  8076. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8077. }
  8078. //---------------------------------------------------------------------------
  8079. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8080. {
  8081. return ScaleByTextHeight(this, 48);
  8082. }
  8083. //---------------------------------------------------------------------------
  8084. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8085. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8086. {
  8087. // when queue is hidden by double-clicking splitter, stray attempt to
  8088. // resize the panel with strange value arrives, make sure it is ignored
  8089. if (ComponentVisible[fcQueueView])
  8090. {
  8091. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8092. if (NewSize > MaxHeightLimit)
  8093. {
  8094. NewSize = MaxHeightLimit;
  8095. }
  8096. int MinHeightLimit =
  8097. GetStaticQueuePanelComponentsHeight() +
  8098. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8099. GetMinQueueViewHeight();
  8100. if (NewSize < MinHeightLimit)
  8101. {
  8102. NewSize = MinHeightLimit;
  8103. }
  8104. }
  8105. else
  8106. {
  8107. Accept = false;
  8108. }
  8109. }
  8110. //---------------------------------------------------------------------------
  8111. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8112. {
  8113. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8114. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8115. if (QueueViewHeight < GetMinQueueViewHeight())
  8116. {
  8117. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8118. }
  8119. }
  8120. //---------------------------------------------------------------------------
  8121. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8122. TDragObject *& /*DragObject*/)
  8123. {
  8124. FQueueActedItem = QueueView3->ItemFocused;
  8125. FQueueScrollOnDragOver->StartDrag();
  8126. }
  8127. //---------------------------------------------------------------------------
  8128. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8129. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8130. {
  8131. FQueueScrollOnDragOver->EndDrag();
  8132. }
  8133. //---------------------------------------------------------------------------
  8134. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8135. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8136. {
  8137. Accept = true;
  8138. if (Source == QueueView3)
  8139. {
  8140. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8141. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8142. if (Accept)
  8143. {
  8144. TQueueItemProxy * QueueItem;
  8145. TQueueItemProxy * DestQueueItem;
  8146. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8147. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8148. Accept = (QueueItem != DestQueueItem) &&
  8149. (QueueItem->Status == TQueueItem::qsPending) &&
  8150. (DestQueueItem->Status == TQueueItem::qsPending);
  8151. }
  8152. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8153. }
  8154. }
  8155. //---------------------------------------------------------------------------
  8156. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8157. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8158. {
  8159. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8160. {
  8161. TQueueItemProxy * QueueItem;
  8162. TQueueItemProxy * DestQueueItem;
  8163. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8164. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8165. QueueItem->Move(DestQueueItem);
  8166. }
  8167. }
  8168. //---------------------------------------------------------------------------
  8169. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8170. {
  8171. if ((QueueView3->ItemFocused == NULL) &&
  8172. (QueueView3->Items->Count > 0))
  8173. {
  8174. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8175. }
  8176. QueueLabelUpdateStatus();
  8177. }
  8178. //---------------------------------------------------------------------------
  8179. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8180. {
  8181. QueueLabelUpdateStatus();
  8182. }
  8183. //---------------------------------------------------------------------------
  8184. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8185. {
  8186. QueueLabel->UpdateStatus();
  8187. }
  8188. //---------------------------------------------------------------------------
  8189. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8190. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8191. {
  8192. if (Selected)
  8193. {
  8194. NonVisualDataModule->UpdateNonVisibleActions();
  8195. }
  8196. }
  8197. //---------------------------------------------------------------------------
  8198. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8199. {
  8200. TDragDropFilesEx * Result = NULL;
  8201. if (Sender == SessionsPageControl)
  8202. {
  8203. Result = FSessionsDragDropFilesEx;
  8204. }
  8205. else if (Sender == QueueView3)
  8206. {
  8207. Result = FQueueDragDropFilesEx;
  8208. }
  8209. else
  8210. {
  8211. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8212. if (DirView != NULL)
  8213. {
  8214. Result = DirView->DragDropFilesEx;
  8215. }
  8216. else
  8217. {
  8218. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8219. if (DriveView != NULL)
  8220. {
  8221. Result = DriveView->DragDropFilesEx;
  8222. }
  8223. }
  8224. }
  8225. DebugAssert(Result != NULL);
  8226. return Result;
  8227. }
  8228. //---------------------------------------------------------------------------
  8229. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8230. {
  8231. return (DView->SelCount == DView->FilesCount);
  8232. }
  8233. //---------------------------------------------------------------------------
  8234. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8235. {
  8236. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8237. }
  8238. //---------------------------------------------------------------------------
  8239. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8240. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8241. {
  8242. DebugAssert(!IsLocalBrowserMode());
  8243. TFileOperation Operation;
  8244. switch (Effect)
  8245. {
  8246. case DROPEFFECT_MOVE:
  8247. Operation = foMove;
  8248. break;
  8249. case DROPEFFECT_COPY:
  8250. // occures on WinXP (reported by user)
  8251. default:
  8252. Operation = foCopy;
  8253. break;
  8254. };
  8255. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8256. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8257. if (DragDropFilesEx->FileList->Count > 0)
  8258. {
  8259. TStrings * FileList = new TStringList();
  8260. try
  8261. {
  8262. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8263. {
  8264. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8265. }
  8266. FDragDropOperation = true;
  8267. TTransferOperationParam Param;
  8268. Param.TargetDirectory = TargetPath;
  8269. // upload, no temp dirs
  8270. Param.Temp = false;
  8271. Param.DragDrop = DragDrop;
  8272. Param.Options =
  8273. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8274. if (ForceQueue)
  8275. {
  8276. Param.Queue = asOn;
  8277. }
  8278. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8279. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8280. {
  8281. if (IsFileControl(DropSourceControl, osLocal))
  8282. {
  8283. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8284. }
  8285. else
  8286. {
  8287. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8288. }
  8289. }
  8290. }
  8291. __finally
  8292. {
  8293. FDragDropOperation = false;
  8294. delete FileList;
  8295. }
  8296. }
  8297. }
  8298. //---------------------------------------------------------------------------
  8299. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8300. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8301. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8302. {
  8303. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8304. }
  8305. //---------------------------------------------------------------------------
  8306. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8307. TObject * Sender, int grfKeyState, int & dwEffect)
  8308. {
  8309. DebugAssert(!IsLocalBrowserMode());
  8310. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8311. if ((dwEffect != DROPEFFECT_NONE) &&
  8312. IsFileControl(DropSourceControl, osRemote))
  8313. {
  8314. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8315. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8316. (RemoteDirView->DropTarget == NULL))
  8317. {
  8318. dwEffect = DROPEFFECT_NONE;
  8319. }
  8320. else
  8321. {
  8322. if (dwEffect == DROPEFFECT_COPY)
  8323. {
  8324. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8325. // currently we support copying always (at least via temporary directory);
  8326. // remove associated checks once this all proves stable and working
  8327. bool CopyCapable = true;
  8328. // if we do not support neither of operations, there's no discussion
  8329. if (!MoveCapable && !CopyCapable)
  8330. {
  8331. dwEffect = DROPEFFECT_NONE;
  8332. }
  8333. else
  8334. {
  8335. // The default effect inside remote panel is move,
  8336. // unless we do not support it, but support copy
  8337. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8338. {
  8339. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8340. }
  8341. else
  8342. {
  8343. // with ctrl-down, we want copy unless it is not supported
  8344. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8345. }
  8346. }
  8347. }
  8348. }
  8349. }
  8350. }
  8351. //---------------------------------------------------------------------------
  8352. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8353. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8354. {
  8355. DebugAssert(!IsLocalBrowserMode());
  8356. if (FDDTotalSize >= 0)
  8357. {
  8358. if (File->IsDirectory)
  8359. {
  8360. FDDTotalSize = -1;
  8361. }
  8362. else
  8363. {
  8364. FDDTotalSize += File->Size;
  8365. }
  8366. }
  8367. DebugAssert(!FDragTempDir.IsEmpty());
  8368. // TODO: this is quite ineffective
  8369. // TODO: what if invalid character replacement is disabled?
  8370. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8371. UnicodeString TransferFileName;
  8372. if (Sender == RemoteDriveView)
  8373. {
  8374. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8375. }
  8376. else
  8377. {
  8378. TransferFileName = File->FileName;
  8379. }
  8380. FDDFileList->AddObject(TransferFileName, File);
  8381. }
  8382. //---------------------------------------------------------------------------
  8383. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8384. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8385. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8386. {
  8387. // sometimes we do not get DDEnd so the list is not released
  8388. SAFE_DESTROY(FDDFileList);
  8389. FDDFileList = new TStringList();
  8390. FDragTempDir = WinConfiguration->TemporaryDir();
  8391. FDDTotalSize = 0;
  8392. FDragDropSshTerminate.reset(NULL);
  8393. }
  8394. //---------------------------------------------------------------------------
  8395. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8396. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8397. HRESULT & Result)
  8398. {
  8399. if (Result == DRAGDROP_S_DROP)
  8400. {
  8401. try
  8402. {
  8403. GlobalDragImageList->HideDragImage();
  8404. try
  8405. {
  8406. RemoteFileControlDDTargetDrop();
  8407. }
  8408. catch(ESshTerminate & E)
  8409. {
  8410. FDragDropSshTerminate.reset(E.Clone());
  8411. }
  8412. }
  8413. catch (Exception &E)
  8414. {
  8415. // If downloading fails we need to cancel drag&drop, otherwise
  8416. // Explorer shows error
  8417. // But by the way exception probably never reach this point as
  8418. // it's catched on way.
  8419. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8420. Result = DRAGDROP_S_CANCEL;
  8421. ShowExtendedException(Terminal, &E);
  8422. }
  8423. }
  8424. }
  8425. //---------------------------------------------------------------------------
  8426. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8427. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8428. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8429. {
  8430. TFileMasks::TParams MaskParams;
  8431. MaskParams.Size = Size;
  8432. MaskParams.Modification = Modification;
  8433. // this does not re-parse the mask if it is the same as the last time
  8434. FDirViewMatchMask = Masks;
  8435. bool ImplicitMatch;
  8436. Matches =
  8437. // Local and RecurseInclude parameters have no effect as there's no path.
  8438. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8439. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8440. (AllowImplicitMatches || !ImplicitMatch);
  8441. }
  8442. //---------------------------------------------------------------------------
  8443. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8444. TObject * Sender, TListItem * Item, WORD & Indexes)
  8445. {
  8446. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8447. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8448. {
  8449. Indexes |= oiPartial;
  8450. }
  8451. }
  8452. //---------------------------------------------------------------------------
  8453. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8454. {
  8455. return
  8456. DirViewEnabled(osCurrent) &&
  8457. DirView(osCurrent)->CanPasteFromClipBoard();
  8458. }
  8459. //---------------------------------------------------------------------------
  8460. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8461. {
  8462. bool Result = false;
  8463. if (CanPasteToDirViewFromClipBoard())
  8464. {
  8465. Result = true;
  8466. }
  8467. else
  8468. {
  8469. UnicodeString ClipboardText;
  8470. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8471. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8472. {
  8473. if (StoredSessions->IsUrl(ClipboardText))
  8474. {
  8475. Result = true;
  8476. }
  8477. else
  8478. {
  8479. Result = DirViewEnabled(osCurrent);
  8480. }
  8481. }
  8482. }
  8483. return Result;
  8484. }
  8485. //---------------------------------------------------------------------------
  8486. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8487. {
  8488. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8489. if (DoesClipboardContainOurFiles())
  8490. {
  8491. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8492. {
  8493. DebugAssert(!IsLocalBrowserMode());
  8494. TTerminalManager * Manager = TTerminalManager::Instance();
  8495. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8496. Manager->ActiveSession = FClipboardTerminal;
  8497. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8498. }
  8499. }
  8500. else if (CanPasteToDirViewFromClipBoard())
  8501. {
  8502. DirView(osCurrent)->PasteFromClipBoard();
  8503. }
  8504. else
  8505. {
  8506. UnicodeString ClipboardText;
  8507. if (NonEmptyTextFromClipboard(ClipboardText))
  8508. {
  8509. if (StoredSessions->IsUrl(ClipboardText))
  8510. {
  8511. NewSession(ClipboardText);
  8512. }
  8513. else
  8514. {
  8515. DirView(osCurrent)->Path = ClipboardText;
  8516. }
  8517. }
  8518. }
  8519. }
  8520. //---------------------------------------------------------------------------
  8521. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8522. {
  8523. // TBD
  8524. }
  8525. //---------------------------------------------------------------------------
  8526. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8527. {
  8528. TCustomDirView * ADirView = DirView(Side);
  8529. ADirView->SelectAll(Mode);
  8530. ADirView->SetFocus();
  8531. }
  8532. //---------------------------------------------------------------------------
  8533. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8534. {
  8535. TCustomDirView * ADirView = DirView(Side);
  8536. TFileFilter Filter;
  8537. DefaultFileFilter(Filter);
  8538. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8539. {
  8540. Configuration->Usage->Inc(L"MaskSelections");
  8541. ADirView->SelectFiles(Filter, Select);
  8542. ADirView->SetFocus();
  8543. }
  8544. }
  8545. //---------------------------------------------------------------------------
  8546. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8547. {
  8548. TCustomDirView * ADirView = DirView(Side);
  8549. ADirView->RestoreSelectedNames();
  8550. ADirView->SetFocus();
  8551. }
  8552. //---------------------------------------------------------------------------
  8553. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8554. {
  8555. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8556. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8557. {
  8558. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8559. UnicodeString Ext;
  8560. if (!IsSideLocalBrowser(osCurrent))
  8561. {
  8562. Ext = UnixExtractFileExt(FileName);
  8563. }
  8564. else
  8565. {
  8566. Ext = ExtractFileExt(FileName);
  8567. }
  8568. if (Ext.IsEmpty())
  8569. {
  8570. Ext = L".";
  8571. }
  8572. TFileFilter Filter;
  8573. Filter.Masks = FORMAT(L"*%s", (Ext));
  8574. Filter.Directories = false;
  8575. CurrentDirView->SelectFiles(Filter, Select);
  8576. }
  8577. }
  8578. //---------------------------------------------------------------------------
  8579. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8580. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8581. {
  8582. UnicodeString Result;
  8583. if (!FIncrementalSearch.IsEmpty() && (Side == GetSide(osCurrent)))
  8584. {
  8585. Result = FormatIncrementalSearchStatus(FIncrementalSearch, FIncrementalSearchHaveNext);
  8586. }
  8587. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8588. {
  8589. // noop
  8590. }
  8591. else
  8592. {
  8593. Result =
  8594. FMTLOAD(FILE_INFO_FORMAT,
  8595. (FormatBytes(FileInfo.SelectedSize),
  8596. FormatBytes(FileInfo.FilesSize),
  8597. FormatNumber(FileInfo.SelectedCount),
  8598. FormatNumber(FileInfo.FilesCount)));
  8599. }
  8600. return Result;
  8601. }
  8602. //---------------------------------------------------------------------------
  8603. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8604. TTBXStatusPanel * Panel, TOperationSide Side)
  8605. {
  8606. if (Panel->Index == 1)
  8607. {
  8608. ToggleShowHiddenFiles();
  8609. }
  8610. else if (Panel->Index == 2)
  8611. {
  8612. Filter(Side);
  8613. }
  8614. }
  8615. //---------------------------------------------------------------------------
  8616. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8617. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8618. {
  8619. DebugAssert(!StatusBar->SimplePanel);
  8620. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8621. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8622. }
  8623. //---------------------------------------------------------------------------
  8624. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8625. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8626. {
  8627. DebugAssert(StatusBar->Panels->Count >= 3);
  8628. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8629. if (FileInfo.HiddenCount > 0)
  8630. {
  8631. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8632. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8633. }
  8634. else
  8635. {
  8636. HiddenFilesPanel->ViewPriority = 0;
  8637. // not really necessary, just to cleanup no-longer-valid data
  8638. HiddenFilesPanel->Caption = L"";
  8639. }
  8640. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8641. if (FileInfo.FilteredCount > 0)
  8642. {
  8643. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8644. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8645. }
  8646. else
  8647. {
  8648. FilteredFilesPanel->ViewPriority = 0;
  8649. // not really necessary, just to cleanup no-longer-valid data
  8650. FilteredFilesPanel->Caption = L"";
  8651. }
  8652. }
  8653. //---------------------------------------------------------------------------
  8654. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8655. TObject * /*Sender*/)
  8656. {
  8657. if (DirView(osOther)->Enabled)
  8658. {
  8659. DirView(osOther)->SetFocus();
  8660. }
  8661. }
  8662. //---------------------------------------------------------------------------
  8663. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8664. {
  8665. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8666. switch (Config.Show)
  8667. {
  8668. case qvShow:
  8669. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8670. {
  8671. Config.Show = qvHide;
  8672. }
  8673. else
  8674. {
  8675. Config.Show = Config.LastHideShow;
  8676. }
  8677. break;
  8678. case qvHideWhenEmpty:
  8679. if (ComponentVisible[fcQueueView])
  8680. {
  8681. Config.Show = qvHide;
  8682. }
  8683. else
  8684. {
  8685. Config.LastHideShow = Config.Show;
  8686. Config.Show = qvShow;
  8687. }
  8688. break;
  8689. case qvHide:
  8690. Config.LastHideShow = Config.Show;
  8691. Config.Show = qvShow;
  8692. break;
  8693. }
  8694. WinConfiguration->QueueView = Config;
  8695. }
  8696. //---------------------------------------------------------------------------
  8697. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8698. {
  8699. UnicodeString Result;
  8700. if (Terminal != NULL)
  8701. {
  8702. switch (WinConfiguration->PathInCaption)
  8703. {
  8704. case picShort:
  8705. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8706. break;
  8707. case picFull:
  8708. Result = Terminal->CurrentDirectory;
  8709. break;
  8710. }
  8711. }
  8712. return Result;
  8713. }
  8714. //---------------------------------------------------------------------------
  8715. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8716. {
  8717. TColor Result = GetWindowColor(FSessionColor);
  8718. return Result;
  8719. }
  8720. //---------------------------------------------------------------------------
  8721. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8722. {
  8723. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8724. return Result;
  8725. }
  8726. //---------------------------------------------------------------------------
  8727. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8728. {
  8729. if (!FSessionChanging)
  8730. {
  8731. TTerminalManager::Instance()->UpdateAppTitle();
  8732. }
  8733. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8734. // background to gray on Windows 7 (works on Windows 10).
  8735. // See also EnableControl
  8736. if (Showing)
  8737. {
  8738. if (ManagedSession != NULL)
  8739. {
  8740. // Update path when it changes
  8741. if ((SessionsPageControl->ActivePage != NULL) &&
  8742. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8743. {
  8744. UpdateSessionTab(SessionsPageControl->ActivePage);
  8745. }
  8746. }
  8747. NonVisualDataModule->ReconnectSessionAction->Update();
  8748. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8749. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8750. CenterReconnectToolbar();
  8751. bool HasTerminal = HasActiveTerminal();
  8752. RemoteDirView->Enabled = HasTerminal;
  8753. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8754. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8755. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8756. RemoteDriveView->Color = RemoteDirView->Color;
  8757. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8758. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8759. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8760. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8761. QueueFileList->Enabled = QueueView3->Enabled;
  8762. QueueFileList->Color = QueueView3->Color;
  8763. QueueFileList->Font->Color = QueueView3->Font->Color;
  8764. QueueLabelUpdateStatus();
  8765. RemoteDirView->DarkMode = WinConfiguration->UseDarkTheme();
  8766. RemoteDriveView->DarkMode = RemoteDirView->DarkMode;
  8767. if (FImmersiveDarkMode != WinConfiguration->UseDarkTheme())
  8768. {
  8769. UpdateDarkMode();
  8770. }
  8771. // As the hi-contrast theme is currently used for session tabs only, which currently do not support dark mode,
  8772. // we always use dark theme. But ultimatelly, we should use an opposite theme to the main one.
  8773. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8774. UnicodeString NewHiContrastThemeName = WinConfiguration->HiContrast ? GetThemeName(true) : EmptyStr;
  8775. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8776. {
  8777. ReleaseHiContrastTheme();
  8778. if (!NewHiContrastThemeName.IsEmpty())
  8779. {
  8780. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8781. }
  8782. SessionsPageControl->ActiveTabTheme = FHiContrastTheme;
  8783. }
  8784. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8785. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8786. }
  8787. }
  8788. //---------------------------------------------------------------------------
  8789. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8790. {
  8791. UpdateControls();
  8792. }
  8793. //---------------------------------------------------------------------------
  8794. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8795. TObject * Sender)
  8796. {
  8797. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8798. DebugAssert(DirView != NULL);
  8799. DoDirViewLoaded(DirView);
  8800. TransferPresetAutoSelect();
  8801. }
  8802. //---------------------------------------------------------------------------
  8803. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8804. {
  8805. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8806. // first run after installation
  8807. if (double(Updates.LastCheck) == 0)
  8808. {
  8809. AppLog(L"First run, scheduling updates check for the next run");
  8810. // make sure next time there will be an update (if enabled)
  8811. Updates.LastCheck = TDateTime(1);
  8812. WinConfiguration->Updates = Updates;
  8813. }
  8814. else
  8815. {
  8816. TDateTime Period;
  8817. if (IsUWP() && !IsOfficialPackage())
  8818. {
  8819. Period = DefaultUpdatesPeriod;
  8820. AppLog(L"Thirdparty UWP package, using default updates check period");
  8821. }
  8822. else
  8823. {
  8824. Period = Updates.Period;
  8825. }
  8826. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8827. if (double(Period) > 0)
  8828. {
  8829. TDateTime Interval = Now() - Updates.LastCheck;
  8830. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8831. if (Interval >= Period)
  8832. {
  8833. StartUpdateThread(UpdatesChecked);
  8834. }
  8835. }
  8836. }
  8837. }
  8838. //---------------------------------------------------------------------------
  8839. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8840. {
  8841. AppLog(L"Updates check done");
  8842. UnicodeString Message;
  8843. bool New;
  8844. TQueryType Type;
  8845. GetUpdatesMessage(Message, New, Type, false);
  8846. if (!Message.IsEmpty())
  8847. {
  8848. AppLogFmt(L"Updates check message: %s", (Message));
  8849. if (New)
  8850. {
  8851. AppLog(L"New version detected");
  8852. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8853. }
  8854. if (!New && (Type != qtWarning))
  8855. {
  8856. AppLog(L"Posting non-critical updates note");
  8857. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8858. }
  8859. else
  8860. {
  8861. AppLog(L"Posting new version or critical message notification");
  8862. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8863. }
  8864. if (New)
  8865. {
  8866. Configuration->Usage->Inc(L"UpdateNotifications");
  8867. }
  8868. }
  8869. }
  8870. //---------------------------------------------------------------------------
  8871. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8872. {
  8873. RestoreApp();
  8874. bool CanDisplay = !NonVisualDataModule->Busy;
  8875. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8876. {
  8877. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8878. }
  8879. if (CanDisplay)
  8880. {
  8881. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8882. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  8883. NonVisualDataModule->StartBusy();
  8884. try
  8885. {
  8886. CheckForUpdates(true);
  8887. }
  8888. __finally
  8889. {
  8890. NonVisualDataModule->EndBusy();
  8891. }
  8892. }
  8893. else
  8894. {
  8895. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8896. }
  8897. }
  8898. //---------------------------------------------------------------------------
  8899. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8900. TCopyParamRuleData & Data)
  8901. {
  8902. DebugAssert(Terminal != NULL);
  8903. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8904. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8905. Data.RemoteDirectory = RemoteDirView->PathName;
  8906. }
  8907. //---------------------------------------------------------------------------
  8908. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8909. {
  8910. // Terminal can be null when we are changing local directory implicitly,
  8911. // because it has been deleted, while no session is connected
  8912. // (Login dialog is open)
  8913. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8914. {
  8915. DebugAssert(!IsLocalBrowserMode());
  8916. TCopyParamRuleData Data;
  8917. GetTransferPresetAutoSelectData(Data);
  8918. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8919. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8920. if (CopyParamIndex < 0)
  8921. {
  8922. // there is no preset that matches autoselection
  8923. // set preset that we consider "default"
  8924. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8925. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8926. }
  8927. else
  8928. {
  8929. // there is preset matching autoselection
  8930. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8931. if (CopyParamName == FCopyParamAutoSelected)
  8932. {
  8933. // autoselected the same preset as the last time
  8934. // make no change (i.e. preserve custom user preset, if any)
  8935. }
  8936. else
  8937. {
  8938. // autoselected the different preset then the last time (or there
  8939. // was default preset set)
  8940. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8941. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8942. }
  8943. }
  8944. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8945. {
  8946. if (CopyParamIndex >= 0)
  8947. {
  8948. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8949. }
  8950. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8951. try
  8952. {
  8953. int Fmt =
  8954. (CopyParamIndex < 0) ?
  8955. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8956. COPY_PARAM_AUTOSELECTED;
  8957. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8958. Data->Message = MainInstructions(Message);
  8959. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8960. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8961. CopyParamAttrs);
  8962. if (CopyParamIndex >= 0)
  8963. {
  8964. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8965. Info = FORMAT(L"%s\n \n%s", (Info,
  8966. FMTLOAD(COPY_PARAM_RULE,
  8967. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8968. }
  8969. Data->Message += L"\n\n" + Info;
  8970. if (WinConfiguration->CopyParamAutoSelectNotice)
  8971. {
  8972. TransferPresetNoteMessage(Data, true);
  8973. }
  8974. else
  8975. {
  8976. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  8977. Data = NULL; // ownership passed
  8978. }
  8979. }
  8980. __finally
  8981. {
  8982. delete Data;
  8983. }
  8984. }
  8985. }
  8986. }
  8987. //---------------------------------------------------------------------------
  8988. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  8989. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  8990. {
  8991. DebugAssert(NoteData != NULL);
  8992. DebugAssert(!IsLocalBrowserMode());
  8993. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  8994. TQueryButtonAlias Aliases[1];
  8995. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  8996. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  8997. Params.Aliases = Aliases;
  8998. Params.AliasesCount = LENOF(Aliases);
  8999. unsigned int Result =
  9000. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9001. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9002. switch (Result)
  9003. {
  9004. case qaNeverAskAgain:
  9005. DebugAssert(AllowNeverAskAgain);
  9006. WinConfiguration->CopyParamAutoSelectNotice = false;
  9007. break;
  9008. case qaIgnore:
  9009. PreferencesDialog(pmPresets);
  9010. break;
  9011. }
  9012. }
  9013. //---------------------------------------------------------------------------
  9014. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9015. {
  9016. // as of now useless, as this is used for notes only, never for balloons, ...
  9017. RestoreApp();
  9018. // .. and we should never be busy here
  9019. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9020. {
  9021. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9022. }
  9023. }
  9024. //---------------------------------------------------------------------------
  9025. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9026. TPreferencesMode APreferencesMode)
  9027. {
  9028. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9029. TCopyParamRuleData Data;
  9030. if (Terminal != NULL)
  9031. {
  9032. PreferencesData.reset(new TPreferencesDialogData());
  9033. GetTransferPresetAutoSelectData(Data);
  9034. PreferencesData->CopyParamRuleData = &Data;
  9035. }
  9036. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9037. }
  9038. //---------------------------------------------------------------------------
  9039. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9040. const TCustomCommandType & Command)
  9041. {
  9042. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9043. {
  9044. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9045. }
  9046. }
  9047. //---------------------------------------------------------------------------
  9048. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9049. {
  9050. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9051. TCustomCommandType Command;
  9052. // make sure we use local custom command when remote are not supported
  9053. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9054. {
  9055. Command = FLastCustomCommand;
  9056. }
  9057. else
  9058. {
  9059. Command.Params = Command.Params | ccLocal;
  9060. }
  9061. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9062. FEditingFocusedAdHocCommand = OnFocused;
  9063. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9064. int Options =
  9065. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9066. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9067. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9068. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9069. {
  9070. FLastCustomCommand = Command;
  9071. UpdateCustomCommandsToolbar();
  9072. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9073. }
  9074. }
  9075. //---------------------------------------------------------------------------
  9076. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9077. {
  9078. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9079. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9080. DebugAssert(State > 0);
  9081. if (State <= 0)
  9082. {
  9083. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9084. }
  9085. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9086. }
  9087. //---------------------------------------------------------------------------
  9088. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9089. TCustomCommandType & Command, int & State)
  9090. {
  9091. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9092. if (Result)
  9093. {
  9094. Command = FLastCustomCommand;
  9095. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9096. }
  9097. return Result;
  9098. }
  9099. //---------------------------------------------------------------------------
  9100. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9101. {
  9102. ResetIncrementalSearch();
  9103. }
  9104. //---------------------------------------------------------------------------
  9105. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9106. {
  9107. DebugAssert(ComponentVisible[Component]);
  9108. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9109. }
  9110. //---------------------------------------------------------------------------
  9111. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9112. {
  9113. // when queue panel is resized here directly, the status bar is stretched
  9114. // over whole space the panel occupied
  9115. PostComponentHide(fcQueueView);
  9116. }
  9117. //---------------------------------------------------------------------------
  9118. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9119. {
  9120. ComponentVisible[fcQueueFileList] = false;
  9121. }
  9122. //---------------------------------------------------------------------------
  9123. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9124. {
  9125. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9126. RefreshColorMode();
  9127. ResetSysDarkTheme();
  9128. ConfigurationChanged();
  9129. ConfigureInterface();
  9130. // Should be called for all controls
  9131. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  9132. }
  9133. //---------------------------------------------------------------------------
  9134. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9135. {
  9136. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9137. if (!FInvalid &&
  9138. (Message.LParam != 0) &&
  9139. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9140. {
  9141. ThemeChanged();
  9142. }
  9143. TForm::Dispatch(&Message);
  9144. }
  9145. //---------------------------------------------------------------------------
  9146. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9147. {
  9148. TMessage * M = static_cast<TMessage*>(Message);
  9149. switch (M->Msg)
  9150. {
  9151. case CM_DIALOGCHAR:
  9152. CMDialogChar(*M);
  9153. break;
  9154. case WM_APPCOMMAND:
  9155. WMAppCommand(*M);
  9156. break;
  9157. case WM_SYSCOMMAND:
  9158. WMSysCommand(*M);
  9159. break;
  9160. case WM_QUERYENDSESSION:
  9161. WMQueryEndSession(*M);
  9162. break;
  9163. case WM_ENDSESSION:
  9164. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9165. break;
  9166. #ifdef _DEBUG
  9167. case WM_WINDOWPOSCHANGED:
  9168. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9169. break;
  9170. case CM_CUSTOMSTYLECHANGED:
  9171. TForm::Dispatch(Message);
  9172. break;
  9173. #endif
  9174. case WM_COMPONENT_HIDE:
  9175. {
  9176. Byte Component = static_cast<Byte>(M->WParam);
  9177. // sanity check
  9178. if (ComponentVisible[Component])
  9179. {
  9180. // special treatment
  9181. if (Component == fcQueueView)
  9182. {
  9183. ToggleQueueVisibility();
  9184. DebugAssert(!ComponentVisible[fcQueueView]);
  9185. }
  9186. else
  9187. {
  9188. ComponentVisible[Component] = false;
  9189. }
  9190. }
  9191. }
  9192. break;
  9193. case WM_COPYDATA:
  9194. WMCopyData(*M);
  9195. break;
  9196. case WM_MANAGES_CAPTION:
  9197. // caption managed in TTerminalManager::UpdateAppTitle()
  9198. M->Result = 1;
  9199. break;
  9200. case WM_WANTS_MOUSEWHEEL:
  9201. M->Result = 1;
  9202. break;
  9203. case CM_SHOWINGCHANGED:
  9204. CMShowingChanged(*M);
  9205. break;
  9206. case WM_CLOSE:
  9207. WMClose(*M);
  9208. break;
  9209. case WM_DPICHANGED:
  9210. WMDpiChanged(*M);
  9211. break;
  9212. case CM_DPICHANGED:
  9213. CMDpiChanged(*M);
  9214. break;
  9215. case WM_SETTINGCHANGE:
  9216. WMSettingChange(*M);
  9217. break;
  9218. case CM_DIALOGKEY:
  9219. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9220. break;
  9221. case WM_PASTE_FILES:
  9222. PasteFiles();
  9223. break;
  9224. case WM_IS_HIDDEN:
  9225. // To treat master password prompt as a main window while showing it when workspace is loading while
  9226. // the exporer is showing up (Visible is true already)
  9227. M->Result = !FShowing;
  9228. break;
  9229. case WM_SHOWWINDOW:
  9230. if (M->WParam)
  9231. {
  9232. AddStartupSequence(L"J");
  9233. }
  9234. TForm::Dispatch(Message);
  9235. break;
  9236. default:
  9237. TForm::Dispatch(Message);
  9238. break;
  9239. }
  9240. }
  9241. //---------------------------------------------------------------------------
  9242. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9243. {
  9244. // noop
  9245. }
  9246. //---------------------------------------------------------------------------
  9247. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  9248. {
  9249. TForm::Dispatch(&Message);
  9250. FSessionColors->Clear();
  9251. AddFixedSessionImages();
  9252. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9253. UpdateImages();
  9254. }
  9255. //---------------------------------------------------------------------------
  9256. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9257. {
  9258. TForm::Dispatch(&Message);
  9259. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9260. UpdatePixelsPerInchMainWindowCounter();
  9261. }
  9262. //---------------------------------------------------------------------------
  9263. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9264. {
  9265. AppLog(L"Main window WM_CLOSE");
  9266. // Cannot close window while we are busy.
  9267. // We cannot test this in FormCloseQuery as that is called also from
  9268. // Close(), which is called by CloseApplicationAction. So we can be busy
  9269. // there already even, when it is legitimate to close the application.
  9270. // Possibly a better place to handle this would be WMSysCommand.
  9271. if (NonVisualDataModule->Busy)
  9272. {
  9273. Message.Result = 1;
  9274. }
  9275. else
  9276. {
  9277. TForm::Dispatch(&Message);
  9278. }
  9279. }
  9280. //---------------------------------------------------------------------------
  9281. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9282. {
  9283. if (!FShowingChanged)
  9284. {
  9285. AddStartupSequence(L"D");
  9286. FShowingChanged = true;
  9287. }
  9288. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9289. bool NoSession = (ManagedSession == NULL);
  9290. // This calls TCustomScpExplorerForm::DoShow
  9291. TForm::Dispatch(&Message);
  9292. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9293. if (Showing && !FStarted)
  9294. {
  9295. FStarted = true;
  9296. InterfaceStarted();
  9297. }
  9298. if (Showing && NoSession)
  9299. {
  9300. // When we are starting minimized (i.e. from an installer),
  9301. // postpone showing Login dialog until we get restored.
  9302. // Otherwise the Login dialog (and Authentication window) show restored
  9303. // over invisible (minimized) main window.
  9304. if (WindowState == wsMinimized)
  9305. {
  9306. FNeedSession = true;
  9307. }
  9308. else
  9309. {
  9310. // This happens before application ever goes idle, so the toolbars would
  9311. // stay enabled (initial state) until the Login dialog is dismissed.
  9312. UpdateActions();
  9313. NonVisualDataModule->StartBusy();
  9314. try
  9315. {
  9316. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9317. // otherwise the dialog does not receive focus.
  9318. // With Commander interface the ProcessMessages is called already
  9319. // by TDriveView, but with Explorer interface, we need to call it explicily
  9320. Application->ProcessMessages();
  9321. // do not reload sessions, they have been loaded just now (optimization)
  9322. NeedSession(true);
  9323. }
  9324. __finally
  9325. {
  9326. NonVisualDataModule->EndBusy();
  9327. }
  9328. }
  9329. }
  9330. }
  9331. //---------------------------------------------------------------------------
  9332. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9333. {
  9334. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9335. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9336. }
  9337. //---------------------------------------------------------------------------
  9338. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9339. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9340. int & MaxHeight)
  9341. {
  9342. // workaround for bug in TWinControl.CalcConstraints
  9343. // Check for empty rect (restore from iconic state) is done there only after
  9344. // call to AdjustClientRect, which enlarges the rect (for forms).
  9345. TRect R = GetClientRect();
  9346. // when restoring from iconic state, place no restrictions
  9347. if (IsRectEmpty(R))
  9348. {
  9349. MinWidth = 0;
  9350. MinHeight = 0;
  9351. MaxWidth = 32000;
  9352. MaxHeight = 32000;
  9353. }
  9354. }
  9355. //---------------------------------------------------------------------------
  9356. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9357. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9358. {
  9359. // terminal can be already closed (e.g. dropped connection)
  9360. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9361. {
  9362. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9363. try
  9364. {
  9365. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9366. }
  9367. catch(...)
  9368. {
  9369. if (!Terminal->Active)
  9370. {
  9371. Close = true;
  9372. }
  9373. throw;
  9374. }
  9375. }
  9376. }
  9377. //---------------------------------------------------------------------------
  9378. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9379. {
  9380. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9381. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9382. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9383. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9384. {
  9385. OnGetSpaceAvailable = GetSpaceAvailable;
  9386. }
  9387. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9388. OnGetSpaceAvailable);
  9389. }
  9390. //---------------------------------------------------------------------------
  9391. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9392. {
  9393. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9394. Terminal->FillSessionDataForCode(Data.get());
  9395. return Data.release();
  9396. }
  9397. //---------------------------------------------------------------------------
  9398. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9399. {
  9400. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9401. DoGenerateUrlDialog(Data.get(), Paths);
  9402. }
  9403. //---------------------------------------------------------------------------
  9404. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9405. {
  9406. GenerateUrl(NULL);
  9407. }
  9408. //---------------------------------------------------------------------------
  9409. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9410. {
  9411. std::unique_ptr<TStrings> Paths(new TStringList());
  9412. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9413. GenerateUrl(Paths.get());
  9414. }
  9415. //---------------------------------------------------------------------------
  9416. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9417. {
  9418. FSessionColor = value;
  9419. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9420. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9421. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9422. DebugAssert(ColorItem != NULL);
  9423. ColorItem->Color = C;
  9424. NonVisualDataModule->ColorMenuItem->Color = C;
  9425. UpdateControls();
  9426. }
  9427. //---------------------------------------------------------------------------
  9428. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9429. {
  9430. if (value != FSessionColor)
  9431. {
  9432. UpdateSessionColor(value);
  9433. // Is null when called from LastTerminalClosed
  9434. if (Terminal != NULL)
  9435. {
  9436. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9437. }
  9438. }
  9439. }
  9440. //---------------------------------------------------------------------------
  9441. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9442. {
  9443. bool Result = FNoteTimer->Enabled;
  9444. if (Result)
  9445. {
  9446. // cannot cancel note too early
  9447. bool NotEarly =
  9448. (Now() - FNoteShown >
  9449. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9450. if (Force || NotEarly)
  9451. {
  9452. FNoteTimer->Enabled = false;
  9453. FNote = L"";
  9454. SAFE_DESTROY(FNoteData);
  9455. FOnNoteClick = NULL;
  9456. FNoteHints = FNotes->Text;
  9457. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9458. UpdateStatusBar();
  9459. }
  9460. }
  9461. return Result;
  9462. }
  9463. //---------------------------------------------------------------------------
  9464. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9465. {
  9466. DebugAssert(FNoteTimer->Enabled);
  9467. CancelNote(true);
  9468. }
  9469. //---------------------------------------------------------------------------
  9470. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9471. {
  9472. FNoteHints = FNotes->Text.TrimRight();
  9473. }
  9474. //---------------------------------------------------------------------------
  9475. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9476. {
  9477. int P = Note.Pos(L"\n");
  9478. if (P > 0)
  9479. {
  9480. Note.SetLength(P - 1);
  9481. }
  9482. FNotes->Add(FORMAT(L"[%s] %s",
  9483. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9484. while (FNotes->Count > 10)
  9485. {
  9486. FNotes->Delete(0);
  9487. }
  9488. if (UpdateNow)
  9489. {
  9490. UpdateNoteHints();
  9491. UpdateStatusBar();
  9492. }
  9493. }
  9494. //---------------------------------------------------------------------------
  9495. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9496. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9497. {
  9498. int P = Note.Pos(L"\n");
  9499. if (P > 0)
  9500. {
  9501. Note.SetLength(P - 1);
  9502. }
  9503. UpdateNoteHints();
  9504. FNote = Note;
  9505. SAFE_DESTROY(FNoteData);
  9506. FNoteData = NoteData;
  9507. FOnNoteClick = OnNoteClick;
  9508. AddNote(Note, false);
  9509. UpdateStatusBar();
  9510. FNoteShown = Now();
  9511. FNoteTimer->Enabled = false;
  9512. if (Seconds == 0)
  9513. {
  9514. Seconds = WinConfiguration->NotificationsTimeout;
  9515. }
  9516. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9517. FNoteTimer->Enabled = true;
  9518. }
  9519. //---------------------------------------------------------------------------
  9520. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9521. {
  9522. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9523. }
  9524. //---------------------------------------------------------------------------
  9525. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9526. {
  9527. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9528. {
  9529. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9530. }
  9531. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9532. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9533. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9534. 0, NULL, NULL);
  9535. }
  9536. //---------------------------------------------------------------------------
  9537. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9538. {
  9539. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9540. UnicodeString Note =
  9541. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9542. PostNote(Note, 0, NULL, NULL);
  9543. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9544. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9545. }
  9546. //---------------------------------------------------------------------------
  9547. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9548. {
  9549. WinConfiguration->FormatSizeBytes = Style;
  9550. }
  9551. //---------------------------------------------------------------------------
  9552. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9553. {
  9554. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9555. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9556. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9557. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9558. }
  9559. //---------------------------------------------------------------------------
  9560. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9561. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9562. {
  9563. if (Panel->Index == 0)
  9564. {
  9565. if (FOnNoteClick != NULL)
  9566. {
  9567. // prevent the user data from being freed by possible call
  9568. // to CancelNote or PostNote during call to OnNoteClick
  9569. std::unique_ptr<TObject> NoteData(FNoteData);
  9570. TNotifyEvent OnNoteClick = FOnNoteClick;
  9571. FNoteData = NULL;
  9572. // need to cancel the note as we are going to delete its user data
  9573. CancelNote(true);
  9574. OnNoteClick(NoteData.get());
  9575. }
  9576. }
  9577. if (HasActiveTerminal() &&
  9578. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9579. {
  9580. FileSystemInfo();
  9581. }
  9582. }
  9583. //---------------------------------------------------------------------------
  9584. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9585. {
  9586. // workaround:
  9587. // 1) for unknown reason, disabling window, while minimized,
  9588. // prevents it from restoring, even if it was enabled again meanwhile
  9589. // 2) when disabling the main window, while another has focus
  9590. // minimize is no longer possible
  9591. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9592. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9593. // Shouldn't we use IsApplicationMinimized() here?
  9594. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9595. {
  9596. Enabled = false;
  9597. }
  9598. FLockLevel++;
  9599. }
  9600. //---------------------------------------------------------------------------
  9601. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9602. {
  9603. DebugAssert(FLockLevel > 0);
  9604. FLockLevel--;
  9605. if (FLockLevel == 0)
  9606. {
  9607. DebugAssert(FLockSuspendLevel == 0);
  9608. Enabled = true;
  9609. }
  9610. }
  9611. //---------------------------------------------------------------------------
  9612. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9613. {
  9614. // We need to make sure that window is enabled when the last modal window closes
  9615. // otherwise focus is not restored correctly.
  9616. // So we re-enable the window when modal window opens and
  9617. // disable it back after is closes
  9618. if (FLockLevel > 0)
  9619. {
  9620. // while we have nesting counter, we know that we never be called
  9621. // recursivelly as Application->OnModalBegin is called only
  9622. // for the top-level modal window
  9623. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9624. {
  9625. // won't be disabled when conditions in LockWindow() were not satisfied
  9626. FDisabledOnLockSuspend = !Enabled;
  9627. // When minimized to tray (or actually when set to SW_HIDE),
  9628. // setting Enabled makes the window focusable even when there's
  9629. // modal window over it
  9630. if (!FTrayIcon->Visible)
  9631. {
  9632. Enabled = true;
  9633. }
  9634. }
  9635. FLockSuspendLevel++;
  9636. }
  9637. }
  9638. //---------------------------------------------------------------------------
  9639. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9640. {
  9641. if (FLockSuspendLevel > 0)
  9642. {
  9643. DebugAssert(FLockLevel > 0);
  9644. FLockSuspendLevel--;
  9645. // see comment in SuspendWindowLock
  9646. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9647. {
  9648. // Note that window can be enabled here, when we were minized to tray when
  9649. // was SuspendWindowLock() called.
  9650. // We should possibly do the same check as in LockWindow(),
  9651. // if it is ever possible that the consitions change between
  9652. // SuspendWindowLock() and ResumeWindowLock()
  9653. Enabled = !FDisabledOnLockSuspend;
  9654. }
  9655. }
  9656. }
  9657. //---------------------------------------------------------------------------
  9658. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9659. {
  9660. TTBXComboBoxItem * RemotePathComboBox =
  9661. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9662. if (!TextOnly)
  9663. {
  9664. TStrings * Items = RemotePathComboBox->Strings;
  9665. Items->BeginUpdate();
  9666. try
  9667. {
  9668. Items->Clear();
  9669. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9670. {
  9671. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9672. while (!IsUnixRootPath(APath))
  9673. {
  9674. int P = APath.LastDelimiter(L'/');
  9675. DebugAssert(P >= 0);
  9676. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9677. APath.SetLength(P - 1);
  9678. }
  9679. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9680. }
  9681. }
  9682. __finally
  9683. {
  9684. Items->EndUpdate();
  9685. }
  9686. }
  9687. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9688. // Setting ItemIndex to -1 does not reset its text
  9689. if (RemotePathComboBox->Strings->Count == 0)
  9690. {
  9691. RemotePathComboBox->Text = L"";
  9692. }
  9693. }
  9694. //---------------------------------------------------------------------------
  9695. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9696. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9697. {
  9698. if (AIndex < 0)
  9699. {
  9700. AIndex = Sender->ItemIndex;
  9701. }
  9702. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9703. }
  9704. //---------------------------------------------------------------------------
  9705. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9706. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9707. int & ImageIndex)
  9708. {
  9709. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9710. }
  9711. //---------------------------------------------------------------------------
  9712. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9713. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9714. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9715. {
  9716. if (!IsLocalBrowserMode())
  9717. {
  9718. ARect.Left += (10 * AIndex);
  9719. }
  9720. }
  9721. //---------------------------------------------------------------------------
  9722. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9723. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9724. {
  9725. AWidth += (10 * AIndex);
  9726. }
  9727. //---------------------------------------------------------------------------
  9728. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9729. {
  9730. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9731. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9732. int Index = RemotePathComboBox->ItemIndex;
  9733. while (Index < RemotePathComboBox->Strings->Count - 1)
  9734. {
  9735. APath = UnixExtractFileDir(APath);
  9736. Index++;
  9737. }
  9738. // VanDyke style paths
  9739. if (APath.IsEmpty())
  9740. {
  9741. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9742. APath = ROOTDIRECTORY;
  9743. }
  9744. if (RemoteDirView->Path != APath)
  9745. {
  9746. RemoteDirView->Path = APath;
  9747. }
  9748. }
  9749. //---------------------------------------------------------------------------
  9750. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9751. {
  9752. DoRemotePathComboBoxItemClick(Sender);
  9753. }
  9754. //---------------------------------------------------------------------------
  9755. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9756. {
  9757. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9758. DebugUsedParam(Sender);
  9759. UpdateRemotePathComboBox(true);
  9760. }
  9761. //---------------------------------------------------------------------------
  9762. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9763. {
  9764. DoRemotePathComboBoxCancel(Sender);
  9765. }
  9766. //---------------------------------------------------------------------------
  9767. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9768. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9769. {
  9770. ResetIncrementalSearch();
  9771. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9772. DebugAssert(DirView != NULL);
  9773. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9774. {
  9775. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9776. // OnEditing is called also from TCustomListView::CanEdit
  9777. if (Edit != NULL)
  9778. {
  9779. EditSelectBaseName(Edit);
  9780. }
  9781. }
  9782. }
  9783. //---------------------------------------------------------------------------
  9784. //---------------------------------------------------------------------------
  9785. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9786. {
  9787. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9788. Result->AutoDetectDnD = false;
  9789. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9790. Result->RenderDataOn = rdoEnterAndDropSync;
  9791. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9792. return Result;
  9793. }
  9794. //---------------------------------------------------------------------------
  9795. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9796. {
  9797. if (IsWin10Build(19041))
  9798. {
  9799. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9800. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9801. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9802. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9803. }
  9804. }
  9805. //---------------------------------------------------------------------------
  9806. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9807. {
  9808. TForm::CreateWnd();
  9809. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9810. UpdateDarkMode();
  9811. if (FSessionsDragDropFilesEx == NULL)
  9812. {
  9813. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9814. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9815. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9816. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9817. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9818. }
  9819. if (FQueueDragDropFilesEx == NULL)
  9820. {
  9821. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9822. // No need to set OnDragOver as we do not have any restrictions
  9823. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9824. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9825. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9826. }
  9827. }
  9828. //---------------------------------------------------------------------------
  9829. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9830. {
  9831. TForm::DestroyWnd();
  9832. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9833. FQueueDragDropFilesEx->DragDropControl = NULL;
  9834. }
  9835. //---------------------------------------------------------------------------
  9836. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9837. {
  9838. SideEnter(FCurrentSide);
  9839. FEverShown = true;
  9840. }
  9841. //---------------------------------------------------------------------------
  9842. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9843. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9844. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9845. {
  9846. if (!NonVisualDataModule->Busy)
  9847. {
  9848. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9849. Configuration->Usage->Inc(L"FileFinds");
  9850. LockWindow(true);
  9851. NonVisualDataModule->StartBusy();
  9852. WinConfiguration->LockedInterface = true;
  9853. try
  9854. {
  9855. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9856. }
  9857. __finally
  9858. {
  9859. WinConfiguration->LockedInterface = false;
  9860. NonVisualDataModule->EndBusy();
  9861. UnlockWindow();
  9862. }
  9863. }
  9864. }
  9865. //---------------------------------------------------------------------------
  9866. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9867. {
  9868. if (!NonVisualDataModule->Busy)
  9869. {
  9870. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9871. SetFocus();
  9872. RemoteDirView->Path = UnixExtractFilePath(Path);
  9873. UnicodeString FileName = UnixExtractFileName(Path);
  9874. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9875. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9876. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9877. if (Item == NULL)
  9878. {
  9879. ReloadDirectory(osRemote);
  9880. Item = RemoteDirView->FindFileItem(FileName);
  9881. }
  9882. if (Item != NULL)
  9883. {
  9884. RemoteDirView->ItemFocused = Item;
  9885. RemoteDirView->ItemFocused->MakeVisible(false);
  9886. RemoteDirView->SetFocus();
  9887. }
  9888. }
  9889. }
  9890. //---------------------------------------------------------------------------
  9891. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9892. {
  9893. bool Result = !NonVisualDataModule->Busy;
  9894. if (Result)
  9895. {
  9896. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9897. }
  9898. return Result;
  9899. }
  9900. //---------------------------------------------------------------------------
  9901. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9902. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9903. {
  9904. if (CanOperateOnFoundFiles(ATerminal))
  9905. {
  9906. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  9907. FOnFileOperationFinished = OnFileOperationFinished;
  9908. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9909. }
  9910. }
  9911. //---------------------------------------------------------------------------
  9912. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9913. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9914. {
  9915. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9916. }
  9917. //---------------------------------------------------------------------------
  9918. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9919. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9920. {
  9921. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9922. }
  9923. //---------------------------------------------------------------------------
  9924. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9925. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9926. {
  9927. if (CanOperateOnFoundFiles(ATerminal))
  9928. {
  9929. for (int Index = 0; Index < FileList->Count; Index++)
  9930. {
  9931. UnicodeString FileName = FileList->Strings[Index];
  9932. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9933. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9934. OnFileOperationFinished(osRemote, FileName, true);
  9935. }
  9936. }
  9937. }
  9938. //---------------------------------------------------------------------------
  9939. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9940. {
  9941. FFileFindTerminal = Terminal;
  9942. ShowFileFindDialog(
  9943. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  9944. DoDownloadFoundFiles, DoEditFoundFiles);
  9945. }
  9946. //---------------------------------------------------------------------------
  9947. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  9948. {
  9949. FTaskbarList = TaskbarList;
  9950. }
  9951. //---------------------------------------------------------------------------
  9952. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  9953. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  9954. {
  9955. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9956. if (Index >= 0)
  9957. {
  9958. if (Button == mbLeft)
  9959. {
  9960. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  9961. // If switching tab (switching session) takes long enough for user
  9962. // to actually release the button, "mouse down" is still raised,
  9963. // but we do not get "mouse up" event, so dragging is not cancelled,
  9964. // prevent that by not beginning dragging in the first place.
  9965. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  9966. if (IsKeyPressed(Key))
  9967. {
  9968. // when user clicks the "+", we get mouse down only after the session
  9969. // is closed, when new session tab is already on X:Y, so dragging
  9970. // starts, prevent that
  9971. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  9972. {
  9973. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9974. if (Terminal != NULL)
  9975. {
  9976. SessionsPageControl->BeginDrag(false);
  9977. }
  9978. }
  9979. }
  9980. }
  9981. else if (Button == mbMiddle)
  9982. {
  9983. // ignore middle-click for "New session tab" and the last local-local tab
  9984. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9985. if ((Session != NULL) && CanCloseSession(Session))
  9986. {
  9987. CloseSessionTab(Index);
  9988. }
  9989. }
  9990. }
  9991. }
  9992. //---------------------------------------------------------------------------
  9993. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  9994. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  9995. {
  9996. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9997. // do not allow dropping on the "+" tab
  9998. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  9999. if ((TargetTerminal != NULL) &&
  10000. (SessionsPageControl->ActivePage->PageIndex != Index))
  10001. {
  10002. Configuration->Usage->Inc(L"SessionTabMoves");
  10003. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10004. // but we want to actually prevent that to avoid flicker
  10005. SessionsPageControl->ActivePage->PageIndex = Index;
  10006. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10007. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10008. }
  10009. }
  10010. //---------------------------------------------------------------------------
  10011. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10012. TObject * Sender, TObject * Source, int X, int Y,
  10013. TDragState /*State*/, bool & Accept)
  10014. {
  10015. Accept = (Sender == Source);
  10016. if (Accept)
  10017. {
  10018. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10019. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10020. // do not allow dragging to the "+" tab
  10021. Accept = (Terminal != NULL);
  10022. }
  10023. }
  10024. //---------------------------------------------------------------------------
  10025. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10026. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10027. {
  10028. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10029. if (Index < 0)
  10030. {
  10031. Effect = DROPEFFECT_NONE;
  10032. }
  10033. else
  10034. {
  10035. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10036. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10037. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10038. {
  10039. Effect = DROPEFFECT_NONE;
  10040. }
  10041. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10042. {
  10043. Effect = DROPEFFECT_COPY;
  10044. }
  10045. }
  10046. }
  10047. //---------------------------------------------------------------------------
  10048. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10049. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10050. {
  10051. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10052. // do not allow dropping on local-local, disconnected and the "+" tab
  10053. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10054. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10055. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10056. {
  10057. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10058. if (!IsFileControl(DropSourceControl, osRemote))
  10059. {
  10060. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10061. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10062. // Why don't we use Terminal->CurrentDirectory directly?
  10063. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10064. // do not force queue, drag drop
  10065. false, true);
  10066. }
  10067. }
  10068. }
  10069. //---------------------------------------------------------------------------
  10070. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10071. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10072. {
  10073. // Downloads are handled in RemoteFileControlDDEnd
  10074. if (!IsFileControl(DropSourceControl, osRemote))
  10075. {
  10076. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10077. Terminal->CurrentDirectory,
  10078. // force queue, drag drop
  10079. true, true);
  10080. }
  10081. }
  10082. //---------------------------------------------------------------------------
  10083. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10084. {
  10085. FShowing = false;
  10086. // Do not save empty workspace
  10087. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10088. {
  10089. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10090. UnicodeString Name = WorkspaceName();
  10091. DoSaveWorkspace(
  10092. Name, DataList.get(),
  10093. !Configuration->DisablePasswordStoring &&
  10094. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10095. WinConfiguration->LastStoredSession = Name;
  10096. }
  10097. AppLog(L"Closing main window");
  10098. }
  10099. //---------------------------------------------------------------------------
  10100. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10101. {
  10102. TManagedTerminal * ManagedTerminal =
  10103. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10104. if (ManagedTerminal != NULL)
  10105. {
  10106. ManagedTerminal->DirectoryLoaded = Now();
  10107. }
  10108. }
  10109. //---------------------------------------------------------------------------
  10110. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10111. TListItem * /*Item*/, bool /*Selected*/)
  10112. {
  10113. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10114. switch (DirView->LastSelectMethod)
  10115. {
  10116. case smKeyboard:
  10117. Configuration->Usage->Inc(L"KeyboardSelections");
  10118. break;
  10119. case smMouse:
  10120. Configuration->Usage->Inc(L"MouseSelections");
  10121. break;
  10122. }
  10123. }
  10124. //---------------------------------------------------------------------------
  10125. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10126. {
  10127. if (Color != 0)
  10128. {
  10129. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10130. }
  10131. else
  10132. {
  10133. return FSessionTabImageIndex;
  10134. }
  10135. }
  10136. //---------------------------------------------------------------------------
  10137. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10138. {
  10139. TPngImageCollectionItem * Item =
  10140. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10141. FSessionColors->AddPng(Item->PngImage);
  10142. return FSessionColors->Count - 1;
  10143. }
  10144. //---------------------------------------------------------------------------
  10145. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10146. {
  10147. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10148. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10149. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10150. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10151. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10152. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10153. }
  10154. //---------------------------------------------------------------------------
  10155. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10156. {
  10157. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10158. }
  10159. //---------------------------------------------------------------------------
  10160. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10161. {
  10162. switch (Side)
  10163. {
  10164. case osLocal:
  10165. return FNewLocalTabTabImageIndex;
  10166. case osRemote:
  10167. case osCurrent:
  10168. return FNewRemoteTabTabImageIndex;
  10169. default:
  10170. DebugFail();
  10171. return -1;
  10172. }
  10173. }
  10174. //---------------------------------------------------------------------------
  10175. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10176. {
  10177. for (int Index = 0; Index < Control->ControlCount; Index++)
  10178. {
  10179. TControl * AControl = Control->Controls[Index];
  10180. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10181. if (WinControl != NULL)
  10182. {
  10183. CollectItemsWithTextDisplayMode(WinControl);
  10184. }
  10185. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10186. if (Toolbar != NULL)
  10187. {
  10188. // we care for top-level items only
  10189. TTBCustomItem * Items = Toolbar->Items;
  10190. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10191. {
  10192. TTBCustomItem * Item = Items->Items[ItemIndex];
  10193. if (((Item->DisplayMode == nbdmImageAndText) ||
  10194. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10195. EligibleForImageDisplayMode(Item))
  10196. {
  10197. FItemsWithTextDisplayMode.insert(Item);
  10198. }
  10199. }
  10200. }
  10201. }
  10202. }
  10203. //---------------------------------------------------------------------------
  10204. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10205. {
  10206. return true;
  10207. }
  10208. //---------------------------------------------------------------------------
  10209. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10210. {
  10211. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10212. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10213. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10214. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10215. bool Result = true;
  10216. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10217. {
  10218. TTBCustomItem * Item = *i;
  10219. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10220. if (Label != NULL)
  10221. {
  10222. // optimization
  10223. if (Label->Visible == SelectiveToolbarText)
  10224. {
  10225. Result = false;
  10226. }
  10227. else
  10228. {
  10229. Label->Visible = SelectiveToolbarText;
  10230. }
  10231. }
  10232. else
  10233. {
  10234. // optimization
  10235. if (Item->DisplayMode == DisplayMode)
  10236. {
  10237. Result = false;
  10238. }
  10239. else
  10240. {
  10241. Item->DisplayMode = DisplayMode;
  10242. }
  10243. }
  10244. ++i;
  10245. }
  10246. UpdateNewTabTab();
  10247. return Result;
  10248. }
  10249. //---------------------------------------------------------------------------
  10250. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10251. {
  10252. DebugFail();
  10253. }
  10254. //---------------------------------------------------------------------------
  10255. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10256. {
  10257. // Among other, a lock level is non zero, while directory is being loaded,
  10258. // even when it happens as a result of dirview navigation,
  10259. // i.e. when TNonVisualDataModule is NOT FBusy.
  10260. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10261. // Among other this prevents a panel auto update to occur while
  10262. // directory is changing.
  10263. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10264. }
  10265. //---------------------------------------------------------------------------
  10266. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10267. {
  10268. // While the window is disabled, we still seem to process menu shortcuts at least,
  10269. // so stop it at least here.
  10270. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10271. bool Result;
  10272. if (Allowed == aaUpdate)
  10273. {
  10274. Result = true;
  10275. }
  10276. else
  10277. {
  10278. Result = !NonVisualDataModule->Busy;
  10279. if (Result && (Allowed == aaShortCut))
  10280. {
  10281. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10282. Action->Update();
  10283. Result = Action->Enabled;
  10284. }
  10285. }
  10286. return Result;
  10287. }
  10288. //---------------------------------------------------------------------------
  10289. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10290. {
  10291. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10292. }
  10293. //---------------------------------------------------------------------------
  10294. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10295. {
  10296. // This is somewhat redundant to LockWindow() call from
  10297. // TTerminalManager::TerminalReadDirectoryProgress.
  10298. // But disabling window is known not to block keyboard shorcuts
  10299. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10300. if (Busy > 0)
  10301. {
  10302. if (NonVisualDataModule->Busy)
  10303. {
  10304. State = false;
  10305. }
  10306. else
  10307. {
  10308. NonVisualDataModule->StartBusy();
  10309. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10310. LockWindow();
  10311. }
  10312. }
  10313. else if (Busy < 0)
  10314. {
  10315. UnlockWindow();
  10316. NonVisualDataModule->EndBusy();
  10317. }
  10318. else
  10319. {
  10320. State = NonVisualDataModule->Busy;
  10321. }
  10322. }
  10323. //---------------------------------------------------------------------------
  10324. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10325. {
  10326. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10327. if (Index >= 0)
  10328. {
  10329. TPopupMenu * PopupMenu = NULL;
  10330. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10331. if (Session != NULL)
  10332. {
  10333. SessionsPageControl->ActivePageIndex = Index;
  10334. if (DebugAlwaysTrue(SessionTabSwitched()))
  10335. {
  10336. // copied from TControl.WMContextMenu
  10337. SendCancelMode(SessionsPageControl);
  10338. // explicit popup instead of using PopupMenu property
  10339. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10340. // while connecting yet not-connected session and hence
  10341. // allowing an access to commands over not-completely connected session
  10342. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10343. }
  10344. }
  10345. else
  10346. {
  10347. if (SupportsLocalBrowser())
  10348. {
  10349. PopupMenu = NonVisualDataModule->NewTabPopup;
  10350. }
  10351. }
  10352. if (PopupMenu != NULL)
  10353. {
  10354. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10355. PopupMenu->PopupComponent = SessionsPageControl;
  10356. PopupMenu->Popup(Point.x, Point.y);
  10357. }
  10358. }
  10359. Handled = true;
  10360. }
  10361. //---------------------------------------------------------------------------
  10362. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10363. {
  10364. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10365. }
  10366. //---------------------------------------------------------------------------
  10367. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10368. {
  10369. Configuration->Usage->Inc(L"PasswordChanges");
  10370. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10371. ChangePasswordData->DisableAuthentationsExceptPassword();
  10372. ChangePasswordData->ChangePassword = true;
  10373. std::unique_ptr<TTerminal> ChangePasswordSession(
  10374. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10375. ChangePasswordSession->AutoReadDirectory = false;
  10376. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10377. {
  10378. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10379. }
  10380. else
  10381. {
  10382. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10383. }
  10384. }
  10385. //---------------------------------------------------------------------------
  10386. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10387. {
  10388. // No nice way to assert SSH2
  10389. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10390. }
  10391. //---------------------------------------------------------------------------
  10392. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10393. {
  10394. TOperationVisualizer OperationVisualizer;
  10395. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10396. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10397. }
  10398. //---------------------------------------------------------------------------
  10399. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10400. {
  10401. TForm::ChangeScale(M, D);
  10402. int APixelsPerInch = GetControlPixelsPerInch(this);
  10403. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  10404. try
  10405. {
  10406. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  10407. }
  10408. __finally
  10409. {
  10410. GUIConfiguration->ChangeResourceModule(ResourceModule);
  10411. }
  10412. }
  10413. //---------------------------------------------------------------------------
  10414. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10415. {
  10416. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10417. }
  10418. //---------------------------------------------------------------------
  10419. class TPublicControl : public TControl
  10420. {
  10421. friend class TCustomScpExplorerForm;
  10422. };
  10423. //---------------------------------------------------------------------------
  10424. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10425. {
  10426. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10427. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10428. }
  10429. //---------------------------------------------------------------------------
  10430. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10431. {
  10432. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10433. OpenBookmark(Side, Bookmark);
  10434. }
  10435. //---------------------------------------------------------------------------
  10436. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10437. {
  10438. DoBookmarkClick(osLocal, Sender);
  10439. }
  10440. //---------------------------------------------------------------------------
  10441. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10442. {
  10443. DoBookmarkClick(osRemote, Sender);
  10444. }
  10445. //---------------------------------------------------------------------------
  10446. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10447. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10448. {
  10449. if (BookmarkList != NULL)
  10450. {
  10451. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10452. if (IsLocalBrowserMode())
  10453. {
  10454. Side = osLocal;
  10455. }
  10456. if (!WinConfiguration->UseLocationProfiles)
  10457. {
  10458. std::unique_ptr<TStringList> Directories(new TStringList());
  10459. Directories->CaseSensitive = (Side == osRemote);
  10460. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10461. {
  10462. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10463. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10464. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10465. {
  10466. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10467. Item->Caption = EscapeHotkey(Directory);
  10468. Item->ShortCut = Bookmark->ShortCut;
  10469. Item->OnClick = OnBookmarkClick;
  10470. Item->Tag = reinterpret_cast<int>(Bookmark);
  10471. Directories->Add(Directory);
  10472. Menu->Add(Item.release());
  10473. }
  10474. }
  10475. }
  10476. else
  10477. {
  10478. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10479. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10480. {
  10481. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10482. if (!Bookmark->Node.IsEmpty())
  10483. {
  10484. Folders->Add(Bookmark->Node);
  10485. }
  10486. }
  10487. for (int Index = 0; Index < Folders->Count; Index++)
  10488. {
  10489. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10490. Item->Caption = Folders->Strings[Index];
  10491. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10492. Folders->Objects[Index] = Item.get();
  10493. Menu->Add(Item.release());
  10494. }
  10495. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10496. {
  10497. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10498. TTBCustomItem * Parent;
  10499. if (!Bookmark->Node.IsEmpty())
  10500. {
  10501. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10502. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10503. }
  10504. else
  10505. {
  10506. Parent = Menu;
  10507. }
  10508. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10509. Item->Caption = Bookmark->Name;
  10510. Item->ShortCut = Bookmark->ShortCut;
  10511. Item->OnClick = OnBookmarkClick;
  10512. Item->Tag = reinterpret_cast<int>(Bookmark);
  10513. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10514. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10515. {
  10516. // No hint for location profiles that are actually mere "bookmarks"
  10517. }
  10518. else
  10519. {
  10520. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10521. UnicodeString LongHint;
  10522. if (!Bookmark->Local.IsEmpty())
  10523. {
  10524. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10525. }
  10526. if (!Bookmark->Remote.IsEmpty())
  10527. {
  10528. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10529. }
  10530. AddToList(Hint, LongHint, L"|");
  10531. Item->Hint = Hint;
  10532. }
  10533. Parent->Add(Item.release());
  10534. }
  10535. }
  10536. AddMenuSeparator(Menu);
  10537. }
  10538. }
  10539. //---------------------------------------------------------------------------
  10540. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10541. {
  10542. Menu->Clear();
  10543. std::unique_ptr<TTBCustomItem> Item;
  10544. Item.reset(new TTBXItem(Owner));
  10545. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10546. Item->Options = Item->Options << tboDefault;
  10547. Menu->Add(Item.release());
  10548. AddMenuSeparator(Menu);
  10549. if (Terminal != NULL)
  10550. {
  10551. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10552. }
  10553. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10554. Item.reset(new TTBXItem(Owner));
  10555. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10556. Menu->Add(Item.release());
  10557. }
  10558. //---------------------------------------------------------------------------
  10559. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10560. {
  10561. bool Result = true;
  10562. bool Remote = !IsSideLocalBrowser(Side);
  10563. try
  10564. {
  10565. UnicodeString APath = Path;
  10566. if (Remote)
  10567. {
  10568. Terminal->ExceptionOnFail = true;
  10569. }
  10570. else
  10571. {
  10572. APath = ExpandEnvironmentVariables(Path);
  10573. }
  10574. try
  10575. {
  10576. DirView(Side)->Path = APath;
  10577. }
  10578. __finally
  10579. {
  10580. if (Remote)
  10581. {
  10582. Terminal->ExceptionOnFail = false;
  10583. }
  10584. }
  10585. }
  10586. catch (Exception & E)
  10587. {
  10588. if (!Remote || Terminal->Active)
  10589. {
  10590. ShowExtendedExceptionEx(Terminal, &E);
  10591. Result = false;
  10592. }
  10593. else
  10594. {
  10595. throw;
  10596. }
  10597. }
  10598. return Result;
  10599. }
  10600. //---------------------------------------------------------------------------
  10601. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10602. {
  10603. // Make sure there some feedback even when loading tiny local folders
  10604. TInstantOperationVisualizer Visualizer;
  10605. DirView(Side)->ReloadDirectory();
  10606. }
  10607. //---------------------------------------------------------------------------
  10608. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10609. {
  10610. if (Index == SessionsPageControl->TabIndex)
  10611. {
  10612. CloseTab();
  10613. }
  10614. else
  10615. {
  10616. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10617. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10618. TTerminalManager * Manager = TTerminalManager::Instance();
  10619. if (!Terminal->Active)
  10620. {
  10621. Manager->FreeTerminal(Terminal);
  10622. }
  10623. else
  10624. {
  10625. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10626. if (CanCloseQueue(Queue))
  10627. {
  10628. Manager->FreeTerminal(Terminal);
  10629. }
  10630. }
  10631. }
  10632. }
  10633. //---------------------------------------------------------------------------
  10634. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10635. {
  10636. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10637. if (Session == NULL)
  10638. {
  10639. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10640. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10641. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10642. //P = SessionsPageControl->ClientToScreen(P);
  10643. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10644. }
  10645. else
  10646. {
  10647. CloseSessionTab(Index);
  10648. }
  10649. }
  10650. //---------------------------------------------------------------------------
  10651. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10652. {
  10653. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10654. {
  10655. TInstantOperationVisualizer Visualizer;
  10656. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10657. // before we create a new data object
  10658. ClipboardClear();
  10659. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10660. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10661. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10662. // Intermediate variable to WORKAROUND a crash in compiler
  10663. TObjectList * ClipboardFakeMonitors =
  10664. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10665. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10666. if (FClipboardDragDropFilesEx.get() == NULL)
  10667. {
  10668. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10669. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10670. }
  10671. FClipboardDragDropFilesEx->FileList->Clear();
  10672. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10673. FClipboardDragDropFilesEx->CopyToClipboard();
  10674. FClipboardTerminal = Terminal;
  10675. // Need full paths, as cwd can be different once files are pasted
  10676. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10677. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10678. {
  10679. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10680. }
  10681. }
  10682. }
  10683. //---------------------------------------------------------------------------
  10684. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10685. {
  10686. if (OpenClipboard(0))
  10687. {
  10688. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10689. CloseClipboard();
  10690. }
  10691. }
  10692. //---------------------------------------------------------------------------
  10693. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10694. {
  10695. return !FClipboardFakeDirectory.IsEmpty();
  10696. }
  10697. //---------------------------------------------------------------------------
  10698. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10699. {
  10700. RemoveDir(ApiPath(FClipboardFakeDirectory));
  10701. FClipboardFakeDirectory = UnicodeString();
  10702. FClipboardTerminal = NULL;
  10703. if (FDownloadingFromClipboard)
  10704. {
  10705. // We are called by the monitor, so attempt to release it would deadlock
  10706. FClipboardFakeMonitorsPendingReset = true;
  10707. }
  10708. else
  10709. {
  10710. FClipboardFakeMonitors.reset(NULL);
  10711. }
  10712. }
  10713. //---------------------------------------------------------------------------
  10714. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10715. {
  10716. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10717. {
  10718. ClipboardStop();
  10719. }
  10720. }
  10721. //---------------------------------------------------------------------------
  10722. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10723. {
  10724. TTerminalManager * Manager = TTerminalManager::Instance();
  10725. Manager->ActiveSession = FClipboardTerminal;
  10726. TTransferOperationParam Params;
  10727. Params.TargetDirectory = TargetDirectory;
  10728. Params.DragDrop = DragDrop;
  10729. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10730. }
  10731. //---------------------------------------------------------------------------
  10732. void TCustomScpExplorerForm::PasteFiles()
  10733. {
  10734. // Guard against possible race conditions
  10735. if (!FClipboardPasteTarget.IsEmpty())
  10736. {
  10737. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10738. UnicodeString Target = FClipboardPasteTarget;
  10739. FClipboardPasteTarget = EmptyStr;
  10740. // Can fail as it can be e.g. locked by AV, so we retry that later
  10741. bool Removed = RemoveDir(ApiPath(Target));
  10742. try
  10743. {
  10744. if (!NonVisualDataModule->Busy)
  10745. {
  10746. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10747. FClipboardFakeMonitorsPendingReset = false;
  10748. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10749. TAutoFlag Flag(FDownloadingFromClipboard);
  10750. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10751. }
  10752. }
  10753. __finally
  10754. {
  10755. if (!Removed)
  10756. {
  10757. RemoveDir(ApiPath(Target));
  10758. }
  10759. }
  10760. }
  10761. }
  10762. //---------------------------------------------------------------------------
  10763. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10764. {
  10765. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10766. // (as it pumps a Windows message queue while being shutted down)
  10767. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10768. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10769. {
  10770. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10771. FClipboardPasteTarget = FileName;
  10772. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10773. // Postponing removing (or actually whole pasting operation) seems to help.
  10774. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10775. }
  10776. }
  10777. //---------------------------------------------------------------------------
  10778. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10779. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10780. {
  10781. TFileMasks::TParams MaskParams;
  10782. MaskParams.Size = Size;
  10783. MaskParams.Modification = Modification;
  10784. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10785. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10786. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10787. if (!Local && Directory)
  10788. {
  10789. FileName = UnixExcludeTrailingBackslash(FileName);
  10790. }
  10791. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10792. {
  10793. bool ImplicitMatch;
  10794. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10795. !ImplicitMatch)
  10796. {
  10797. Color = Iter->Color;
  10798. break;
  10799. }
  10800. }
  10801. }
  10802. //---------------------------------------------------------------------------
  10803. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10804. {
  10805. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10806. if (!DirView->IsEditing())
  10807. {
  10808. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10809. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10810. // while searching
  10811. if (Key == VK_BACK)
  10812. {
  10813. if (!FIncrementalSearch.IsEmpty())
  10814. {
  10815. if (FIncrementalSearch.Length() == 1)
  10816. {
  10817. ResetIncrementalSearch();
  10818. }
  10819. else
  10820. {
  10821. UnicodeString NewText = FIncrementalSearch.SubString(1, FIncrementalSearch.Length() - 1);
  10822. IncrementalSearch(NewText, false, false);
  10823. }
  10824. Key = 0;
  10825. }
  10826. }
  10827. }
  10828. }
  10829. //---------------------------------------------------------------------------
  10830. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10831. {
  10832. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10833. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10834. {
  10835. // Filter control sequences.
  10836. // When not searching yet, prefer use of the space for toggling file selection
  10837. // (so we cannot incrementally search for a string starting with a space).
  10838. if ((Key > VK_SPACE) ||
  10839. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearch.IsEmpty()))
  10840. {
  10841. IncrementalSearch(FIncrementalSearch + Key, false, false);
  10842. Key = 0;
  10843. }
  10844. }
  10845. }
  10846. //---------------------------------------------------------------------------
  10847. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10848. {
  10849. if (!FIncrementalSearch.IsEmpty())
  10850. {
  10851. FIncrementalSearch = L"";
  10852. DirView(osCurrent)->UpdateStatusBar();
  10853. }
  10854. }
  10855. //---------------------------------------------------------------------------
  10856. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10857. {
  10858. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10859. if (Item == NULL)
  10860. {
  10861. MessageBeep(MB_ICONHAND);
  10862. }
  10863. else
  10864. {
  10865. TCustomDirView * ADirView = DirView(osCurrent);
  10866. {
  10867. TAutoNestingCounter Guard(FIncrementalSearching);
  10868. ADirView->FocusItem(Item);
  10869. if (ADirView->NortonLike == nlOff)
  10870. {
  10871. if ((ADirView->Selected != Item) ||
  10872. (ADirView->SelCount > 1))
  10873. {
  10874. ADirView->ClearSelection();
  10875. ADirView->Selected = Item;
  10876. }
  10877. }
  10878. }
  10879. FIncrementalSearch = Text;
  10880. Item->MakeVisible(false);
  10881. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10882. FIncrementalSearchHaveNext = (NextItem != NULL) && (NextItem != Item);
  10883. ADirView->UpdateStatusBar();
  10884. }
  10885. }
  10886. //---------------------------------------------------------------------------
  10887. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  10888. {
  10889. int Index = Item->Index;
  10890. if (!Reverse)
  10891. {
  10892. Index++;
  10893. if (Index >= Item->Owner->Count)
  10894. {
  10895. Index = 0;
  10896. }
  10897. }
  10898. else
  10899. {
  10900. Index--;
  10901. if (Index < 0)
  10902. {
  10903. Index = Item->Owner->Count - 1;
  10904. }
  10905. }
  10906. return Item->Owner->Item[Index];
  10907. }
  10908. //---------------------------------------------------------------------------
  10909. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10910. {
  10911. TCustomDirView * ADirView = DirView(osCurrent);
  10912. if (ADirView->Items->Count == 0)
  10913. {
  10914. return NULL;
  10915. }
  10916. else
  10917. {
  10918. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  10919. TListItem * Item = CurrentItem;
  10920. if (SkipCurrent)
  10921. {
  10922. Item = DebugNotNull(GetNextFile(Item, Reverse));
  10923. }
  10924. while (true)
  10925. {
  10926. bool Matches = false;
  10927. switch (WinConfiguration->PanelSearch)
  10928. {
  10929. case isNameStartOnly:
  10930. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  10931. break;
  10932. case isName:
  10933. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  10934. break;
  10935. case isAll:
  10936. int ColCount = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Count : 1;
  10937. int Index = 0;
  10938. while ((Index < ColCount) && !Matches)
  10939. {
  10940. bool Visible = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Visible[Index] : true;
  10941. if (Visible)
  10942. {
  10943. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  10944. }
  10945. Index++;
  10946. }
  10947. break;
  10948. }
  10949. if (Matches)
  10950. {
  10951. return Item;
  10952. }
  10953. Item = GetNextFile(Item, Reverse);
  10954. if (Item == CurrentItem)
  10955. {
  10956. return NULL;
  10957. }
  10958. }
  10959. }
  10960. }
  10961. //---------------------------------------------------------------------------
  10962. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  10963. {
  10964. ResetIncrementalSearch();
  10965. }
  10966. //---------------------------------------------------------------------------
  10967. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  10968. {
  10969. if (Message.CharCode == VK_TAB)
  10970. {
  10971. if (!FIncrementalSearch.IsEmpty())
  10972. {
  10973. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  10974. bool Reverse = Shift.Contains(ssShift);
  10975. IncrementalSearch(FIncrementalSearch, true, Reverse);
  10976. Message.Result = 1;
  10977. return;
  10978. }
  10979. }
  10980. else if (Message.CharCode == VK_ESCAPE)
  10981. {
  10982. if (!FIncrementalSearch.IsEmpty())
  10983. {
  10984. ResetIncrementalSearch();
  10985. Message.Result = 1;
  10986. return;
  10987. }
  10988. }
  10989. TForm::Dispatch(&Message);
  10990. }
  10991. //---------------------------------------------------------------------------
  10992. void __fastcall TCustomScpExplorerForm::Deactivate()
  10993. {
  10994. TForm::Deactivate();
  10995. // E.g. when switching to an internal editor window
  10996. ResetIncrementalSearch();
  10997. }
  10998. //---------------------------------------------------------------------------
  10999. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11000. {
  11001. // When switching to another application
  11002. ResetIncrementalSearch();
  11003. }
  11004. //---------------------------------------------------------------------------
  11005. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11006. {
  11007. ResetIncrementalSearch();
  11008. }
  11009. //---------------------------------------------------------------------------
  11010. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11011. {
  11012. if (FIncrementalSearching <= 0)
  11013. {
  11014. ResetIncrementalSearch();
  11015. }
  11016. }
  11017. //---------------------------------------------------------------------------
  11018. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11019. {
  11020. CountClicksForWindowPrint(this);
  11021. }
  11022. //---------------------------------------------------------------------------
  11023. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11024. {
  11025. CenterReconnectToolbar();
  11026. }
  11027. //---------------------------------------------------------------------------
  11028. void TCustomScpExplorerForm::DoBrowseFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11029. {
  11030. if (!FileName.IsEmpty())
  11031. {
  11032. DirView->RestoreFocus(FileName);
  11033. if (DirView->ItemFocused != NULL)
  11034. {
  11035. DirView->ItemFocused->Selected = true;
  11036. }
  11037. }
  11038. }
  11039. //---------------------------------------------------------------------------
  11040. void __fastcall TCustomScpExplorerForm::BrowseFile(const UnicodeString & FileName)
  11041. {
  11042. DoBrowseFile(RemoteDirView, FileName);
  11043. }
  11044. //---------------------------------------------------------------------------
  11045. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11046. {
  11047. if (!FQueueStatusUpdating)
  11048. {
  11049. bool Refresh;
  11050. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11051. {
  11052. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11053. }
  11054. else
  11055. {
  11056. if (FQueueFileList->GetCount() > 0)
  11057. {
  11058. FQueueFileList->Clear();
  11059. Refresh = true;
  11060. }
  11061. }
  11062. int Count = FQueueFileList->GetCount();
  11063. if (QueueFileList->Items->Count != Count)
  11064. {
  11065. DebugAssert(Refresh);
  11066. QueueFileList->Items->Count = Count;
  11067. }
  11068. if (Refresh)
  11069. {
  11070. QueueFileList->Invalidate();
  11071. }
  11072. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11073. }
  11074. }
  11075. //---------------------------------------------------------------------------
  11076. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11077. {
  11078. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11079. }
  11080. //---------------------------------------------------------------------------
  11081. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11082. {
  11083. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11084. // See TSynchronizeChecklistDialog::UpdateTimer
  11085. if (QueueFileList->Items->Count > 0)
  11086. {
  11087. QueueFileList->Items->Item[0]->MakeVisible(false);
  11088. }
  11089. UpdateQueueFileList();
  11090. }
  11091. //---------------------------------------------------------------------------
  11092. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11093. {
  11094. Active = QueueView3->Focused() || QueueFileList->Focused();
  11095. }
  11096. //---------------------------------------------------------------------------
  11097. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11098. {
  11099. QueueLabelUpdateStatus();
  11100. }
  11101. //---------------------------------------------------------------------------
  11102. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11103. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11104. {
  11105. int State = FQueueFileList->GetState(Item->Index);
  11106. if (State == qfsProcessed)
  11107. {
  11108. Sender->Canvas->Font->Color = clGrayText;
  11109. }
  11110. }
  11111. //---------------------------------------------------------------------------
  11112. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11113. {
  11114. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11115. QueueFileList->Column[0]->Width =
  11116. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11117. }
  11118. //---------------------------------------------------------------------------
  11119. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11120. {
  11121. QueueFileListColumnAutoSize();
  11122. }
  11123. //---------------------------------------------------------------------------
  11124. void __fastcall TCustomScpExplorerForm::CloseApp()
  11125. {
  11126. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11127. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11128. // So we clear the flag here.
  11129. DebugAssert(NonVisualDataModule->Busy);
  11130. NonVisualDataModule->EndBusy();
  11131. try
  11132. {
  11133. Close();
  11134. }
  11135. __finally
  11136. {
  11137. NonVisualDataModule->StartBusy();
  11138. }
  11139. }
  11140. //---------------------------------------------------------------------------
  11141. bool __fastcall TCustomScpExplorerForm::IsActiveTerminal(TTerminal * Terminal)
  11142. {
  11143. return (Terminal != NULL) && Terminal->Active;
  11144. }
  11145. //---------------------------------------------------------------------------
  11146. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  11147. {
  11148. return (ManagedSession != NULL);
  11149. }
  11150. //---------------------------------------------------------------------------
  11151. bool __fastcall TCustomScpExplorerForm::HasActiveTerminal()
  11152. {
  11153. return IsActiveTerminal(Terminal);
  11154. }
  11155. //---------------------------------------------------------------------------
  11156. void TCustomScpExplorerForm::LocalLocalCopy(
  11157. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11158. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11159. {
  11160. DebugFail();
  11161. }
  11162. //---------------------------------------------------------------------------
  11163. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11164. {
  11165. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11166. }
  11167. //---------------------------------------------------------------------------
  11168. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11169. {
  11170. // 1) Changing tab list triggers the OnResize.
  11171. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11172. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11173. {
  11174. // UpdateTabsCaptionTruncation should be enough
  11175. SessionListChanged(true);
  11176. }
  11177. }
  11178. //---------------------------------------------------------------------------
  11179. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11180. {
  11181. if (ASession == ManagedSession)
  11182. {
  11183. UpdateSession(ASession);
  11184. }
  11185. TSessionData * Data = ASession->StateData;
  11186. UnicodeString Result;
  11187. if (Side == osLocal)
  11188. {
  11189. Result = Data->LocalDirectory;
  11190. }
  11191. else if (DebugAlwaysTrue(Side == osOther))
  11192. {
  11193. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11194. }
  11195. return Result;
  11196. }
  11197. //---------------------------------------------------------------------------
  11198. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11199. {
  11200. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11201. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11202. if (Title == Result)
  11203. {
  11204. Result = EmptyStr;
  11205. }
  11206. else
  11207. {
  11208. Result += L"\n";
  11209. }
  11210. return Result;
  11211. }
  11212. //---------------------------------------------------------------------------
  11213. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11214. {
  11215. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11216. if (!ASession->Active)
  11217. {
  11218. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11219. }
  11220. else
  11221. {
  11222. Result += GetSessionPath(ASession, osRemote);
  11223. }
  11224. return Result;
  11225. }
  11226. //---------------------------------------------------------------------------
  11227. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11228. {
  11229. return LoadStr(NEW_REMOTE_TAB_HINT);
  11230. }
  11231. //---------------------------------------------------------------------------
  11232. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11233. {
  11234. if (Index >= 0)
  11235. {
  11236. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11237. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11238. if (TabSession == NULL)
  11239. {
  11240. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11241. if (NewTabTabCaption != TabSheet->Caption)
  11242. {
  11243. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11244. }
  11245. }
  11246. else
  11247. {
  11248. TTerminalManager * Manager = TTerminalManager::Instance();
  11249. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11250. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11251. }
  11252. }
  11253. }
  11254. //---------------------------------------------------------------------------
  11255. typedef std::vector<TListItem *> TListItemsVector;
  11256. struct TCalculateSizeOperation
  11257. {
  11258. TCalculateSizeStats Stats;
  11259. TListItemsVector ListItems;
  11260. size_t Index;
  11261. };
  11262. //---------------------------------------------------------------------------
  11263. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11264. {
  11265. TCalculateSizeOperation CalculateSizeOperation;
  11266. Side = GetSide(Side);
  11267. TCustomDirView * ADirView = DirView(Side);
  11268. bool LocalSide = IsSideLocalBrowser(Side);
  11269. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11270. std::unique_ptr<TStrings> FileList(new TStringList());
  11271. for (int Index = 0; Index < AllFileList->Count; Index++)
  11272. {
  11273. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11274. if (ADirView->ItemIsDirectory(Item))
  11275. {
  11276. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11277. CalculateSizeOperation.ListItems.push_back(Item);
  11278. }
  11279. }
  11280. CalculateSizeOperation.Index = 0;
  11281. __int64 Size = 0;
  11282. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation);
  11283. FCalculateSizeOperation = &CalculateSizeOperation;
  11284. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11285. FOnFileOperationFinished = DirectorySizeCalculated;
  11286. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation);
  11287. FPrimaryOperation = foCalculateSize;
  11288. TCalculatedSizes CalculatedSizes;
  11289. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11290. if (LocalSide)
  11291. {
  11292. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide);
  11293. FProgressSide = Side;
  11294. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11295. }
  11296. else
  11297. {
  11298. TCalculateSizeParams Params;
  11299. Params.Stats = &CalculateSizeOperation.Stats;
  11300. Params.UseCache = true;
  11301. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11302. }
  11303. }
  11304. //---------------------------------------------------------------------------
  11305. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool Success)
  11306. {
  11307. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11308. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11309. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11310. // optimization
  11311. bool GotExpectedItem =
  11312. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11313. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11314. int Index = -1;
  11315. if (DebugAlwaysTrue(GotExpectedItem))
  11316. {
  11317. Index = FCalculateSizeOperation->Index;
  11318. FCalculateSizeOperation->Index++;
  11319. }
  11320. else
  11321. {
  11322. TListItemsVector::iterator I =
  11323. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11324. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11325. {
  11326. Index = I - FCalculateSizeOperation->ListItems.begin();
  11327. }
  11328. }
  11329. if (DebugAlwaysTrue(Index >= 0) && Success)
  11330. {
  11331. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11332. ADirView->SetItemCalculatedSize(Item, Size);
  11333. }
  11334. }
  11335. //---------------------------------------------------------------------------
  11336. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11337. {
  11338. Accept = false;
  11339. }
  11340. //---------------------------------------------------------------------------
  11341. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11342. {
  11343. // Send Ctrl+Gray+ to the list view
  11344. TKeyboardState KeyState;
  11345. GetKeyboardState(KeyState);
  11346. TKeyboardState NewKeyState;
  11347. memset(NewKeyState, 0, sizeof(NewKeyState));
  11348. NewKeyState[VK_CONTROL] = 0x81;
  11349. SetKeyboardState(NewKeyState);
  11350. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11351. SetKeyboardState(KeyState);
  11352. }
  11353. //---------------------------------------------------------------------------
  11354. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11355. {
  11356. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11357. }