CustomScpExplorer.cpp 335 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255
  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 <Bookmarks.h>
  8. #include <Interface.h>
  9. #include <Exceptions.h>
  10. #include <CoreMain.h>
  11. #include <FileSystems.h>
  12. #include <TextsCore.h>
  13. #include <TextsWin.h>
  14. #include <HelpWin.h>
  15. #include <VCLCommon.h>
  16. #include <Progress.h>
  17. #include <SynchronizeProgress.h>
  18. #include <DragExt.h>
  19. #include <WinApi.h>
  20. #include "GUITools.h"
  21. #include "NonVisual.h"
  22. #include "Glyphs.h"
  23. #include "Tools.h"
  24. #include "WinConfiguration.h"
  25. #include "TerminalManager.h"
  26. #include "EditorManager.h"
  27. #include "ProgParams.h"
  28. #include "Setup.h"
  29. #include <Consts.hpp>
  30. #include <DateUtils.hpp>
  31. #include <TB2Common.hpp>
  32. #include <DirectoryMonitor.hpp>
  33. //---------------------------------------------------------------------------
  34. #pragma package(smart_init)
  35. #pragma link "CustomDirView"
  36. #pragma link "CustomUnixDirView"
  37. #pragma link "IEListView"
  38. #pragma link "NortonLikeListView"
  39. #pragma link "UnixDirView"
  40. #pragma link "CustomDriveView"
  41. #pragma link "UnixDriveView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "TB2Dock"
  44. #pragma link "TBXStatusBars"
  45. #pragma link "TB2Item"
  46. #pragma link "TB2Toolbar"
  47. #pragma link "ThemePageControl"
  48. #pragma link "PathLabel"
  49. #ifndef NO_RESOURCES
  50. #pragma resource "*.dfm"
  51. #endif
  52. //---------------------------------------------------------------------------
  53. #define SAVE_SELECTION(DIRVIEW) \
  54. UnicodeString FocusFile = L""; \
  55. UnicodeString LastFocusedFile = L""; \
  56. if (DIRVIEW->ItemFocused) LastFocusedFile = DIRVIEW->ItemFocused->Caption; \
  57. { TListItem * ClosestUnselected = DIRVIEW->ClosestUnselected(DIRVIEW->ItemFocused); \
  58. if (ClosestUnselected) FocusFile = ClosestUnselected->Caption; }
  59. #define RESTORE_SELECTION(DIRVIEW) \
  60. if (!LastFocusedFile.IsEmpty() && \
  61. (!DIRVIEW->ItemFocused || (DIRVIEW->ItemFocused->Caption != LastFocusedFile))) \
  62. { \
  63. TListItem *ItemToSelect = DIRVIEW->FindFileItem(FocusFile); \
  64. if (ItemToSelect) \
  65. { \
  66. DIRVIEW->ItemFocused = ItemToSelect; \
  67. DIRVIEW->ItemFocused->MakeVisible(False); \
  68. } \
  69. }
  70. //---------------------------------------------------------------------------
  71. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  72. static const int SessionPanelCount = 4;
  73. //---------------------------------------------------------------------------
  74. class TMutexGuard
  75. {
  76. public:
  77. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  78. int Timeout = 5000)
  79. {
  80. FMutex = NULL;
  81. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  82. if (WaitResult == WAIT_TIMEOUT)
  83. {
  84. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  85. }
  86. else
  87. {
  88. FMutex = AMutex;
  89. }
  90. }
  91. ~TMutexGuard()
  92. {
  93. if (FMutex != NULL)
  94. {
  95. ReleaseMutex(FMutex);
  96. }
  97. }
  98. private:
  99. HANDLE FMutex;
  100. };
  101. //---------------------------------------------------------------------------
  102. class TWindowLock
  103. {
  104. public:
  105. TWindowLock(TCustomScpExplorerForm * Form) :
  106. FForm(Form)
  107. {
  108. FForm->LockWindow();
  109. }
  110. ~TWindowLock()
  111. {
  112. FForm->UnlockWindow();
  113. }
  114. private:
  115. TCustomScpExplorerForm * FForm;
  116. };
  117. //---------------------------------------------------------------------------
  118. class TAutoBatch
  119. {
  120. public:
  121. TAutoBatch(TCustomScpExplorerForm * Form) :
  122. FForm(Form)
  123. {
  124. FForm->BatchStart(FBatchStorage);
  125. }
  126. ~TAutoBatch()
  127. {
  128. FForm->BatchEnd(FBatchStorage);
  129. }
  130. private:
  131. TCustomScpExplorerForm * FForm;
  132. void * FBatchStorage;
  133. };
  134. //---------------------------------------------------------------------------
  135. struct TTransferOperationParam
  136. {
  137. TTransferOperationParam();
  138. UnicodeString TargetDirectory;
  139. bool Temp;
  140. bool DragDrop;
  141. int Options;
  142. TAutoSwitch Queue;
  143. };
  144. //---------------------------------------------------------------------------
  145. TTransferOperationParam::TTransferOperationParam()
  146. {
  147. Temp = false;
  148. DragDrop = false;
  149. Options = 0;
  150. Queue = asAuto;
  151. }
  152. //---------------------------------------------------------------------------
  153. class TTransferPresetNoteData : public TObject
  154. {
  155. public:
  156. UnicodeString Message;
  157. };
  158. //---------------------------------------------------------------------------
  159. class TTerminalNoteData : public TObject
  160. {
  161. public:
  162. TTerminal * Terminal;
  163. };
  164. //---------------------------------------------------------------------------
  165. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  166. FFormRestored(false),
  167. TForm(Owner)
  168. {
  169. FCurrentSide = osRemote;
  170. FEverShown = false;
  171. FDocks = new TList();
  172. RestoreParams();
  173. ConfigurationChanged();
  174. RemoteDirView->Invalidate();
  175. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  176. NonVisualDataModule->ScpExplorer = this;
  177. FAutoOperation = false;
  178. FOnFileOperationFinished = NULL;
  179. FForceExecution = false;
  180. FIgnoreNextDialogChar = 0;
  181. FErrorList = NULL;
  182. FSynchronizeProgressForm = NULL;
  183. FProgressForm = NULL;
  184. FRefreshLocalDirectory = false;
  185. FRefreshRemoteDirectory = false;
  186. FDDExtMapFile = NULL;
  187. // CreateMutexW keeps failing with ERROR_NOACCESS
  188. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  189. DebugAssert(FDDExtMutex != NULL);
  190. FDDTargetControl = NULL;
  191. FDelayedDeletionTimer = NULL;
  192. FDelayedDeletionList = new TStringList();
  193. FDDFileList = NULL;
  194. FPendingTempSpaceWarn = false;
  195. FCapturedLog = NULL;
  196. FDragDropOperation = false;
  197. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  198. FAllowTransferPresetAutoSelect = true;
  199. FCopyParamDefault = L"";
  200. FSynchronizeController = NULL;
  201. FPendingQueueActionItem = NULL;
  202. FLockLevel = 0;
  203. FLockSuspendLevel = 0;
  204. FDisabledOnLockSuspend = false;
  205. FAlternativeDelete = false;
  206. FTrayIcon = new ::TTrayIcon(0);
  207. FTrayIcon->OnClick = TrayIconClick;
  208. FMaxQueueLength = 0;
  209. FLastContextPopupScreenPoint = TPoint(-1, -1);
  210. FTransferResumeList = NULL;
  211. FMoveToQueue = false;
  212. FStandaloneEditing = false;
  213. FOnFeedSynchronizeError = NULL;
  214. FNeedSession = false;
  215. FDoNotIdleCurrentTerminal = 0;
  216. FEditorManager = new TEditorManager();
  217. FEditorManager->OnFileChange = ExecutedFileChanged;
  218. FEditorManager->OnFileReload = ExecutedFileReload;
  219. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  220. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  221. FLocalEditors = new TList();
  222. FQueueStatus = NULL;
  223. FQueueStatusSection = new TCriticalSection();
  224. FQueueStatusInvalidated = false;
  225. FQueueItemInvalidated = false;
  226. FQueueActedItem = NULL;
  227. FQueueController = new TQueueController(QueueView3);
  228. FUserActionTimer = new TTimer(this);
  229. FUserActionTimer->Enabled = false;
  230. FUserActionTimer->Interval = 10;
  231. FUserActionTimer->OnTimer = UserActionTimer;
  232. FNotes = new TStringList();
  233. FNoteTimer = new TTimer(this);
  234. FNoteTimer->Enabled = false;
  235. FNoteTimer->OnTimer = NoteTimer;
  236. FOnNoteClick = NULL;
  237. FOle32Library = LoadLibrary(L"Ole32.dll");
  238. FDragMoveCursor = FOle32Library != NULL ?
  239. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  240. UseSystemSettings(this);
  241. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  242. static_cast<TObject*>(GetComponent(fcTransferList)));
  243. DebugAssert(TransferList != NULL);
  244. FTransferListHoverIndex = -1;
  245. TransferList->OnChange = TransferListChange;
  246. TransferList->OnDrawItem = TransferListDrawItem;
  247. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))));
  248. SetSubmenu(NonVisualDataModule->ColorMenuItem);
  249. UseDesktopFont(SessionsPageControl);
  250. UpdateSessionsPageControlHeight();
  251. UseDesktopFont(RemoteDirView);
  252. UseDesktopFont(RemoteDriveView);
  253. UseDesktopFont(QueueView3);
  254. UseDesktopFont(QueueLabel);
  255. UseDesktopFont(RemoteStatusBar);
  256. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  257. QueueSplitter->ShowHint = true;
  258. RemotePanelSplitter->ShowHint = true;
  259. UpdateImages();
  260. FCustomCommandMenu = CreateTBXPopupMenu(this);
  261. FCustomCommandLocalFileList = NULL;
  262. FCustomCommandRemoteFileList = NULL;
  263. FSessionColors = new TPngImageList(this);
  264. FSessionColors->ColorDepth = cd32Bit;
  265. AddFixedSessionImages();
  266. SessionsPageControl->Images = FSessionColors;
  267. QueueLabel->FocusControl = QueueView3;
  268. UpdateQueueLabel();
  269. FRemoteDirViewWasFocused = true;
  270. CreateHiddenWindow();
  271. StartUpdates();
  272. }
  273. //---------------------------------------------------------------------------
  274. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  275. {
  276. // this has to be one of the very first things to do
  277. StopUpdateThread();
  278. delete FCustomCommandLocalFileList;
  279. delete FCustomCommandRemoteFileList;
  280. delete FCustomCommandMenu;
  281. delete FTrayIcon;
  282. FTrayIcon = NULL;
  283. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  284. delete FEditorManager;
  285. ForceCloseLocalEditors();
  286. delete FLocalEditors;
  287. HideFileFindDialog();
  288. if (FDelayedDeletionTimer)
  289. {
  290. DoDelayedDeletion(NULL);
  291. SAFE_DESTROY(FDelayedDeletionTimer);
  292. }
  293. SAFE_DESTROY(FDelayedDeletionList);
  294. // sometimes we do not get DDEnd so the list is not released
  295. SAFE_DESTROY(FDDFileList);
  296. DebugAssert(FSynchronizeController == NULL);
  297. CloseHandle(FDDExtMutex);
  298. FDDExtMutex = NULL;
  299. FreeLibrary(FOle32Library);
  300. FOle32Library = NULL;
  301. FDragMoveCursor = NULL;
  302. DebugAssert(!FErrorList);
  303. if (FEverShown)
  304. {
  305. // when window is never shown (like when running command-line operation),
  306. // particularly window site is not restored correctly (BoundsRect value set
  307. // in RestoreForm gets lost during handle allocation), so we do not want
  308. // it to be stored
  309. StoreParams();
  310. }
  311. Terminal = NULL;
  312. Queue = NULL;
  313. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  314. NonVisualDataModule->ScpExplorer = NULL;
  315. delete FQueueController;
  316. FQueueController = NULL;
  317. delete FQueueStatusSection;
  318. FQueueStatusSection = NULL;
  319. delete FQueueStatus;
  320. FQueueStatus = NULL;
  321. delete FUserActionTimer;
  322. FUserActionTimer = NULL;
  323. delete FNoteTimer;
  324. delete FNotes;
  325. delete FNoteData;
  326. SAFE_DESTROY(FDocks);
  327. SessionsPageControl->Images = NULL;
  328. // only after clearing Terminal (after DoTerminalListChanged => ... => AddSessionColor is called)
  329. SAFE_DESTROY(FSessionColors);
  330. SAFE_DESTROY(FSessionsDragDropFilesEx);
  331. SAFE_DESTROY(FHistoryMenu[0][0]);
  332. SAFE_DESTROY(FHistoryMenu[0][1]);
  333. SAFE_DESTROY(FHistoryMenu[1][0]);
  334. SAFE_DESTROY(FHistoryMenu[1][1]);
  335. if (FHiddenWindow != NULL)
  336. {
  337. DestroyWindow(FHiddenWindow);
  338. FHiddenWindow = NULL;
  339. }
  340. }
  341. //---------------------------------------------------------------------------
  342. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  343. {
  344. std::unique_ptr<TSessionData> Data;
  345. if (!Session.IsEmpty())
  346. {
  347. bool DefaultsOnly;
  348. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  349. }
  350. TTerminalManager * Manager = TTerminalManager::Instance();
  351. for (int Index = 0; Index < Manager->Count; Index++)
  352. {
  353. TTerminal * Terminal = Manager->Terminals[Index];
  354. if (Session.IsEmpty() ||
  355. Terminal->SessionData->IsSameSite(Data.get()))
  356. {
  357. if (Path.IsEmpty())
  358. {
  359. Terminal->ClearCaches();
  360. }
  361. else
  362. {
  363. Terminal->DirectoryModified(Path, true);
  364. }
  365. }
  366. }
  367. // We should flag a pending refresh for the background terminals or busy foreground terminals
  368. if ((Terminal != NULL) && Terminal->Active &&
  369. CanCommandLineFromAnotherInstance() &&
  370. (Session.IsEmpty() || Terminal->SessionData->IsSameSite(Data.get())) &&
  371. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  372. {
  373. Terminal->ReloadDirectory();
  374. }
  375. }
  376. //---------------------------------------------------------------------------
  377. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  378. {
  379. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  380. size_t MessageSize = sizeof(TCopyDataMessage);
  381. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  382. if (Result)
  383. {
  384. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  385. Result = (Message.Version == TCopyDataMessage::Version1);
  386. if (Result)
  387. {
  388. switch (Message.Command)
  389. {
  390. case TCopyDataMessage::CommandCanCommandLine:
  391. Result = CanCommandLineFromAnotherInstance();
  392. break;
  393. case TCopyDataMessage::CommandCommandLine:
  394. {
  395. UnicodeString CommandLine(Message.CommandLine);
  396. Result = CommandLineFromAnotherInstance(CommandLine);
  397. }
  398. break;
  399. case TCopyDataMessage::RefreshPanel:
  400. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  401. break;
  402. case TCopyDataMessage::MainWindowCheck:
  403. Result = true;
  404. break;
  405. default:
  406. Result = false;
  407. break;
  408. }
  409. }
  410. }
  411. Message.Result = Result ? 1 : 0;
  412. }
  413. //---------------------------------------------------------------------------
  414. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  415. {
  416. WNDCLASS WindowClass = {0};
  417. WindowClass.lpfnWndProc = DefWindowProc;
  418. WindowClass.hInstance = HInstance;
  419. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  420. FHiddenWindow = NULL;
  421. if (RegisterClass(&WindowClass))
  422. {
  423. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  424. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  425. }
  426. }
  427. //---------------------------------------------------------------------------
  428. bool __fastcall TCustomScpExplorerForm::CanConsole()
  429. {
  430. return (Terminal != NULL) && (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  431. }
  432. //---------------------------------------------------------------------------
  433. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  434. {
  435. bool Result = Visible && !NonVisualDataModule->Busy;
  436. return Result;
  437. }
  438. //---------------------------------------------------------------------------
  439. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  440. const UnicodeString & CommandLine)
  441. {
  442. TProgramParams Params(CommandLine);
  443. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  444. if (Result)
  445. {
  446. NonVisualDataModule->StartBusy();
  447. try
  448. {
  449. // this action is initiated from another process,
  450. // so it's likely that our window is not visible,
  451. // and user won't see what is going on
  452. Application->BringToFront();
  453. // reload sessions as we may be asked to open a session
  454. // just stored by another instance
  455. StoredSessions->Reload();
  456. UnicodeString SessionName = Params.Param[1];
  457. std::unique_ptr<TObjectList> DataList(new TObjectList());
  458. UnicodeString DownloadFile; // unused
  459. try
  460. {
  461. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this);
  462. }
  463. catch (EAbort &)
  464. {
  465. // Happens when opening session in PuTTY and in other situations,
  466. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  467. // to process the command-line on its own (or to pass it to yet another instance)
  468. }
  469. if (DataList->Count > 0)
  470. {
  471. TTerminalManager * Manager = TTerminalManager::Instance();
  472. Manager->ActiveTerminal = Manager->NewTerminals(DataList.get());
  473. }
  474. }
  475. __finally
  476. {
  477. NonVisualDataModule->EndBusy();
  478. }
  479. }
  480. return Result;
  481. }
  482. //---------------------------------------------------------------------------
  483. void __fastcall TCustomScpExplorerForm::SetTerminal(TTerminal * value)
  484. {
  485. if (FTerminal != value)
  486. {
  487. TerminalChanging();
  488. DoSetTerminal(value, false);
  489. }
  490. }
  491. //---------------------------------------------------------------------------
  492. void __fastcall TCustomScpExplorerForm::DoSetTerminal(TTerminal * value, bool Replace)
  493. {
  494. FTerminal = value;
  495. bool PrevAllowTransferPresetAutoSelect = FAllowTransferPresetAutoSelect;
  496. FAllowTransferPresetAutoSelect = false;
  497. try
  498. {
  499. TerminalChanged(Replace);
  500. }
  501. __finally
  502. {
  503. FAllowTransferPresetAutoSelect = PrevAllowTransferPresetAutoSelect;
  504. }
  505. if (Terminal != NULL)
  506. {
  507. TransferPresetAutoSelect();
  508. }
  509. }
  510. //---------------------------------------------------------------------------
  511. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TTerminal * value)
  512. {
  513. DoSetTerminal(value, true);
  514. }
  515. //---------------------------------------------------------------------------
  516. void __fastcall TCustomScpExplorerForm::TerminalChanging()
  517. {
  518. if (FTerminal != NULL)
  519. {
  520. UpdateTerminal(Terminal);
  521. }
  522. }
  523. //---------------------------------------------------------------------------
  524. void __fastcall TCustomScpExplorerForm::TerminalChanged(bool Replaced)
  525. {
  526. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  527. if (ManagedTerminal != NULL)
  528. {
  529. UpdateSessionColor((TColor)ManagedTerminal->StateData->Color);
  530. }
  531. DoTerminalListChanged();
  532. if (Replaced)
  533. {
  534. RemoteDirView->ReplaceTerminal(Terminal);
  535. }
  536. else
  537. {
  538. RemoteDirView->Terminal = Terminal;
  539. }
  540. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  541. if (Terminal != NULL)
  542. {
  543. if (Terminal->Active)
  544. {
  545. Terminal->RefreshDirectory();
  546. }
  547. DebugAssert(ManagedTerminal == Terminal);
  548. if (WinConfiguration->PreservePanelState)
  549. {
  550. if (ManagedTerminal->RemoteExplorerState != NULL)
  551. {
  552. RemoteDirView->RestoreState(ManagedTerminal->RemoteExplorerState);
  553. }
  554. else
  555. {
  556. RemoteDirView->ClearState();
  557. }
  558. }
  559. if (!Replaced)
  560. {
  561. InitStatusBar();
  562. }
  563. }
  564. UpdateTransferList();
  565. // Update panels Enable state before refreshing the labels
  566. UpdateControls();
  567. }
  568. //---------------------------------------------------------------------------
  569. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  570. {
  571. if (Queue != value)
  572. {
  573. if (FQueue != NULL)
  574. {
  575. FQueue->OnListUpdate = NULL;
  576. FQueue->OnQueueItemUpdate = NULL;
  577. }
  578. FQueue = value;
  579. if (FQueue != NULL)
  580. {
  581. DebugAssert(FQueue->OnListUpdate == NULL);
  582. FQueue->OnListUpdate = QueueListUpdate;
  583. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  584. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  585. }
  586. QueueChanged();
  587. }
  588. }
  589. //---------------------------------------------------------------------------
  590. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  591. TListItem * Item)
  592. {
  593. if (FQueueActedItem == Item)
  594. {
  595. FQueueActedItem = NULL;
  596. if ((QueueView3->PopupMenu != NULL) &&
  597. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  598. {
  599. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  600. ReleaseCapture();
  601. }
  602. }
  603. if (Item->Data == FPendingQueueActionItem)
  604. {
  605. FPendingQueueActionItem = NULL;
  606. }
  607. }
  608. //---------------------------------------------------------------------------
  609. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  610. {
  611. {
  612. TGuard Guard(FQueueStatusSection);
  613. FQueueStatusInvalidated = false;
  614. if (FQueue != NULL)
  615. {
  616. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  617. }
  618. }
  619. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  620. {
  621. FMaxQueueLength = FQueueStatus->Count;
  622. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  623. }
  624. FQueueController->UpdateQueueStatus(FQueueStatus);
  625. SetQueueProgress();
  626. UpdateQueueView();
  627. bool IsEmpty = (FQueueStatus == NULL) || (FQueueStatus->Count == 0);
  628. if (IsEmpty && (Terminal != NULL))
  629. {
  630. TOnceDoneOperation OnceDoneOperation =
  631. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  632. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  633. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  634. {
  635. FQueue->Enabled = false;
  636. }
  637. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  638. {
  639. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  640. }
  641. }
  642. }
  643. //---------------------------------------------------------------------------
  644. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  645. {
  646. UnicodeString Result;
  647. if (FQueueStatus != NULL)
  648. {
  649. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  650. {
  651. TFileOperationProgressType * ProgressData =
  652. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  653. if ((ProgressData != NULL) && ProgressData->InProgress)
  654. {
  655. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  656. }
  657. }
  658. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  659. {
  660. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  661. }
  662. }
  663. return Result;
  664. }
  665. //---------------------------------------------------------------------------
  666. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  667. {
  668. ComponentVisible[fcQueueView] =
  669. (WinConfiguration->QueueView.Show == qvShow) ||
  670. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  671. (FQueueStatus != NULL) && (FQueueStatus->Count > 0));
  672. }
  673. //---------------------------------------------------------------------------
  674. void __fastcall TCustomScpExplorerForm::QueueChanged()
  675. {
  676. if (FQueueStatus != NULL)
  677. {
  678. delete FQueueStatus;
  679. FQueueStatus = NULL;
  680. }
  681. UpdateQueueStatus(true);
  682. }
  683. //---------------------------------------------------------------------------
  684. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  685. {
  686. if (FQueue == Queue)
  687. {
  688. FQueueStatusInvalidated = true;
  689. }
  690. }
  691. //---------------------------------------------------------------------------
  692. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  693. TQueueItem * Item)
  694. {
  695. if (FQueue == Queue)
  696. {
  697. TGuard Guard(FQueueStatusSection);
  698. // this may be running in parallel with QueueChanged
  699. if (FQueueStatus != NULL)
  700. {
  701. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  702. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  703. {
  704. FRefreshLocalDirectory = (QueueItem == NULL) ||
  705. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  706. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  707. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  708. }
  709. if (QueueItem != NULL)
  710. {
  711. QueueItem->UserData = (void*)true;
  712. FQueueItemInvalidated = true;
  713. }
  714. }
  715. }
  716. }
  717. //---------------------------------------------------------------------------
  718. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  719. {
  720. // during standalone editing, we have no way to see/control queue,
  721. // so we have to always popup prompts automatically
  722. return FStandaloneEditing || GUIConfiguration->QueueAutoPopup;
  723. }
  724. //---------------------------------------------------------------------------
  725. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  726. {
  727. if (FQueueStatus != NULL)
  728. {
  729. bool QueueAutoPopup = IsQueueAutoPopup();
  730. bool NeedRefresh = FQueueController->NeedRefresh();
  731. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  732. FQueueItemInvalidated = false;
  733. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  734. bool Updated = false;
  735. TQueueItemProxy * QueueItem;
  736. bool WasUserAction;
  737. for (int Index = 0; Index < Limit; Index++)
  738. {
  739. bool Update = false;
  740. QueueItem = FQueueStatus->Items[Index];
  741. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  742. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  743. (FPendingQueueActionItem == NULL))
  744. {
  745. FPendingQueueActionItem = QueueItem;
  746. FUserActionTimer->Enabled = true;
  747. }
  748. if ((bool)QueueItem->UserData)
  749. {
  750. QueueItem->UserData = (void*)false;
  751. QueueItem->Update();
  752. Updated = true;
  753. Update = true;
  754. }
  755. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  756. {
  757. Update = true;
  758. }
  759. if (Update)
  760. {
  761. FQueueController->RefreshQueueItem(QueueItem);
  762. }
  763. }
  764. if (Updated)
  765. {
  766. NonVisualDataModule->UpdateNonVisibleActions();
  767. SetQueueProgress();
  768. }
  769. }
  770. }
  771. //---------------------------------------------------------------------------
  772. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  773. {
  774. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  775. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  776. }
  777. //---------------------------------------------------------------------------
  778. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  779. {
  780. if (ProgressData->Operation != foCalculateSize)
  781. {
  782. int OverallProgress;
  783. // FProgressForm is null when this is called from SetQueueProgress
  784. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  785. {
  786. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  787. }
  788. else
  789. {
  790. OverallProgress = ProgressData->OverallProgress();
  791. }
  792. // implies TBPF_NORMAL
  793. FTaskbarList->SetProgressValue(GetMainForm()->Handle, OverallProgress, 100);
  794. }
  795. else
  796. {
  797. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  798. }
  799. }
  800. //---------------------------------------------------------------------------
  801. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  802. {
  803. TTerminalManager::Instance()->QueueStatusUpdated();
  804. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  805. {
  806. if ((FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0))
  807. {
  808. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  809. {
  810. TFileOperationProgressType * ProgressData = NULL;
  811. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  812. {
  813. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  814. }
  815. if ((ProgressData != NULL) &&
  816. ProgressData->InProgress)
  817. {
  818. SetTaskbarListProgressValue(ProgressData);
  819. }
  820. else
  821. {
  822. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  823. }
  824. }
  825. else
  826. {
  827. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  828. }
  829. }
  830. else
  831. {
  832. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  833. }
  834. }
  835. UpdateQueueLabel();
  836. }
  837. //---------------------------------------------------------------------------
  838. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  839. {
  840. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  841. if (FQueueStatus != NULL)
  842. {
  843. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  844. if (ActiveAndPendingPrimaryCount > 0)
  845. {
  846. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  847. }
  848. }
  849. QueueLabel->Caption = Caption;
  850. }
  851. //---------------------------------------------------------------------------
  852. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  853. {
  854. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  855. static_cast<TComponent*>(GetComponent(fcTransferList)));
  856. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  857. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  858. TransferList->Strings->BeginUpdate();
  859. try
  860. {
  861. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  862. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  863. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  864. if (FTransferDropDownHint.IsEmpty())
  865. {
  866. FTransferDropDownHint = TransferDropDown->Hint;
  867. }
  868. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  869. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  870. TransferDropDown->Text = StripHotkey(Name);
  871. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  872. (FTransferDropDownHint, StripHotkey(Name),
  873. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  874. FLAGMASK(((Terminal != NULL) && Terminal->Active), Terminal->UsableCopyParamAttrs(0).General))));
  875. // update the label, otherwise when it is updated only on the first draw
  876. // of the list, it is drawn "bold" for some reason
  877. FTransferListHoverIndex = TransferList->ItemIndex;
  878. UpdateTransferLabel();
  879. }
  880. __finally
  881. {
  882. TransferList->Strings->EndUpdate();
  883. }
  884. }
  885. //---------------------------------------------------------------------------
  886. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  887. {
  888. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  889. DebugAssert(Toolbar != NULL);
  890. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  891. }
  892. //---------------------------------------------------------------------------
  893. void __fastcall TCustomScpExplorerForm::UpdateActions()
  894. {
  895. TForm::UpdateActions();
  896. if (ComponentVisible[fcCustomCommandsBand])
  897. {
  898. UpdateCustomCommandsToolbar();
  899. }
  900. }
  901. //---------------------------------------------------------------------------
  902. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  903. {
  904. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  905. }
  906. //---------------------------------------------------------------------------
  907. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  908. {
  909. Color = WinConfiguration->UseDarkTheme() ? TColor(RGB(43, 43, 43)) : clBtnFace;
  910. DebugAssert(Configuration && RemoteDirView);
  911. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  912. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  913. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  914. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  915. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  916. if (RemoteDirView->RowSelect != WinConfiguration->FullRowSelect)
  917. {
  918. RemoteDirView->RowSelect = WinConfiguration->FullRowSelect;
  919. // selection is not redrawn automatically when RowSelect changes
  920. RemoteDirView->Invalidate();
  921. }
  922. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  923. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  924. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  925. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  926. UpdateSessionsPageControlHeight();
  927. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  928. UpdateToolbarDisplayMode();
  929. UpdateTransferList();
  930. if (Terminal != NULL)
  931. {
  932. TransferPresetAutoSelect();
  933. }
  934. UpdateQueueView();
  935. UpdateControls();
  936. // this can be called even before constuctor finishes.
  937. if (FEditorManager != NULL)
  938. {
  939. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  940. }
  941. // this can be called even before constuctor finishes.
  942. if (FLocalEditors != NULL)
  943. {
  944. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  945. {
  946. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  947. }
  948. }
  949. if (ComponentVisible[fcCustomCommandsBand])
  950. {
  951. UpdateCustomCommandsToolbar();
  952. }
  953. // show only when keeping queue items forever,
  954. // otherwise, its enough to have in in the context menu
  955. QueueDeleteAllDoneQueueToolbarItem->Visible =
  956. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  957. if (FFileColorsCurrent != WinConfiguration->FileColors)
  958. {
  959. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  960. FFileColorsCurrent = WinConfiguration->FileColors;
  961. FileColorsChanged();
  962. }
  963. }
  964. //---------------------------------------------------------------------------
  965. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  966. {
  967. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  968. DirView->Invalidate();
  969. }
  970. //---------------------------------------------------------------------------
  971. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  972. {
  973. DoFileColorsChanged(RemoteDirView);
  974. }
  975. //---------------------------------------------------------------------------
  976. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  977. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  978. void * /*Arg*/)
  979. {
  980. if (Token != NULL)
  981. {
  982. TForm * Editor = dynamic_cast<TForm*>(Token);
  983. DebugAssert(Editor != NULL);
  984. ReconfigureEditorForm(Editor);
  985. }
  986. }
  987. //---------------------------------------------------------------------------
  988. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  989. {
  990. WinConfiguration->DDTransferConfirmation = asOn;
  991. }
  992. //---------------------------------------------------------------------------
  993. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  994. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  995. {
  996. // noop
  997. }
  998. //---------------------------------------------------------------------------
  999. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1000. TTransferDirection Direction, TTransferType Type, bool Temp,
  1001. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1002. bool Confirm, bool DragDrop, int Options)
  1003. {
  1004. bool Result = true;
  1005. DebugAssert(Terminal && Terminal->Active);
  1006. // these parameters are known in advance
  1007. int Params =
  1008. FLAGMASK(Type == ttMove, cpDelete);
  1009. bool ToTemp = (Temp && (Direction == tdToLocal));
  1010. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1011. {
  1012. bool DisableNewerOnly =
  1013. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1014. ToTemp;
  1015. Options |=
  1016. FLAGMASK(ToTemp, coTemp) |
  1017. FLAGMASK(!Terminal->IsCapable[fsBackgroundTransfers], coDisableQueue) |
  1018. coDoNotShowAgain;
  1019. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1020. int CopyParamAttrs = (Direction == tdToRemote ?
  1021. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1022. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1023. int OutputOptions =
  1024. FLAGMASK(DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto),
  1025. cooDoNotShowAgain);
  1026. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1027. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1028. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1029. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions);
  1030. if (Result)
  1031. {
  1032. if (FLAGSET(OutputOptions, cooDoNotShowAgain))
  1033. {
  1034. if (DragDrop)
  1035. {
  1036. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1037. {
  1038. PopupTrayBalloon(NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation,
  1039. NULL, 0, EnableDDTransferConfirmation, NULL);
  1040. }
  1041. WinConfiguration->DDTransferConfirmation = asOff;
  1042. }
  1043. else
  1044. {
  1045. WinConfiguration->ConfirmTransferring = false;
  1046. }
  1047. }
  1048. else
  1049. {
  1050. // User explicitly unchecked "do not show again",
  1051. // so show him the dialog the next time
  1052. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1053. {
  1054. WinConfiguration->DDTransferConfirmation = asOn;
  1055. }
  1056. }
  1057. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1058. }
  1059. }
  1060. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fsBackgroundTransfers])
  1061. {
  1062. Configuration->Usage->Inc(L"TransfersOnBackground");
  1063. // these parameter are known only after transfer dialog
  1064. Params |=
  1065. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1066. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1067. Result = false;
  1068. ClearTransferSourceSelection(Direction);
  1069. }
  1070. return Result;
  1071. }
  1072. //---------------------------------------------------------------------------
  1073. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1074. {
  1075. if (FOnFileOperationFinished != NULL)
  1076. {
  1077. FOnFileOperationFinished(UnicodeString(), true);
  1078. }
  1079. else
  1080. {
  1081. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1082. if (HasDirView[Side])
  1083. {
  1084. DirView(Side)->SelectAll(smNone);
  1085. }
  1086. }
  1087. }
  1088. //---------------------------------------------------------------------------
  1089. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1090. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1091. const UnicodeString TargetDirectory, const TGUICopyParamType & CopyParam,
  1092. int Params)
  1093. {
  1094. DebugAssert(Queue != NULL);
  1095. bool SingleFile = false;
  1096. if (FileList->Count == 1)
  1097. {
  1098. if (Direction == tdToRemote)
  1099. {
  1100. UnicodeString FileName = FileList->Strings[0];
  1101. SingleFile = FileExists(ApiPath(FileName));
  1102. }
  1103. else
  1104. {
  1105. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1106. SingleFile = !File->IsDirectory;
  1107. }
  1108. }
  1109. TQueueItem * QueueItem;
  1110. if (Direction == tdToRemote)
  1111. {
  1112. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1113. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1114. }
  1115. else
  1116. {
  1117. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1118. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1119. }
  1120. AddQueueItem(Queue, QueueItem, Terminal);
  1121. }
  1122. //---------------------------------------------------------------------------
  1123. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TTerminal * Terminal)
  1124. {
  1125. if (Queue->IsEmpty)
  1126. {
  1127. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  1128. ManagedTerminal->QueueOperationStart = Now();
  1129. }
  1130. Queue->AddItem(QueueItem);
  1131. }
  1132. //---------------------------------------------------------------------------
  1133. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1134. {
  1135. }
  1136. //---------------------------------------------------------------------------
  1137. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1138. {
  1139. DebugAssert(FDocks != NULL);
  1140. for (int Index = 0; Index < ComponentCount; Index++)
  1141. {
  1142. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1143. if ((Dock != NULL) && (Dock->Tag == 0))
  1144. {
  1145. FDocks->Add(Dock);
  1146. }
  1147. }
  1148. CollectItemsWithTextDisplayMode(this);
  1149. ConfigurationChanged();
  1150. QueuePanel->Height =
  1151. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1152. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1153. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1154. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1155. }
  1156. //---------------------------------------------------------------------------
  1157. void __fastcall TCustomScpExplorerForm::StoreParams()
  1158. {
  1159. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1160. WinConfiguration->QueueView.HeightPixelsPerInch = GetControlPixelsPerInch(this);
  1161. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1162. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1163. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1164. }
  1165. //---------------------------------------------------------------------------
  1166. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1167. {
  1168. if (!FFormRestored)
  1169. {
  1170. FFormRestored = true;
  1171. RestoreFormParams();
  1172. }
  1173. TForm::CreateParams(Params);
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1177. {
  1178. DebugAssert(FDocks != NULL);
  1179. for (int Index = 0; Index < FDocks->Count; Index++)
  1180. {
  1181. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1182. }
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1186. {
  1187. SetDockAllowDrag(true);
  1188. while (!ButtonsStr.IsEmpty())
  1189. {
  1190. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1191. UnicodeString Name = CutToChar(S, L'=', true);
  1192. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1193. {
  1194. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1195. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1196. {
  1197. while (!S.IsEmpty())
  1198. {
  1199. UnicodeString S2 = CutToChar(S, L',', true);
  1200. UnicodeString Name = CutToChar(S2, L':', true);
  1201. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1202. {
  1203. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1204. if (SameText(GetToolbarItemName(Item), Name))
  1205. {
  1206. // forward compatibility
  1207. UnicodeString S3 = CutToChar(S2, L':', true);
  1208. bool Visible = StrToIntDef(S3, 0);
  1209. Item->Visible = Visible;
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. }
  1216. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1217. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1221. {
  1222. UnicodeString Result;
  1223. SetDockAllowDrag(true);
  1224. Result = ::GetToolbarsLayoutStr(this);
  1225. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1226. return Result;
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1230. {
  1231. UnicodeString Result;
  1232. if (Item->Action != NULL)
  1233. {
  1234. Result = Item->Action->Name;
  1235. Result = RemoveSuffix(Result, L"Action");
  1236. }
  1237. else
  1238. {
  1239. Result = Item->Name;
  1240. Result = RemoveSuffix(Result, L"SubmenuItem");
  1241. Result = RemoveSuffix(Result, L"Item");
  1242. }
  1243. return Result;
  1244. }
  1245. //---------------------------------------------------------------------------
  1246. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1247. {
  1248. UnicodeString Result;
  1249. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1250. {
  1251. UnicodeString ToolbarStr;
  1252. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1253. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1254. {
  1255. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1256. {
  1257. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1258. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1259. // Once we introduce any buttons that aer hidden by default, we would have to remember their initial state
  1260. // and save the changes here only.
  1261. if (!Item->Visible)
  1262. {
  1263. UnicodeString Name = GetToolbarItemName(Item);
  1264. DebugAssert(Name.Pos(L"TBX") == 0);
  1265. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1266. }
  1267. }
  1268. }
  1269. if (!ToolbarStr.IsEmpty())
  1270. {
  1271. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1272. }
  1273. }
  1274. return Result;
  1275. }
  1276. //---------------------------------------------------------------------------
  1277. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1278. {
  1279. DebugAssert(FProgressForm == NULL);
  1280. FProgressForm =
  1281. new TProgressForm(Application, (FTransferResumeList != NULL), Terminal->IsCapable[fsSkipTransfer], SynchronizeProgress);
  1282. FProgressForm->DeleteLocalToRecycleBin =
  1283. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1284. FProgressForm->DeleteRemoteToRecycleBin =
  1285. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1286. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1287. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1288. LockWindow();
  1289. if (FTaskbarList != NULL)
  1290. {
  1291. // Actually, do not know what hides the progress once the operation finishes
  1292. SetTaskbarListProgressState(TBPF_NORMAL);
  1293. }
  1294. }
  1295. //---------------------------------------------------------------------------
  1296. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1297. {
  1298. UnlockWindow();
  1299. SAFE_DESTROY(FProgressForm);
  1300. SetQueueProgress();
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1304. TFileOperationProgressType & ProgressData)
  1305. {
  1306. // Download to temporary local directory
  1307. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1308. {
  1309. bool Continue = true;
  1310. FPendingTempSpaceWarn = false;
  1311. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1312. if (!Continue)
  1313. {
  1314. Abort();
  1315. }
  1316. }
  1317. // operation is being executed and we still didn't show up progress form
  1318. if (ProgressData.InProgress && !FProgressForm)
  1319. {
  1320. CreateProgressForm(NULL);
  1321. // When main window is hidden, synchronisation form does not exist (we do not get here during synchronization - only comparing),
  1322. // we suppose "/upload" or URL download mode
  1323. if (!Visible && (ProgressData.Operation != foCalculateSize) &&
  1324. (ProgressData.Operation != foCalculateChecksum) &&
  1325. // Hack to prevent renames from DoSynchronizeMove (synchronize checklist) closing the connection
  1326. (ProgressData.Operation != foRemoteMove) &&
  1327. (FSynchronizeProgressForm == NULL) &&
  1328. !FStandaloneEditing)
  1329. {
  1330. FProgressForm->OnceDoneOperation = odoDisconnect;
  1331. }
  1332. }
  1333. // operation is finished (or terminated), so we hide progress form
  1334. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1335. {
  1336. DestroyProgressForm();
  1337. if (ProgressData.Operation == foCalculateSize)
  1338. {
  1339. // When calculating size before transfer, the abort caused by
  1340. // cancel flag set due to "MoveToQueue" below,
  1341. // is not propagated back to us in ExecuteFileOperation,
  1342. // as it is silently swallowed.
  1343. // So we explicitly (re)throw it here.
  1344. if (FMoveToQueue)
  1345. {
  1346. Abort();
  1347. }
  1348. }
  1349. else
  1350. {
  1351. if ((ProgressData.Cancel == csContinue) &&
  1352. !FAutoOperation)
  1353. {
  1354. OperationComplete(ProgressData.StartTime);
  1355. }
  1356. }
  1357. }
  1358. if (FProgressForm &&
  1359. // Can happen only during synchronization, when ending one of the operations
  1360. ProgressData.InProgress)
  1361. {
  1362. FProgressForm->SetProgressData(ProgressData);
  1363. if (FTaskbarList != NULL)
  1364. {
  1365. DebugAssert(ProgressData.InProgress);
  1366. SetTaskbarListProgressValue(&ProgressData);
  1367. }
  1368. if (FProgressForm->Cancel > csContinue)
  1369. {
  1370. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1371. if (FProgressForm->Cancel == csCancelFile)
  1372. {
  1373. FProgressForm->ClearCancel();
  1374. }
  1375. // cancel cancels even the move
  1376. FMoveToQueue = false;
  1377. }
  1378. else if (FProgressForm->MoveToQueue)
  1379. {
  1380. FMoveToQueue = true;
  1381. ProgressData.SetCancelAtLeast(csCancel);
  1382. }
  1383. if ((FTransferResumeList != NULL) &&
  1384. ProgressData.InProgress &&
  1385. ((ProgressData.Operation == foCopy) || (ProgressData.Operation == foMove)) &&
  1386. !ProgressData.FullFileName.IsEmpty())
  1387. {
  1388. if ((FTransferResumeList->Count == 0) ||
  1389. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1390. {
  1391. // note that we do not recognize directories from files here
  1392. FTransferResumeList->Add(ProgressData.FullFileName);
  1393. }
  1394. }
  1395. }
  1396. }
  1397. //---------------------------------------------------------------------------
  1398. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1399. const TDateTime & StartTime)
  1400. {
  1401. if (GUIConfiguration->BeepOnFinish &&
  1402. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1403. {
  1404. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1405. DWORD Sound;
  1406. if (!ExtractFileExt(BeepSound).IsEmpty())
  1407. {
  1408. Sound = SND_FILENAME;
  1409. }
  1410. else
  1411. {
  1412. Sound = SND_ALIAS;
  1413. }
  1414. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1415. }
  1416. }
  1417. //---------------------------------------------------------------------------
  1418. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1419. TFileOperationProgressType & ProgressData)
  1420. {
  1421. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1422. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1423. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1424. FileOperationProgress(ProgressData);
  1425. }
  1426. //---------------------------------------------------------------------------
  1427. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1428. {
  1429. UnicodeString Result;
  1430. if (FProgressForm != NULL)
  1431. {
  1432. Result = FProgressForm->ProgressStr();
  1433. }
  1434. return Result;
  1435. }
  1436. //---------------------------------------------------------------------------
  1437. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1438. bool DragDrop)
  1439. {
  1440. return (!DragDrop && (DropSourceControl == NULL)) ||
  1441. (DropSourceControl == RemoteDirView);
  1442. }
  1443. //---------------------------------------------------------------------------
  1444. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1445. TFileOperation Operation, TOperationSide Side,
  1446. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1447. TOnceDoneOperation & OnceDoneOperation)
  1448. {
  1449. if (!FAutoOperation)
  1450. {
  1451. // no selection on "/upload", form servers only as event handler
  1452. // (it is not displayed)
  1453. if (PanelOperation(Side, FDragDropOperation) &&
  1454. Visible && (Operation != foCalculateSize) &&
  1455. (Operation != foGetProperties) && (Operation != foCalculateChecksum))
  1456. {
  1457. if (FOnFileOperationFinished != NULL)
  1458. {
  1459. FOnFileOperationFinished(FileName, Success);
  1460. }
  1461. else
  1462. {
  1463. TCustomDirView * DView = DirView(Side);
  1464. UnicodeString FileNameOnly = ExtractFileName(FileName, (Side == osRemote));
  1465. TListItem *Item = DView->FindFileItem(FileNameOnly);
  1466. // this can happen when local drive is unplugged in the middle of the operation
  1467. if (Item != NULL)
  1468. {
  1469. if (Success) Item->Selected = false;
  1470. DView->MakeProgressVisible(Item);
  1471. }
  1472. }
  1473. }
  1474. if ((Operation == foCopy) || (Operation == foMove))
  1475. {
  1476. if (Side == osLocal)
  1477. {
  1478. Configuration->Usage->Inc(L"UploadedFiles");
  1479. }
  1480. else
  1481. {
  1482. Configuration->Usage->Inc(L"DownloadedFiles");
  1483. }
  1484. }
  1485. }
  1486. if (Success && (FSynchronizeController != NULL))
  1487. {
  1488. if (Operation == foCopy)
  1489. {
  1490. DebugAssert(Side == osLocal);
  1491. FSynchronizeController->LogOperation(soUpload, FileName);
  1492. }
  1493. else if (Operation == foDelete)
  1494. {
  1495. DebugAssert(Side == osRemote);
  1496. FSynchronizeController->LogOperation(soDelete, FileName);
  1497. }
  1498. }
  1499. if (FProgressForm)
  1500. {
  1501. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1502. }
  1503. }
  1504. //---------------------------------------------------------------------------
  1505. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1506. TFileOperation Operation, TOperationSide Side,
  1507. bool Temp, const UnicodeString & FileName, Boolean Success,
  1508. TOnceDoneOperation & OnceDoneOperation)
  1509. {
  1510. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1511. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1512. OnceDoneOperation);
  1513. }
  1514. //---------------------------------------------------------------------------
  1515. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1516. {
  1517. DebugAssert(GetSide(Side) == osRemote);
  1518. DebugUsedParam(Side);
  1519. return RemoteDirView;
  1520. }
  1521. //---------------------------------------------------------------------------
  1522. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1523. {
  1524. DebugAssert(GetSide(Side) == osRemote);
  1525. DebugUsedParam(Side);
  1526. return (Terminal != NULL);
  1527. }
  1528. //---------------------------------------------------------------------------
  1529. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1530. TOperationSide Side, int FilesOnly)
  1531. {
  1532. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1536. TOperationSide Side, int FilesOnly)
  1537. {
  1538. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1539. }
  1540. //---------------------------------------------------------------------------
  1541. struct THistoryItemData
  1542. {
  1543. short int Side;
  1544. short int Index;
  1545. };
  1546. //---------------------------------------------------------------------------
  1547. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1548. {
  1549. DirView(Side)->HistoryGo(Index);
  1550. }
  1551. //---------------------------------------------------------------------------
  1552. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1553. {
  1554. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1555. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1556. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1557. }
  1558. //---------------------------------------------------------------------------
  1559. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1560. bool Back)
  1561. {
  1562. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1563. {
  1564. TCustomDirView * DView = DirView(Side);
  1565. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1566. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1567. if (ICount > 10)
  1568. {
  1569. ICount = 10;
  1570. }
  1571. Menu->Items->Clear();
  1572. THistoryItemData Data;
  1573. Data.Side = Side;
  1574. for (short int i = 1; i <= ICount; i++)
  1575. {
  1576. TTBCustomItem * Item = new TTBXItem(Menu);
  1577. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1578. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, (Side == osRemote));
  1579. Item->Hint = DView->HistoryPath[Data.Index];
  1580. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1581. Item->Tag = *reinterpret_cast<int*>(&Data);
  1582. Item->OnClick = HistoryItemClick;
  1583. Menu->Items->Add(Item);
  1584. }
  1585. }
  1586. }
  1587. //---------------------------------------------------------------------------
  1588. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1589. TOperationSide Side, bool Back)
  1590. {
  1591. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1592. {
  1593. // workaround
  1594. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1595. // operator new allocates memory in Pascal code, but calls inline
  1596. // contructor in C++, leading in problems, the function does
  1597. // both in Pascal code
  1598. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1599. UpdateHistoryMenu(Side, Back);
  1600. }
  1601. return FHistoryMenu[Side == osLocal][Back];
  1602. }
  1603. //---------------------------------------------------------------------------
  1604. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1605. TCustomDirView *Sender)
  1606. {
  1607. TOperationSide Side = (Sender == DirView(osRemote) ? osRemote : osLocal);
  1608. UpdateHistoryMenu(Side, true);
  1609. UpdateHistoryMenu(Side, false);
  1610. }
  1611. //---------------------------------------------------------------------------
  1612. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1613. {
  1614. // remote custom commands can be executed only if the server supports shell commands
  1615. // or have secondary shell
  1616. return (FTerminal != NULL) && (FTerminal->IsCapable[fcSecondaryShell] || FTerminal->IsCapable[fcShellAnyCommand]);
  1617. }
  1618. //---------------------------------------------------------------------------
  1619. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1620. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1621. {
  1622. int Result;
  1623. TFileCustomCommand RemoteCustomCommand;
  1624. TLocalCustomCommand LocalCustomCommand;
  1625. TFileCustomCommand * NonInteractiveCustomCommand =
  1626. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1627. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1628. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1629. if (FLAGCLEAR(Command.Params, ccLocal))
  1630. {
  1631. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1632. // custom command that does not operate with files can be executed anytime ...
  1633. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1634. {
  1635. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1636. {
  1637. // ... but do not show such command in remote file menu (TODO)
  1638. Result = AllowedState;
  1639. }
  1640. else
  1641. {
  1642. Result = -1;
  1643. }
  1644. }
  1645. else
  1646. {
  1647. if ((ListType == ccltAll) || (ListType == ccltFile))
  1648. {
  1649. Result = ((FCurrentSide == osRemote) && DirView(osRemote)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1650. }
  1651. else
  1652. {
  1653. Result = -1;
  1654. }
  1655. }
  1656. }
  1657. else
  1658. {
  1659. // custom command that does not operate with files can be executed anytime
  1660. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1661. {
  1662. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1663. }
  1664. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1665. {
  1666. if ((ListType == ccltAll) || (ListType == ccltFile))
  1667. {
  1668. // special case is "diff"-style command that can be executed over any side,
  1669. // if we have both sides
  1670. Result =
  1671. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1672. // directly (instead of EnableSelectedOperation) to pass
  1673. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1674. ((HasDirView[osLocal] && DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1675. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1676. }
  1677. else if (ListType == ccltBoth)
  1678. {
  1679. Result = 1;
  1680. }
  1681. else
  1682. {
  1683. Result = -1;
  1684. }
  1685. }
  1686. else
  1687. {
  1688. if ((ListType == ccltAll) || (ListType == ccltFile))
  1689. {
  1690. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1691. }
  1692. else
  1693. {
  1694. Result = -1;
  1695. }
  1696. }
  1697. }
  1698. return Result;
  1699. }
  1700. //---------------------------------------------------------------------------
  1701. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1702. TStrings * FileList, const TCustomCommandType & ACommand,
  1703. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1704. {
  1705. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1706. {
  1707. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1708. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1709. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1710. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1711. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1712. bool Capture =
  1713. FLAGSET(ACommand.Params, ccShowResults) ||
  1714. FLAGSET(ACommand.Params, ccCopyResults) ||
  1715. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1716. TCaptureOutputEvent OutputEvent = NULL;
  1717. DebugAssert(FCapturedLog == NULL);
  1718. if (Capture)
  1719. {
  1720. FCapturedLog = new TStringList();
  1721. OutputEvent = TerminalCaptureLog;
  1722. }
  1723. try
  1724. {
  1725. if (!RemoteCustomCommand.IsFileCommand(Command))
  1726. {
  1727. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1728. OutputEvent);
  1729. }
  1730. else
  1731. {
  1732. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1733. }
  1734. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1735. {
  1736. if (FLAGSET(ACommand.Params, ccCopyResults))
  1737. {
  1738. CopyToClipboard(FCapturedLog);
  1739. }
  1740. if (FLAGSET(ACommand.Params, ccShowResults))
  1741. {
  1742. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1743. }
  1744. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1745. {
  1746. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1747. }
  1748. }
  1749. }
  1750. __finally
  1751. {
  1752. SAFE_DESTROY(FCapturedLog);
  1753. }
  1754. }
  1755. }
  1756. //---------------------------------------------------------------------------
  1757. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1758. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1759. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1760. {
  1761. TStrings * LocalFileList = NULL;
  1762. TStrings * RemoteFileList = NULL;
  1763. TStrings * RemoteFileListFull = NULL;
  1764. try
  1765. {
  1766. if (LocalFileCommand)
  1767. {
  1768. if (ALocalFileList == NULL)
  1769. {
  1770. DebugAssert(HasDirView[osLocal]);
  1771. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1772. // directly (instead of EnableSelectedOperation) to pass
  1773. // false to FocusedFileOnlyWhenFocused
  1774. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  1775. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  1776. }
  1777. else
  1778. {
  1779. LocalFileList = ALocalFileList;
  1780. }
  1781. if (FileListCommand)
  1782. {
  1783. if (LocalFileList->Count != 1)
  1784. {
  1785. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  1786. }
  1787. }
  1788. else
  1789. {
  1790. if ((LocalFileList->Count != 1) &&
  1791. (FileList->Count != 1) &&
  1792. (LocalFileList->Count != FileList->Count))
  1793. {
  1794. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  1795. }
  1796. }
  1797. }
  1798. UnicodeString RootTempDir;
  1799. UnicodeString TempDir;
  1800. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  1801. if (!RemoteFiles)
  1802. {
  1803. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  1804. }
  1805. try
  1806. {
  1807. TDateTimes RemoteFileTimes;
  1808. if (RemoteFiles)
  1809. {
  1810. RemoteFileList = FileList;
  1811. }
  1812. else
  1813. {
  1814. RemoteFileList = new TStringList();
  1815. TMakeLocalFileListParams MakeFileListParam;
  1816. MakeFileListParam.FileList = RemoteFileList;
  1817. MakeFileListParam.FileTimes = &RemoteFileTimes;
  1818. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  1819. MakeFileListParam.Recursive =
  1820. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  1821. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  1822. if (!MakeFileListParam.Recursive)
  1823. {
  1824. RemoteFileTimes.clear();
  1825. RemoteFileListFull = new TStringList();
  1826. MakeFileListParam.FileList = RemoteFileListFull;
  1827. MakeFileListParam.Recursive = true;
  1828. MakeFileListParam.IncludeDirs = false;
  1829. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  1830. }
  1831. else
  1832. {
  1833. RemoteFileListFull = RemoteFileList;
  1834. }
  1835. }
  1836. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  1837. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  1838. if (!NonBlocking)
  1839. {
  1840. int Count;
  1841. if (FileListCommand)
  1842. {
  1843. Count = 1;
  1844. }
  1845. else if (LocalFileCommand)
  1846. {
  1847. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  1848. }
  1849. else
  1850. {
  1851. Count = RemoteFileList->Count;
  1852. }
  1853. Progress.Start(foCustomCommand, osRemote, Count);
  1854. DebugAssert(FProgressForm != NULL);
  1855. FProgressForm->ReadOnly = true;
  1856. }
  1857. try
  1858. {
  1859. if (FileListCommand)
  1860. {
  1861. UnicodeString LocalFile;
  1862. // MakeFileList does not delimit filenames
  1863. UnicodeString FileList = MakeFileList(RemoteFileList);
  1864. if (LocalFileCommand)
  1865. {
  1866. DebugAssert(LocalFileList->Count == 1);
  1867. LocalFile = LocalFileList->Strings[0];
  1868. }
  1869. TLocalCustomCommand CustomCommand(Data,
  1870. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  1871. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  1872. if (NonBlocking)
  1873. {
  1874. DebugAssert(!POutput);
  1875. ExecuteShellChecked(ShellCommand);
  1876. }
  1877. else
  1878. {
  1879. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  1880. }
  1881. }
  1882. else if (LocalFileCommand)
  1883. {
  1884. if (LocalFileList->Count == 1)
  1885. {
  1886. UnicodeString LocalFile = LocalFileList->Strings[0];
  1887. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  1888. {
  1889. UnicodeString FileName = RemoteFileList->Strings[Index];
  1890. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  1891. Progress.SetFile(FileNameForProgress);
  1892. TLocalCustomCommand CustomCommand(Data,
  1893. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  1894. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1895. TOnceDoneOperation OnceDoneOperation;
  1896. // Do not unselect anything, as it won't work with two panels anyway
  1897. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1898. }
  1899. }
  1900. else if (RemoteFileList->Count == 1)
  1901. {
  1902. UnicodeString FileName = RemoteFileList->Strings[0];
  1903. for (int Index = 0; Index < LocalFileList->Count; Index++)
  1904. {
  1905. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  1906. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  1907. Progress.SetFile(LocalFileNameOnly);
  1908. TLocalCustomCommand CustomCommand(
  1909. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1910. FileName, LocalFileName, L"");
  1911. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1912. TOnceDoneOperation OnceDoneOperation;
  1913. // Do not unselect anything, as it won't work with two panels anyway
  1914. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1915. }
  1916. }
  1917. else
  1918. {
  1919. if (LocalFileList->Count != RemoteFileList->Count)
  1920. {
  1921. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  1922. }
  1923. for (int Index = 0; Index < LocalFileList->Count; Index++)
  1924. {
  1925. UnicodeString FileName = RemoteFileList->Strings[Index];
  1926. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  1927. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  1928. Progress.SetFile(LocalFileNameOnly); // sic
  1929. TLocalCustomCommand CustomCommand(
  1930. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1931. FileName, LocalFileName, L"");
  1932. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1933. TOnceDoneOperation OnceDoneOperation;
  1934. // Do not unselect anything, as it won't work with two panels anyway
  1935. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  1936. }
  1937. }
  1938. }
  1939. else
  1940. {
  1941. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  1942. {
  1943. UnicodeString FileName = RemoteFileList->Strings[Index];
  1944. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  1945. Progress.SetFile(FileNameForProgress);
  1946. TLocalCustomCommand CustomCommand(Data,
  1947. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  1948. FileName, L"", L"");
  1949. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  1950. TOnceDoneOperation OnceDoneOperation;
  1951. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  1952. }
  1953. }
  1954. }
  1955. __finally
  1956. {
  1957. if (!NonBlocking)
  1958. {
  1959. Progress.Stop();
  1960. }
  1961. }
  1962. DebugAssert(!FAutoOperation);
  1963. if (!RemoteFiles)
  1964. {
  1965. TempDir = IncludeTrailingBackslash(TempDir);
  1966. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  1967. {
  1968. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  1969. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  1970. // Skip directories, process only nested files.
  1971. // The check is redundant as FileAge fails for directories anyway.
  1972. !DirectoryExists(FileName))
  1973. {
  1974. UnicodeString RemoteDir =
  1975. UnixExtractFileDir(
  1976. UnixIncludeTrailingBackslash(FTerminal->CurrentDirectory) +
  1977. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  1978. TDateTime NewTime;
  1979. if (FileAge(FileName, NewTime) &&
  1980. (NewTime != RemoteFileTimes[Index]))
  1981. {
  1982. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  1983. TemporaryFileCopyParam(CopyParam);
  1984. CopyParam.FileMask = L"";
  1985. FAutoOperation = true;
  1986. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  1987. TemporaryFilesList->Add(FileName);
  1988. FTerminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  1989. }
  1990. }
  1991. }
  1992. }
  1993. }
  1994. __finally
  1995. {
  1996. FAutoOperation = false;
  1997. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  1998. {
  1999. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  2000. }
  2001. }
  2002. }
  2003. __finally
  2004. {
  2005. if (RemoteFileList != FileList)
  2006. {
  2007. delete RemoteFileList;
  2008. }
  2009. if (LocalFileList != ALocalFileList)
  2010. {
  2011. delete LocalFileList;
  2012. }
  2013. if (RemoteFileListFull != RemoteFileList)
  2014. {
  2015. delete RemoteFileListFull;
  2016. }
  2017. }
  2018. }
  2019. //---------------------------------------------------------------------------
  2020. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2021. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2022. bool FileListCommand, UnicodeString * POutput)
  2023. {
  2024. std::unique_ptr<TStrings> SelectedFileList(DirView(osLocal)->CreateFileList(false, true, NULL));
  2025. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2026. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2027. {
  2028. UnicodeString FileName = SelectedFileList->Strings[Index];
  2029. if (DirectoryExists(FileName))
  2030. {
  2031. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2032. {
  2033. LocalFileList->Add(FileName);
  2034. }
  2035. if (FLAGSET(ACommand.Params, ccRecursive))
  2036. {
  2037. TMakeLocalFileListParams MakeFileListParam;
  2038. MakeFileListParam.FileList = LocalFileList.get();
  2039. MakeFileListParam.FileTimes = NULL;
  2040. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2041. MakeFileListParam.Recursive = true;
  2042. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2043. }
  2044. }
  2045. else
  2046. {
  2047. LocalFileList->Add(FileName);
  2048. }
  2049. }
  2050. if (FileListCommand)
  2051. {
  2052. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2053. TLocalCustomCommand CustomCommand(
  2054. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2055. L"", L"", FileList);
  2056. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2057. }
  2058. else
  2059. {
  2060. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2061. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2062. DebugAssert(FProgressForm != NULL);
  2063. FProgressForm->ReadOnly = true;
  2064. try
  2065. {
  2066. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2067. {
  2068. UnicodeString FileName = LocalFileList->Strings[Index];
  2069. Progress.SetFile(FileName);
  2070. TLocalCustomCommand CustomCommand(
  2071. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2072. FileName, L"", L"");
  2073. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2074. TOnceDoneOperation OnceDoneOperation;
  2075. Progress.Finish(FileName, true, OnceDoneOperation);
  2076. }
  2077. }
  2078. __finally
  2079. {
  2080. Progress.Stop();
  2081. }
  2082. }
  2083. }
  2084. //---------------------------------------------------------------------------
  2085. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2086. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2087. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2088. {
  2089. TLocalCustomCommand LocalCustomCommand(Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory());
  2090. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2091. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2092. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2093. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2094. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2095. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2096. std::unique_ptr<UnicodeString> POutput;
  2097. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2098. FLAGSET(ACommand.Params, ccCopyResults))
  2099. {
  2100. POutput.reset(new UnicodeString());
  2101. }
  2102. if (!LocalCustomCommand.IsFileCommand(Command))
  2103. {
  2104. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2105. }
  2106. // remote files?
  2107. else if ((FCurrentSide == osRemote) || LocalFileCommand)
  2108. {
  2109. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2110. }
  2111. // local files
  2112. else
  2113. {
  2114. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2115. }
  2116. if (POutput.get() != NULL)
  2117. {
  2118. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2119. int P = POutput->Pos(sLineBreak);
  2120. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2121. {
  2122. POutput->SetLength(P - 1);
  2123. }
  2124. // Copy even empty output to clipboard
  2125. if (FLAGSET(ACommand.Params, ccCopyResults))
  2126. {
  2127. CopyToClipboard(*POutput);
  2128. }
  2129. // But do not show an empty message box.
  2130. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2131. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2132. !POutput->IsEmpty())
  2133. {
  2134. TClipboardHandler ClipboardHandler;
  2135. ClipboardHandler.Text = *POutput;
  2136. TMessageParams Params;
  2137. TQueryButtonAlias Aliases[1];
  2138. Aliases[0].Button = qaRetry;
  2139. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2140. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2141. Params.Aliases = Aliases;
  2142. Params.AliasesCount = LENOF(Aliases);
  2143. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2144. }
  2145. }
  2146. }
  2147. //---------------------------------------------------------------------------
  2148. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2149. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2150. {
  2151. TCustomCommandData Data(Terminal);
  2152. UnicodeString Site = Terminal->SessionData->SessionKey;
  2153. UnicodeString HelpKeyword = ACommand.HomePage;
  2154. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2155. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2156. {
  2157. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2158. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2159. {
  2160. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, Terminal->CurrentDirectory));
  2161. }
  2162. else
  2163. {
  2164. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory()));
  2165. }
  2166. if (!DoCustomCommandOptionsDialog(
  2167. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2168. {
  2169. Abort();
  2170. }
  2171. }
  2172. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2173. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2174. {
  2175. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2176. }
  2177. else
  2178. {
  2179. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2180. }
  2181. }
  2182. //---------------------------------------------------------------------------
  2183. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2184. const TCustomCommandType & Command)
  2185. {
  2186. DebugAssert(FCustomCommandLocalFileList != NULL);
  2187. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2188. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2189. TStrings * LocalFileList = new TStringList();
  2190. TStrings * RemoteFileList = new TStringList();
  2191. try
  2192. {
  2193. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2194. {
  2195. LocalFileList->Clear();
  2196. LocalFileList->AddObject(
  2197. FCustomCommandLocalFileList->Strings[Index],
  2198. FCustomCommandLocalFileList->Objects[Index]);
  2199. RemoteFileList->Clear();
  2200. RemoteFileList->AddObject(
  2201. FCustomCommandRemoteFileList->Strings[Index],
  2202. FCustomCommandRemoteFileList->Objects[Index]);
  2203. CustomCommand(RemoteFileList, Command, LocalFileList);
  2204. }
  2205. }
  2206. __finally
  2207. {
  2208. delete LocalFileList;
  2209. delete RemoteFileList;
  2210. }
  2211. }
  2212. //---------------------------------------------------------------------------
  2213. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2214. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2215. {
  2216. delete FCustomCommandLocalFileList;
  2217. delete FCustomCommandRemoteFileList;
  2218. // takeover ownership,
  2219. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2220. FCustomCommandLocalFileList = LocalFileList;
  2221. FCustomCommandRemoteFileList = RemoteFileList;
  2222. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2223. if (Button != NULL)
  2224. {
  2225. FCustomCommandMenu->Items->Clear();
  2226. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth);
  2227. MenuPopup(FCustomCommandMenu, Button);
  2228. }
  2229. else
  2230. {
  2231. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2232. }
  2233. }
  2234. //---------------------------------------------------------------------------
  2235. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2236. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2237. {
  2238. DebugAssert(FCapturedLog != NULL);
  2239. if ((OutputType == cotOutput) || (OutputType == cotError))
  2240. {
  2241. FCapturedLog->Add(AddedLine);
  2242. }
  2243. }
  2244. //---------------------------------------------------------------------------
  2245. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2246. TOperationSide Side)
  2247. {
  2248. return (Side == osRemote) &&
  2249. ((Control == RemoteDirView) || (Control == RemoteDriveView));
  2250. }
  2251. //---------------------------------------------------------------------------
  2252. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2253. TOperationSide Side, TTBXCustomItem * Item, TDoubleClickAction DoubleClickAction)
  2254. {
  2255. TTBItemOptions O;
  2256. O = Item->Options;
  2257. TCustomDirView * DView = DirView(Side);
  2258. if ((DView->ItemFocused != NULL) &&
  2259. (WinConfiguration->DoubleClickAction == DoubleClickAction) &&
  2260. // when resolving links is disabled, default action is to enter the directory,
  2261. // no matter what DoubleClickAction is configured to
  2262. ((Side != osRemote) || Terminal->ResolvingSymlinks || Terminal->IsEncryptingFiles()) &&
  2263. // Can only Edit files, but can Open/Copy even directories
  2264. ((DoubleClickAction != dcaEdit) ||
  2265. !DView->ItemIsDirectory(DView->ItemFocused)))
  2266. {
  2267. Item->Options = O << tboDefault;
  2268. }
  2269. else
  2270. {
  2271. Item->Options = O >> tboDefault;
  2272. }
  2273. }
  2274. //---------------------------------------------------------------------------
  2275. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2276. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2277. {
  2278. TCustomDirView * DView = DirView(Side);
  2279. TListItem * Item = DView->ItemFocused;
  2280. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2281. EnableFocusedOperation[Side])
  2282. {
  2283. TPoint ClientPoint;
  2284. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2285. TPoint(0, 0) : MousePos;
  2286. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2287. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2288. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2289. }
  2290. }
  2291. //---------------------------------------------------------------------------
  2292. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2293. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2294. {
  2295. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, dcaOpen);
  2296. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, dcaEdit);
  2297. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, dcaCopy);
  2298. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2299. Handled = true;
  2300. }
  2301. //---------------------------------------------------------------------------
  2302. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2303. {
  2304. }
  2305. //---------------------------------------------------------------------------
  2306. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2307. {
  2308. DebugAssert(FErrorList == NULL);
  2309. if (WinConfiguration->ContinueOnError)
  2310. {
  2311. FErrorList = new TStringList();
  2312. Configuration->Usage->Inc(L"ContinuationsOnError");
  2313. }
  2314. NonVisualDataModule->StartBusy();
  2315. }
  2316. //---------------------------------------------------------------------------
  2317. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2318. {
  2319. NonVisualDataModule->EndBusy();
  2320. if (FErrorList)
  2321. {
  2322. HandleErrorList(FErrorList);
  2323. }
  2324. }
  2325. //---------------------------------------------------------------------------
  2326. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2327. const TCopyParamType & CopyParam)
  2328. {
  2329. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2330. {
  2331. Configuration->Usage->Inc(L"FileMaskUses");
  2332. }
  2333. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2334. {
  2335. Configuration->Usage->Inc(L"OperationMaskUses");
  2336. }
  2337. }
  2338. //---------------------------------------------------------------------------
  2339. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2340. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2341. {
  2342. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2343. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2344. TTransferOperationParam DefaultParam;
  2345. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2346. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2347. switch (Param.Queue)
  2348. {
  2349. case asOn:
  2350. CopyParam.Queue = true;
  2351. break;
  2352. case asOff:
  2353. CopyParam.Queue = false;
  2354. break;
  2355. case asAuto:
  2356. default:
  2357. // keep default
  2358. break;
  2359. }
  2360. bool Result =
  2361. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2362. if (Result)
  2363. {
  2364. DebugAssert(Terminal);
  2365. bool SelectionRestored = false;
  2366. TCustomDirView * DView = NULL;
  2367. if (HasDirView[Side])
  2368. {
  2369. DView = DirView(Side);
  2370. DView->SaveSelection();
  2371. DView->SaveSelectedNames();
  2372. }
  2373. UpdateCopyParamCounters(CopyParam);
  2374. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2375. DebugAssert(FTransferResumeList == NULL);
  2376. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2377. FMoveToQueue = false;
  2378. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2379. try
  2380. {
  2381. TStrings * PermanentFileList;
  2382. std::unique_ptr<TStrings> PermanentFileListOwner;
  2383. try
  2384. {
  2385. if (Side == osLocal)
  2386. {
  2387. PermanentFileList = FileList;
  2388. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2389. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2390. if (Operation == foMove)
  2391. {
  2392. ReloadLocalDirectory();
  2393. if (DView != NULL)
  2394. {
  2395. DView->RestoreSelection();
  2396. }
  2397. SelectionRestored = true;
  2398. }
  2399. }
  2400. else
  2401. {
  2402. // Clone the file list as it may refer to current directory files,
  2403. // which get destroyed, when the source directory is reloaded after foMove operation.
  2404. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2405. // But for a hotfix, we are not going to do such a big change.
  2406. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2407. PermanentFileList = PermanentFileListOwner.get();
  2408. try
  2409. {
  2410. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2411. }
  2412. __finally
  2413. {
  2414. if (Operation == foMove)
  2415. {
  2416. if (DView != NULL)
  2417. {
  2418. DView->RestoreSelection();
  2419. }
  2420. SelectionRestored = true;
  2421. }
  2422. ReloadLocalDirectory(Param.TargetDirectory);
  2423. }
  2424. }
  2425. }
  2426. catch (EAbort &)
  2427. {
  2428. if (FMoveToQueue)
  2429. {
  2430. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2431. DebugAssert(CopyParam.TransferSkipList == NULL);
  2432. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2433. if (TransferResumeList->Count > 0)
  2434. {
  2435. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2436. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2437. }
  2438. CopyParam.TransferSkipList = TransferResumeList.release();
  2439. // not really needed, just to keep it consistent with TransferResumeList
  2440. FTransferResumeList = NULL;
  2441. FMoveToQueue = false;
  2442. Configuration->Usage->Inc("MovesToBackground");
  2443. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2444. ClearTransferSourceSelection(Direction);
  2445. }
  2446. throw;
  2447. }
  2448. }
  2449. __finally
  2450. {
  2451. if (!SelectionRestored && (DView != NULL))
  2452. {
  2453. DView->DiscardSavedSelection();
  2454. }
  2455. FTransferResumeList = NULL;
  2456. }
  2457. }
  2458. return Result;
  2459. }
  2460. //---------------------------------------------------------------------------
  2461. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2462. TOperationSide Side, TStrings * FileList, void * Param)
  2463. {
  2464. DebugAssert(FileList->Count);
  2465. // We deliberately do not toggle alternative flag (Param), but use OR,
  2466. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2467. // shortcut of CurrentDeleteAlternativeAction
  2468. bool Alternative =
  2469. bool(Param) || UseAlternativeFunction();
  2470. bool Recycle;
  2471. if (Side == osLocal)
  2472. {
  2473. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2474. }
  2475. else
  2476. {
  2477. Recycle =
  2478. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2479. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2480. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2481. }
  2482. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2483. if (!Result)
  2484. {
  2485. UnicodeString Query;
  2486. if (FileList->Count == 1)
  2487. {
  2488. if (Side == osLocal)
  2489. {
  2490. Query = ExtractFileName(FileList->Strings[0]);
  2491. }
  2492. else
  2493. {
  2494. Query = UnixExtractFileName(FileList->Strings[0]);
  2495. }
  2496. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2497. }
  2498. else
  2499. {
  2500. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2501. }
  2502. TMessageParams Params(mpNeverAskAgainCheck);
  2503. Params.ImageName = L"Delete file";
  2504. unsigned int Answer =
  2505. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2506. if (Answer == qaNeverAskAgain)
  2507. {
  2508. Result = true;
  2509. if (Recycle)
  2510. {
  2511. WinConfiguration->ConfirmRecycling = false;
  2512. }
  2513. else
  2514. {
  2515. WinConfiguration->ConfirmDeleting = false;
  2516. }
  2517. }
  2518. else
  2519. {
  2520. Result = (Answer == qaOK);
  2521. }
  2522. }
  2523. if (Result)
  2524. {
  2525. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2526. }
  2527. return Result;
  2528. }
  2529. //---------------------------------------------------------------------------
  2530. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2531. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2532. {
  2533. TAutoBatch AutoBatch(this);
  2534. bool Result;
  2535. if ((Operation == foCopy) || (Operation == foMove))
  2536. {
  2537. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2538. }
  2539. else if (Operation == foRename)
  2540. {
  2541. DebugAssert(DirView(Side)->ItemFocused);
  2542. DirView(Side)->ItemFocused->EditCaption();
  2543. Result = true;
  2544. }
  2545. else if (Operation == foDelete)
  2546. {
  2547. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2548. }
  2549. else if (Operation == foSetProperties)
  2550. {
  2551. RemoteDirView->SaveSelectedNames();
  2552. Result = SetProperties(Side, FileList);
  2553. }
  2554. else if (Operation == foCustomCommand)
  2555. {
  2556. DebugAssert(Param);
  2557. DebugAssert(Side == osRemote);
  2558. RemoteDirView->SaveSelectedNames();
  2559. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2560. CustomCommand(FileList, *Command, NULL);
  2561. Result = true;
  2562. }
  2563. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2564. {
  2565. DebugAssert(Side == osRemote);
  2566. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2567. (Operation == foRemoteMove), reinterpret_cast<TTerminal *>(Param));
  2568. }
  2569. else if (Operation == foLock)
  2570. {
  2571. DebugAssert(Side == osRemote);
  2572. LockFiles(FileList, true);
  2573. Result = true;
  2574. }
  2575. else if (Operation == foUnlock)
  2576. {
  2577. DebugAssert(Side == osRemote);
  2578. LockFiles(FileList, false);
  2579. Result = true;
  2580. }
  2581. else
  2582. {
  2583. DebugFail();
  2584. }
  2585. return Result;
  2586. }
  2587. //---------------------------------------------------------------------------
  2588. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2589. {
  2590. if (Side == osCurrent)
  2591. {
  2592. Side = FCurrentSide;
  2593. }
  2594. return Side;
  2595. }
  2596. //---------------------------------------------------------------------------
  2597. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2598. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2599. {
  2600. Side = GetSide(Side);
  2601. bool Result;
  2602. TStrings * FileList = DirView(Side)->CreateFileList(OnFocused, (Side == osLocal), NULL);
  2603. try
  2604. {
  2605. Result = ExecuteFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2606. }
  2607. __finally
  2608. {
  2609. delete FileList;
  2610. }
  2611. return Result;
  2612. }
  2613. //---------------------------------------------------------------------------
  2614. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2615. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2616. bool NoConfirmation, void * Param)
  2617. {
  2618. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2619. {
  2620. if ((Operation == foCopy) || (Operation == foMove))
  2621. {
  2622. if (GetSide(Side) == osLocal)
  2623. {
  2624. Configuration->Usage->Inc(L"UploadsCommand");
  2625. }
  2626. else
  2627. {
  2628. Configuration->Usage->Inc(L"DownloadsCommand");
  2629. }
  2630. }
  2631. }
  2632. }
  2633. //---------------------------------------------------------------------------
  2634. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2635. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2636. {
  2637. TTransferOperationParam Param;
  2638. if ((WinConfiguration->Interface != ifCommander) ||
  2639. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2640. {
  2641. Flags &= ~cocShortCutHint;
  2642. }
  2643. TCustomDirView * DView = DirView(Side);
  2644. Param.Options =
  2645. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2646. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2647. if (FLAGSET(Flags, cocQueue))
  2648. {
  2649. Param.Queue = asOn;
  2650. }
  2651. else if (FLAGSET(Flags, cocNonQueue))
  2652. {
  2653. Param.Queue = asOff;
  2654. }
  2655. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2656. }
  2657. //---------------------------------------------------------------------------
  2658. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2659. {
  2660. try
  2661. {
  2662. if (ErrorList->Count)
  2663. {
  2664. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2665. if (MessageDialog(Message, qtError,
  2666. qaOK | qaCancel, HELP_NONE) == qaOK)
  2667. {
  2668. unsigned int Answer;
  2669. int Index = 0;
  2670. do
  2671. {
  2672. DebugAssert(Index >= 0 && Index < ErrorList->Count);
  2673. TQueryButtonAlias Aliases[2];
  2674. Aliases[0].Button = qaYes;
  2675. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2676. Aliases[1].Button = qaNo;
  2677. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2678. TMessageParams Params;
  2679. Params.Aliases = Aliases;
  2680. Params.AliasesCount = LENOF(Aliases);
  2681. Answer = MoreMessageDialog(
  2682. FMTLOAD(ERROR_LIST_NUMBER, (Index+1, ErrorList->Count, ErrorList->Strings[Index])),
  2683. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2684. (Index ? qaYes : 0) | (Index < ErrorList->Count - 1 ? qaNo : 0) |
  2685. qaOK, HELP_NONE, &Params);
  2686. if (Answer == qaNo)
  2687. {
  2688. Index++;
  2689. }
  2690. if (Answer == qaYes)
  2691. {
  2692. Index--;
  2693. }
  2694. }
  2695. while (Answer != qaOK);
  2696. }
  2697. }
  2698. }
  2699. __finally
  2700. {
  2701. TStrings * List = ErrorList;
  2702. ErrorList = NULL;
  2703. for (int i = 0; i < List->Count; i++)
  2704. {
  2705. delete List->Objects[i];
  2706. }
  2707. delete List;
  2708. }
  2709. }
  2710. //---------------------------------------------------------------------------
  2711. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  2712. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  2713. {
  2714. // needed for checking filemasks, as there's no directory object
  2715. // associated with the file object
  2716. File->FullFileName = FullFileName;
  2717. TFileMasks::TParams MaskParams;
  2718. MaskParams.Size = File->Size;
  2719. MaskParams.Modification = File->Modification;
  2720. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  2721. }
  2722. //---------------------------------------------------------------------------
  2723. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  2724. {
  2725. DebugAssert(!WinConfiguration->DisableOpenEdit);
  2726. Side = GetSide(Side);
  2727. TCustomDirView * DView = DirView(Side);
  2728. TListItem * FocusedItem = DView->ItemFocused;
  2729. UnicodeString Name;
  2730. if ((FocusedItem != NULL) && !DView->ItemIsParentDirectory(FocusedItem))
  2731. {
  2732. Name = DView->ItemFileName(FocusedItem);
  2733. }
  2734. else
  2735. {
  2736. Name = LoadStr(NEW_FILE);
  2737. }
  2738. UnicodeString Names = Name;
  2739. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  2740. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  2741. HELP_EDIT_NEW, History.get(), true))
  2742. {
  2743. while (!Names.IsEmpty())
  2744. {
  2745. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  2746. CustomWinConfiguration->History[L"EditFile"] = History.get();
  2747. UnicodeString TargetFileName;
  2748. UnicodeString LocalFileName;
  2749. UnicodeString RootTempDir;
  2750. UnicodeString TempDir;
  2751. UnicodeString RemoteDirectory;
  2752. bool ExistingFile = false;
  2753. if (Side == osRemote)
  2754. {
  2755. Name = AbsolutePath(FTerminal->CurrentDirectory, Name);
  2756. TRemoteFile * File = NULL;
  2757. if (FTerminal->FileExists(Name, &File))
  2758. {
  2759. try
  2760. {
  2761. ExecuteRemoteFile(Name, File, efDefaultEditor);
  2762. ExistingFile = true;
  2763. }
  2764. __finally
  2765. {
  2766. delete File;
  2767. }
  2768. }
  2769. if (!ExistingFile)
  2770. {
  2771. RemoteDirectory = UnixExtractFilePath(Name);
  2772. TemporaryDirectoryForRemoteFiles(
  2773. RemoteDirectory, GUIConfiguration->CurrentCopyParam, TempDir, RootTempDir);
  2774. TargetFileName = UnixExtractFileName(Name);
  2775. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2776. LocalFileName = TempDir +
  2777. // We probably do not want to trim the VMS version here
  2778. FTerminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  2779. }
  2780. }
  2781. else
  2782. {
  2783. if (ExtractFilePath(Name).IsEmpty())
  2784. {
  2785. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  2786. }
  2787. else
  2788. {
  2789. LocalFileName = ExpandFileName(Name);
  2790. }
  2791. TargetFileName = ExtractFileName(Name);
  2792. }
  2793. if (!ExistingFile)
  2794. {
  2795. if (!FileExists(ApiPath(LocalFileName)))
  2796. {
  2797. int File = FileCreate(ApiPath(LocalFileName));
  2798. if (File < 0)
  2799. {
  2800. if (!RootTempDir.IsEmpty())
  2801. {
  2802. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  2803. }
  2804. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  2805. }
  2806. else
  2807. {
  2808. FileClose(File);
  2809. }
  2810. }
  2811. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  2812. const TEditorData * ExternalEditor = NULL;
  2813. TFileMasks::TParams MaskParams; // size not known
  2814. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  2815. false, MaskParams);
  2816. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  2817. ExternalEditor, RootTempDir, RemoteDirectory);
  2818. }
  2819. }
  2820. }
  2821. }
  2822. //---------------------------------------------------------------------------
  2823. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  2824. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  2825. {
  2826. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  2827. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  2828. DebugAssert(ExecuteFileBy != efDefaultEditor);
  2829. return
  2830. ((ExecuteFileBy == efInternalEditor)) ||
  2831. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  2832. }
  2833. //---------------------------------------------------------------------------
  2834. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  2835. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  2836. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  2837. UnicodeString RemoteDirectory)
  2838. {
  2839. DebugAssert(!WinConfiguration->DisableOpenEdit);
  2840. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  2841. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  2842. DebugAssert(ExecuteFileBy != efDefaultEditor);
  2843. Side = GetSide(Side);
  2844. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  2845. if (Side == osRemote)
  2846. {
  2847. Data->Terminal = Terminal;
  2848. Data->Queue = Queue;
  2849. Data->SessionData = CloneCurrentSessionData();
  2850. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  2851. Data->RemoteDirectory = RemoteDirectory;
  2852. Data->SessionName = Terminal->SessionData->SessionName;
  2853. Data->LocalRootDirectory = LocalRootDirectory;
  2854. Data->OriginalFileName = OriginalFileName;
  2855. Data->Command = L""; // will be changed later for external editor
  2856. }
  2857. if (ExecuteFileBy == efInternalEditor)
  2858. {
  2859. if (Side == osRemote)
  2860. {
  2861. UnicodeString Caption = UnixIncludeTrailingBackslash(RemoteDirectory) + OriginalFileName +
  2862. L" - " + Terminal->SessionData->SessionName;
  2863. TForm * Editor;
  2864. try
  2865. {
  2866. TNotifyEvent OnFileChanged = NULL;
  2867. TNotifyEvent OnSaveAll = NULL;
  2868. TAnyModifiedEvent OnAnyModified = NULL;
  2869. // Edited files are uploaded in background queue, what we do not support with encrypted files
  2870. if (Terminal->IsCapable[fsBackgroundTransfers])
  2871. {
  2872. OnFileChanged = FEditorManager->FileChanged;
  2873. OnSaveAll = SaveAllInternalEditors;
  2874. OnAnyModified = AnyInternalEditorModified;
  2875. }
  2876. Editor = ShowEditorForm(FileName, this, OnFileChanged,
  2877. FEditorManager->FileReload, FEditorManager->FileClosed,
  2878. OnSaveAll, OnAnyModified,
  2879. Caption, FStandaloneEditing, SessionColor, Terminal->SessionData->InternalEditorEncoding);
  2880. }
  2881. catch(...)
  2882. {
  2883. if (!LocalRootDirectory.IsEmpty())
  2884. {
  2885. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory), false);
  2886. }
  2887. throw;
  2888. }
  2889. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  2890. }
  2891. else
  2892. {
  2893. DebugAssert(!FStandaloneEditing);
  2894. TForm * Editor =
  2895. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  2896. SaveAllInternalEditors, AnyInternalEditorModified,
  2897. L"", false, SessionColor, -1);
  2898. FLocalEditors->Add(Editor);
  2899. }
  2900. }
  2901. else
  2902. {
  2903. HANDLE Process;
  2904. if (ExecuteFileBy == efExternalEditor)
  2905. {
  2906. UnicodeString Program, Params, Dir;
  2907. Data->Command = ExternalEditor->ExternalEditor;
  2908. ReformatFileNameCommand(Data->Command);
  2909. SplitCommand(Data->Command, Program, Params, Dir);
  2910. Params = ExpandFileNameCommand(Params, FileName);
  2911. Program = ExpandEnvironmentVariables(Program);
  2912. if (!ExecuteShell(Program, Params, Process))
  2913. {
  2914. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  2915. }
  2916. }
  2917. else
  2918. {
  2919. DebugAssert(Side == osRemote);
  2920. if (!ExecuteShell(FileName, L"", Process))
  2921. {
  2922. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  2923. }
  2924. }
  2925. if ((Side == osLocal) ||
  2926. ((ExecuteFileBy == efShell) &&
  2927. !WinConfiguration->Editor.SDIShellEditor) ||
  2928. ((ExecuteFileBy == efExternalEditor) &&
  2929. !ExternalEditor->SDIExternalEditor))
  2930. {
  2931. // no need for handle
  2932. if (Process != NULL)
  2933. {
  2934. DebugCheck(CloseHandle(Process));
  2935. }
  2936. Process = INVALID_HANDLE_VALUE;
  2937. }
  2938. else
  2939. {
  2940. if (Process == NULL)
  2941. {
  2942. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  2943. }
  2944. }
  2945. if (Side == osRemote)
  2946. {
  2947. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  2948. }
  2949. }
  2950. }
  2951. //---------------------------------------------------------------------------
  2952. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  2953. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  2954. void * /*Arg*/)
  2955. {
  2956. if (Token != NULL)
  2957. {
  2958. EditorFormFileSave(static_cast<TForm *>(Token));
  2959. }
  2960. }
  2961. //---------------------------------------------------------------------------
  2962. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  2963. {
  2964. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  2965. {
  2966. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  2967. }
  2968. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  2969. }
  2970. //---------------------------------------------------------------------------
  2971. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  2972. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  2973. void * Arg)
  2974. {
  2975. if ((Token != NULL) &&
  2976. IsEditorFormModified(static_cast<TForm *>(Token)))
  2977. {
  2978. *static_cast<bool *>(Arg) = true;
  2979. }
  2980. }
  2981. //---------------------------------------------------------------------------
  2982. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  2983. TObject * /*Sender*/, bool & Modified)
  2984. {
  2985. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  2986. {
  2987. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  2988. {
  2989. Modified = true;
  2990. }
  2991. }
  2992. if (!Modified)
  2993. {
  2994. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  2995. }
  2996. }
  2997. //---------------------------------------------------------------------------
  2998. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  2999. {
  3000. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3001. }
  3002. //---------------------------------------------------------------------------
  3003. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3004. UnicodeString RemoteDirectory, TCopyParamType CopyParam,
  3005. UnicodeString & Result, UnicodeString & RootDirectory)
  3006. {
  3007. if (!WinConfiguration->TemporaryDirectoryDeterministic)
  3008. {
  3009. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3010. Result = RootDirectory;
  3011. }
  3012. else
  3013. {
  3014. RootDirectory = L"";
  3015. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3016. Result = IncludeTrailingBackslash(Result);
  3017. }
  3018. if (WinConfiguration->TemporaryDirectoryAppendSession)
  3019. {
  3020. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3021. }
  3022. if (WinConfiguration->TemporaryDirectoryAppendPath)
  3023. {
  3024. if (!RemoteDirectory.IsEmpty() && (RemoteDirectory[1] == L'/'))
  3025. {
  3026. RemoteDirectory.Delete(1, 1);
  3027. }
  3028. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(RemoteDirectory)));
  3029. }
  3030. if (!ForceDirectories(ApiPath(Result)))
  3031. {
  3032. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3033. }
  3034. }
  3035. //---------------------------------------------------------------------------
  3036. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3037. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3038. bool AllFiles, bool GetTargetNames, bool AutoOperation)
  3039. {
  3040. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3041. if (ForceText)
  3042. {
  3043. CopyParam.TransferMode = tmAscii;
  3044. }
  3045. TemporaryFileCopyParam(CopyParam);
  3046. if (AllFiles)
  3047. {
  3048. CopyParam.IncludeFileMask = TFileMasks();
  3049. }
  3050. if (TempDir.IsEmpty())
  3051. {
  3052. TemporaryDirectoryForRemoteFiles(FTerminal->CurrentDirectory, CopyParam, TempDir, RootTempDir);
  3053. }
  3054. DebugAssert(!FAutoOperation);
  3055. FAutoOperation = AutoOperation;
  3056. Terminal->ExceptionOnFail = true;
  3057. try
  3058. {
  3059. try
  3060. {
  3061. // turn off confirmations, as for MDI editors we may possibly download
  3062. // the same file over
  3063. Terminal->CopyToLocal(
  3064. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3065. if (GetTargetNames)
  3066. {
  3067. for (int i = 0; i < FileList->Count; i++)
  3068. {
  3069. FileList->Strings[i] =
  3070. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3071. }
  3072. }
  3073. }
  3074. catch(...)
  3075. {
  3076. if (!RootTempDir.IsEmpty())
  3077. {
  3078. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3079. }
  3080. throw;
  3081. }
  3082. }
  3083. __finally
  3084. {
  3085. FAutoOperation = false;
  3086. Terminal->ExceptionOnFail = false;
  3087. }
  3088. }
  3089. //---------------------------------------------------------------------------
  3090. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3091. {
  3092. // Do not waste time checking for default editor list the next time,
  3093. // or testing if default editor is not notepad.
  3094. bool TryNextTime = false;
  3095. UnicodeString UsageState;
  3096. if (!WinConfiguration->EditorList->IsDefaultList())
  3097. {
  3098. UsageState = "H";
  3099. }
  3100. else
  3101. {
  3102. UnicodeString Executable;
  3103. UnicodeString ExecutableDescription;
  3104. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3105. {
  3106. UnicodeString Message =
  3107. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3108. unsigned int Answer =
  3109. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3110. if (Answer != qaOK)
  3111. {
  3112. UsageState = "R";
  3113. }
  3114. else
  3115. {
  3116. UsageState = "A";
  3117. TEditorData EditorData;
  3118. EditorData.Editor = edExternal;
  3119. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3120. EditorData.DecideExternalEditorText();
  3121. TEditorList EditorList;
  3122. EditorList = *WinConfiguration->EditorList;
  3123. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3124. WinConfiguration->EditorList = &EditorList;
  3125. }
  3126. }
  3127. }
  3128. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3129. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3130. }
  3131. //---------------------------------------------------------------------------
  3132. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3133. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3134. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3135. {
  3136. if (ExecuteFileBy == efDefaultEditor)
  3137. {
  3138. if (!WinConfiguration->OfferedEditorAutoConfig)
  3139. {
  3140. EditorAutoConfig();
  3141. }
  3142. const TEditorPreferences * Editor =
  3143. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3144. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3145. {
  3146. ExecuteFileBy = efInternalEditor;
  3147. ExternalEditor = NULL;
  3148. }
  3149. else if (Editor->Data->Editor == edOpen)
  3150. {
  3151. ExecuteFileBy = efShell;
  3152. ExternalEditor = NULL;
  3153. }
  3154. else
  3155. {
  3156. ExecuteFileBy = efExternalEditor;
  3157. ExternalEditor = Editor->Data;
  3158. }
  3159. }
  3160. }
  3161. //---------------------------------------------------------------------------
  3162. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3163. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3164. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3165. {
  3166. UnicodeString OriginalFileName;
  3167. UnicodeString LocalRootDirectory;
  3168. UnicodeString RemoteDirectory;
  3169. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3170. (Side == osLocal), MaskParams);
  3171. UnicodeString Counter;
  3172. UnicodeString LocalFileName;
  3173. bool Handled = false;
  3174. if (Side == osRemote)
  3175. {
  3176. // We need to trim VMS version here, so that we use name without version
  3177. // when uploading back to create a new version of the file
  3178. OriginalFileName = FTerminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3179. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3180. TObject * Token = NULL;
  3181. UnicodeString LocalDirectory;
  3182. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3183. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3184. LocalDirectory))
  3185. {
  3186. if (Token != NULL)
  3187. {
  3188. TForm * Form = dynamic_cast<TForm *>(Token);
  3189. if (Form->WindowState == wsMinimized)
  3190. {
  3191. ShowWindow(Form->Handle, SW_RESTORE);
  3192. }
  3193. else
  3194. {
  3195. Form->SetFocus();
  3196. }
  3197. Handled = true;
  3198. }
  3199. else
  3200. {
  3201. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3202. }
  3203. }
  3204. if (!Handled)
  3205. {
  3206. TStringList * FileList1 = new TStringList();
  3207. try
  3208. {
  3209. FileList1->AddObject(FullFileName, Object);
  3210. TemporarilyDownloadFiles(FileList1,
  3211. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3212. LocalRootDirectory, LocalDirectory, true, true, true);
  3213. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3214. }
  3215. __finally
  3216. {
  3217. delete FileList1;
  3218. }
  3219. switch (ExecuteFileBy)
  3220. {
  3221. case efShell:
  3222. Counter = "RemoteFilesExecuted";
  3223. break;
  3224. case efInternalEditor:
  3225. Counter = "RemoteFilesOpenedInInternalEditor";
  3226. break;
  3227. case efExternalEditor:
  3228. Counter = "RemoteFilesOpenedInExternalEditor";
  3229. break;
  3230. default:
  3231. DebugFail();
  3232. }
  3233. }
  3234. }
  3235. else
  3236. {
  3237. LocalFileName = FullFileName;
  3238. OriginalFileName = ExtractFileName(FullFileName);
  3239. switch (ExecuteFileBy)
  3240. {
  3241. case efShell:
  3242. Counter = "LocalFilesExecuted";
  3243. break;
  3244. case efInternalEditor:
  3245. Counter = "LocalFilesOpenedInInternalEditor";
  3246. break;
  3247. case efExternalEditor:
  3248. Counter = "LocalFilesOpenedInExternalEditor";
  3249. break;
  3250. default:
  3251. DebugFail();
  3252. }
  3253. }
  3254. if (!Handled)
  3255. {
  3256. Configuration->Usage->Inc(Counter);
  3257. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3258. ExternalEditor, LocalRootDirectory, RemoteDirectory);
  3259. }
  3260. }
  3261. //---------------------------------------------------------------------------
  3262. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3263. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3264. bool AllSelected, bool OnFocused)
  3265. {
  3266. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3267. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3268. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3269. Side = GetSide(Side);
  3270. TCustomDirView * DView = DirView(Side);
  3271. TStrings * FileList = AllSelected ?
  3272. DView->CreateFileList(OnFocused, Side == osLocal) :
  3273. DView->CreateFocusedFileList(Side == osLocal);
  3274. try
  3275. {
  3276. DebugAssert(AllSelected || (FileList->Count == 1));
  3277. for (int i = 0; i < FileList->Count; i++)
  3278. {
  3279. UnicodeString ListFileName = FileList->Strings[i];
  3280. UnicodeString FileNameOnly = (Side == osRemote) ?
  3281. UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3282. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3283. if (!DView->ItemIsDirectory(Item))
  3284. {
  3285. UnicodeString FullFileName;
  3286. if (Side == osRemote)
  3287. {
  3288. FullFileName = RemoteDirView->Path + ListFileName;
  3289. }
  3290. else
  3291. {
  3292. FullFileName = ListFileName;
  3293. }
  3294. TFileMasks::TParams MaskParams;
  3295. MaskParams.Size = DView->ItemFileSize(Item);
  3296. TDateTimePrecision Precision;
  3297. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3298. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName,
  3299. FileList->Objects[i], MaskParams);
  3300. }
  3301. }
  3302. }
  3303. __finally
  3304. {
  3305. delete FileList;
  3306. }
  3307. }
  3308. //---------------------------------------------------------------------------
  3309. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3310. {
  3311. // do not forget to add additional options to TemporarilyDownloadFiles, and AS
  3312. CopyParam.FileNameCase = ncNoChange;
  3313. CopyParam.PreserveRights = false;
  3314. CopyParam.PreserveReadOnly = false;
  3315. CopyParam.ReplaceInvalidChars = true;
  3316. CopyParam.IncludeFileMask = TFileMasks();
  3317. CopyParam.NewerOnly = false;
  3318. CopyParam.FileMask = L"";
  3319. }
  3320. //---------------------------------------------------------------------------
  3321. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(const UnicodeString FileName,
  3322. TEditedFileData * Data, HANDLE UploadCompleteEvent)
  3323. {
  3324. TTerminalManager * Manager = TTerminalManager::Instance();
  3325. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3326. {
  3327. if (!NonVisualDataModule->Busy)
  3328. {
  3329. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3330. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3331. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3332. if (Data->Terminal == NULL)
  3333. {
  3334. TTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3335. if (SameSiteTerminal != NULL)
  3336. {
  3337. UnicodeString Message =
  3338. FMTLOAD(EDIT_SESSION_REATTACH,
  3339. (FileNameOnly, Data->SessionName, FileNameOnly));
  3340. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3341. {
  3342. Data->Terminal = Terminal;
  3343. Data->Queue = Manager->FindQueueForTerminal(Terminal);
  3344. Data->SessionName = Terminal->SessionData->SessionName;
  3345. // We might also overwrite session data
  3346. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3347. }
  3348. else
  3349. {
  3350. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3351. Abort();
  3352. }
  3353. }
  3354. }
  3355. // foreground session should reconnect itself
  3356. else if (Terminal != Data->Terminal)
  3357. {
  3358. UnicodeString Message =
  3359. MainInstructions(
  3360. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3361. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3362. {
  3363. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3364. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3365. }
  3366. else
  3367. {
  3368. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3369. Abort();
  3370. }
  3371. }
  3372. }
  3373. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3374. {
  3375. Configuration->Usage->Inc(L"EditInactiveSession");
  3376. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3377. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3378. (ExtractFileName(FileName), Data->SessionName)));
  3379. }
  3380. }
  3381. TStrings * FileList = new TStringList();
  3382. try
  3383. {
  3384. FileList->Add(FileName);
  3385. // consider using the same settings (preset) as when the file was downloaded
  3386. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3387. TemporaryFileCopyParam(CopyParam);
  3388. if (Data->ForceText)
  3389. {
  3390. CopyParam.TransferMode = tmAscii;
  3391. }
  3392. // so i do not need to worry if masking algorithm works in all cases
  3393. // ("" means "copy file name", no masking is actually done)
  3394. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3395. {
  3396. CopyParam.FileMask = L"";
  3397. }
  3398. else
  3399. {
  3400. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3401. }
  3402. DebugAssert(Data->Queue != NULL);
  3403. int Params = cpNoConfirmation | cpTemporary;
  3404. TQueueItem * QueueItem = new TUploadQueueItem(Data->Terminal, FileList,
  3405. Data->RemoteDirectory, &CopyParam, Params, true, false);
  3406. QueueItem->CompleteEvent = UploadCompleteEvent;
  3407. AddQueueItem(Data->Queue, QueueItem, Data->Terminal);
  3408. }
  3409. __finally
  3410. {
  3411. delete FileList;
  3412. }
  3413. }
  3414. //---------------------------------------------------------------------------
  3415. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3416. const UnicodeString FileName, const TEditedFileData * Data)
  3417. {
  3418. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3419. DebugAssert(!NonVisualDataModule->Busy);
  3420. if ((Data->Terminal == NULL) || !Data->Terminal->Active)
  3421. {
  3422. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3423. (ExtractFileName(FileName), Data->SessionName)));
  3424. }
  3425. TTerminal * PrevTerminal = TTerminalManager::Instance()->ActiveTerminal;
  3426. TTerminalManager::Instance()->ActiveTerminal = Data->Terminal;
  3427. NonVisualDataModule->StartBusy();
  3428. try
  3429. {
  3430. std::unique_ptr<TRemoteFile> File;
  3431. UnicodeString RemoteFileName =
  3432. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3433. FTerminal->ExceptionOnFail = true;
  3434. try
  3435. {
  3436. TRemoteFile * AFile = NULL;
  3437. FTerminal->ReadFile(RemoteFileName, AFile);
  3438. File.reset(AFile);
  3439. if (!File->HaveFullFileName)
  3440. {
  3441. File->FullFileName = RemoteFileName;
  3442. }
  3443. }
  3444. __finally
  3445. {
  3446. FTerminal->ExceptionOnFail = false;
  3447. }
  3448. std::unique_ptr<TStrings> FileList(new TStringList());
  3449. FileList->AddObject(RemoteFileName, File.get());
  3450. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3451. UnicodeString TempDir = ExtractFilePath(FileName);
  3452. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir,
  3453. TempDir, true, true, true);
  3454. // sanity check, the target file name should be still the same
  3455. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3456. }
  3457. __finally
  3458. {
  3459. NonVisualDataModule->EndBusy();
  3460. // it actually may not exist anymore...
  3461. TTerminalManager::Instance()->ActiveTerminal = PrevTerminal;
  3462. }
  3463. }
  3464. //---------------------------------------------------------------------------
  3465. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3466. const TEditedFileData * Data, bool & KeepOpen)
  3467. {
  3468. // Command is set for external editors only (not for "shell" open).
  3469. if (!Data->Command.IsEmpty())
  3470. {
  3471. bool AnyFound = false;
  3472. bool AnyMDI = false;
  3473. bool AnyNonMDI = false;
  3474. bool AnyDetect = false;
  3475. TEditorList * EditorList = new TEditorList();
  3476. try
  3477. {
  3478. *EditorList = *WinConfiguration->EditorList;
  3479. for (int i = 0; i < EditorList->Count; i++)
  3480. {
  3481. const TEditorPreferences * Editor = EditorList->Editors[i];
  3482. if ((Editor->Data->Editor == edExternal) &&
  3483. (Editor->Data->ExternalEditor == Data->Command))
  3484. {
  3485. AnyFound = true;
  3486. if (Editor->Data->SDIExternalEditor)
  3487. {
  3488. AnyNonMDI = true;
  3489. if (Editor->Data->DetectMDIExternalEditor)
  3490. {
  3491. AnyDetect = true;
  3492. }
  3493. }
  3494. else
  3495. {
  3496. AnyMDI = true;
  3497. }
  3498. }
  3499. }
  3500. bool EnableMDI = false;
  3501. bool DisableDetect = false;
  3502. if (AnyMDI)
  3503. {
  3504. KeepOpen = true;
  3505. if (AnyNonMDI)
  3506. {
  3507. // there is at least one instance of the editor with MDI support enabled,
  3508. // and one with disabled, enable it for all instances
  3509. EnableMDI = true;
  3510. }
  3511. }
  3512. else if (AnyFound && !AnyDetect)
  3513. {
  3514. // at least once instance found but all have MDI autodetection disabled
  3515. // => close the file (default action)
  3516. }
  3517. else
  3518. {
  3519. // no instance of the editor has MDI support enabled
  3520. TMessageParams Params;
  3521. if (AnyFound)
  3522. {
  3523. // there is at least one instance of the editor
  3524. Params.Params |= mpNeverAskAgainCheck;
  3525. }
  3526. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3527. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3528. switch (Answer)
  3529. {
  3530. case qaNeverAskAgain:
  3531. DisableDetect = true;
  3532. break;
  3533. case qaNo:
  3534. EnableMDI = true;
  3535. KeepOpen = true;
  3536. break;
  3537. }
  3538. }
  3539. if (AnyFound && (EnableMDI || DisableDetect))
  3540. {
  3541. bool Changed = false;
  3542. for (int i = 0; i < EditorList->Count; i++)
  3543. {
  3544. const TEditorPreferences * Editor = EditorList->Editors[i];
  3545. if ((Editor->Data->Editor == edExternal) &&
  3546. (Editor->Data->ExternalEditor == Data->Command) &&
  3547. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3548. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3549. {
  3550. Changed = true;
  3551. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3552. if (EnableMDI)
  3553. {
  3554. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3555. }
  3556. if (DisableDetect)
  3557. {
  3558. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3559. }
  3560. EditorList->Change(i, UpdatedEditor);
  3561. }
  3562. }
  3563. if (Changed)
  3564. {
  3565. WinConfiguration->EditorList = EditorList;
  3566. }
  3567. }
  3568. }
  3569. __finally
  3570. {
  3571. delete EditorList;
  3572. }
  3573. }
  3574. else
  3575. {
  3576. // "open" case
  3577. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  3578. qaOK, HELP_APP_EARLY_CLOSED);
  3579. }
  3580. }
  3581. //---------------------------------------------------------------------------
  3582. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  3583. {
  3584. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  3585. }
  3586. //---------------------------------------------------------------------------
  3587. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  3588. {
  3589. SideEnter(osRemote);
  3590. }
  3591. //---------------------------------------------------------------------------
  3592. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  3593. {
  3594. MakeNextInTabOrder(RemoteDirView, RemoteDriveView);
  3595. SideEnter(osRemote);
  3596. }
  3597. //---------------------------------------------------------------------------
  3598. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  3599. {
  3600. FCurrentSide = Side;
  3601. if (Visible)
  3602. {
  3603. UpdateControls();
  3604. }
  3605. }
  3606. //---------------------------------------------------------------------------
  3607. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  3608. TStrings * FileList, bool Alternative)
  3609. {
  3610. TCustomDirView * DView = DirView(Side);
  3611. DView->SaveSelection();
  3612. DView->SaveSelectedNames();
  3613. DebugAssert(!FAlternativeDelete);
  3614. FAlternativeDelete = Alternative;
  3615. try
  3616. {
  3617. if (Side == osRemote)
  3618. {
  3619. DebugAssert(Terminal != NULL);
  3620. Terminal->DeleteFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  3621. }
  3622. else
  3623. {
  3624. try
  3625. {
  3626. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  3627. }
  3628. __finally
  3629. {
  3630. ReloadLocalDirectory();
  3631. }
  3632. }
  3633. FAlternativeDelete = false;
  3634. }
  3635. catch(...)
  3636. {
  3637. FAlternativeDelete = false;
  3638. DView->DiscardSavedSelection();
  3639. throw;
  3640. }
  3641. DView->RestoreSelection();
  3642. }
  3643. //---------------------------------------------------------------------------
  3644. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  3645. {
  3646. DebugAssert(Terminal);
  3647. RemoteDirView->SaveSelection();
  3648. RemoteDirView->SaveSelectedNames();
  3649. try
  3650. {
  3651. if (Lock)
  3652. {
  3653. Terminal->LockFiles(FileList);
  3654. }
  3655. else
  3656. {
  3657. Terminal->UnlockFiles(FileList);
  3658. }
  3659. }
  3660. catch(...)
  3661. {
  3662. RemoteDirView->DiscardSavedSelection();
  3663. throw;
  3664. }
  3665. RemoteDirView->RestoreSelection();
  3666. }
  3667. //---------------------------------------------------------------------------
  3668. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TTerminal *& Session,
  3669. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  3670. bool NoConfirmation, bool Move)
  3671. {
  3672. DebugAssert(Terminal != NULL);
  3673. // update Terminal->StateData->RemoteDirectory
  3674. UpdateTerminal(Terminal);
  3675. if (Session == NULL)
  3676. {
  3677. Session = TTerminalManager::Instance()->ActiveTerminal;
  3678. }
  3679. if (Session == TTerminalManager::Instance()->ActiveTerminal)
  3680. {
  3681. if (RemoteDriveView->DropTarget != NULL)
  3682. {
  3683. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  3684. }
  3685. else if (RemoteDirView->DropTarget != NULL)
  3686. {
  3687. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  3688. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  3689. }
  3690. else
  3691. {
  3692. Target = RemoteDirView->Path;
  3693. }
  3694. }
  3695. else
  3696. {
  3697. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(Session));
  3698. Target = ManagedTerminal->StateData->RemoteDirectory;
  3699. }
  3700. Target = UnixIncludeTrailingBackslash(Target);
  3701. if (FileList->Count == 1)
  3702. {
  3703. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  3704. }
  3705. else
  3706. {
  3707. FileMask = AnyMask;
  3708. }
  3709. DirectCopy = FTerminal->IsCapable[fcRemoteCopy] || FTerminal->IsCapable[fcSecondaryShell];
  3710. bool Result = true;
  3711. if (!NoConfirmation)
  3712. {
  3713. bool Multi = (FileList->Count > 1);
  3714. if (Move)
  3715. {
  3716. Result = DoRemoteMoveDialog(Multi, Target, FileMask);
  3717. }
  3718. else
  3719. {
  3720. TStrings * Sessions = TTerminalManager::Instance()->TerminalList;
  3721. TStrings * Directories = new TStringList;
  3722. try
  3723. {
  3724. for (int Index = 0; Index < Sessions->Count; Index++)
  3725. {
  3726. TManagedTerminal * Terminal =
  3727. dynamic_cast<TManagedTerminal *>(Sessions->Objects[Index]);
  3728. Directories->Add(Terminal->StateData->RemoteDirectory);
  3729. }
  3730. TDirectRemoteCopy AllowDirectCopy;
  3731. if (FTerminal->IsCapable[fcRemoteCopy] || FTerminal->CommandSessionOpened)
  3732. {
  3733. DebugAssert(DirectCopy);
  3734. AllowDirectCopy = drcAllow;
  3735. }
  3736. else if (FTerminal->IsCapable[fcSecondaryShell])
  3737. {
  3738. DebugAssert(DirectCopy);
  3739. AllowDirectCopy = drcConfirmCommandSession;
  3740. }
  3741. else
  3742. {
  3743. DebugAssert(!DirectCopy);
  3744. AllowDirectCopy = drcDisallow;
  3745. }
  3746. void * ASession = Session;
  3747. Result = DoRemoteCopyDialog(Sessions, Directories, AllowDirectCopy,
  3748. Multi, ASession, Target, FileMask, DirectCopy, TTerminalManager::Instance()->ActiveTerminal);
  3749. Session = static_cast<TTerminal *>(ASession);
  3750. }
  3751. __finally
  3752. {
  3753. delete Directories;
  3754. }
  3755. }
  3756. }
  3757. return Result;
  3758. }
  3759. //---------------------------------------------------------------------------
  3760. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  3761. TStrings * FileList, bool NoConfirmation, bool Move, TTerminal * Session)
  3762. {
  3763. bool DirectCopy;
  3764. UnicodeString Target, FileMask;
  3765. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  3766. if (Result)
  3767. {
  3768. if (!Move && !DirectCopy)
  3769. {
  3770. Configuration->Usage->Inc("RemoteCopyTemp");
  3771. UnicodeString RootTempDir;
  3772. UnicodeString TempDir;
  3773. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, false);
  3774. TStrings * TemporaryFilesList = new TStringList();
  3775. try
  3776. {
  3777. TMakeLocalFileListParams MakeFileListParam;
  3778. MakeFileListParam.FileList = TemporaryFilesList;
  3779. MakeFileListParam.FileTimes = NULL;
  3780. MakeFileListParam.IncludeDirs = true;
  3781. MakeFileListParam.Recursive = false;
  3782. ProcessLocalDirectory(TempDir, FTerminal->MakeLocalFileList, &MakeFileListParam);
  3783. TTerminalManager::Instance()->ActiveTerminal = Session;
  3784. if (TemporaryFilesList->Count > 0)
  3785. {
  3786. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3787. CopyParam.FileMask = FileMask;
  3788. DebugAssert(!FAutoOperation);
  3789. FAutoOperation = true;
  3790. FTerminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  3791. }
  3792. }
  3793. __finally
  3794. {
  3795. delete TemporaryFilesList;
  3796. FAutoOperation = false;
  3797. if (!RootTempDir.IsEmpty())
  3798. {
  3799. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir), false);
  3800. }
  3801. }
  3802. }
  3803. else
  3804. {
  3805. RemoteDirView->SaveSelection();
  3806. RemoteDirView->SaveSelectedNames();
  3807. try
  3808. {
  3809. if (Move)
  3810. {
  3811. Configuration->Usage->Inc("RemoteMove");
  3812. Terminal->MoveFiles(FileList, Target, FileMask);
  3813. }
  3814. else
  3815. {
  3816. Configuration->Usage->Inc("RemoteCopyDirect");
  3817. DebugAssert(DirectCopy);
  3818. DebugAssert(Session == FTerminal);
  3819. if (FTerminal->IsCapable[fcRemoteCopy] ||
  3820. FTerminal->CommandSessionOpened ||
  3821. CommandSessionFallback())
  3822. {
  3823. Terminal->CopyFiles(FileList, Target, FileMask);
  3824. }
  3825. }
  3826. }
  3827. catch(...)
  3828. {
  3829. RemoteDirView->DiscardSavedSelection();
  3830. throw;
  3831. }
  3832. RemoteDirView->RestoreSelection();
  3833. }
  3834. }
  3835. return Result;
  3836. }
  3837. //---------------------------------------------------------------------------
  3838. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  3839. const UnicodeString & Path, TRemoteProperties & Properties)
  3840. {
  3841. Properties.Valid = Properties.Valid << vpEncrypt;
  3842. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  3843. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  3844. }
  3845. //---------------------------------------------------------------------------
  3846. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  3847. {
  3848. Side = GetSide(Side);
  3849. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  3850. TRemoteProperties * AProperties = (Side == osRemote ? &Properties : NULL);
  3851. UnicodeString Name = LoadStr(NEW_FOLDER);
  3852. int AllowedChanges =
  3853. FLAGMASK((Side == osRemote) && Terminal->IsCapable[fcModeChanging], cpMode);
  3854. bool SaveSettings = false;
  3855. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  3856. {
  3857. TWindowLock Lock(this);
  3858. if (Side == osRemote)
  3859. {
  3860. if (SaveSettings)
  3861. {
  3862. GUIConfiguration->NewDirectoryProperties = Properties;
  3863. }
  3864. CreateRemoteDirectory(Name, Properties);
  3865. }
  3866. else
  3867. {
  3868. DirView(Side)->CreateDirectory(Name);
  3869. }
  3870. }
  3871. }
  3872. //---------------------------------------------------------------------------
  3873. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  3874. {
  3875. TWindowLock Lock(this);
  3876. DirView(Side)->ExecuteHomeDirectory();
  3877. }
  3878. //---------------------------------------------------------------------------
  3879. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  3880. {
  3881. DoOpenDirectoryDialog(odBrowse, Side);
  3882. }
  3883. //---------------------------------------------------------------------------
  3884. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  3885. {
  3886. UnicodeString Path = Bookmark->GetSideDirectory(Side);
  3887. bool Result = !Path.IsEmpty();
  3888. if (Result)
  3889. {
  3890. // While we might get here when the session is closed (from location profiles),
  3891. // it's not a problem as the Path setter is noop then
  3892. DirView(Side)->Path = Path;
  3893. }
  3894. return Result;
  3895. }
  3896. //---------------------------------------------------------------------------
  3897. void __fastcall TCustomScpExplorerForm::CalculateSize(
  3898. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  3899. bool & Close)
  3900. {
  3901. // terminal can be already closed (e.g. dropped connection)
  3902. if (Terminal != NULL)
  3903. {
  3904. try
  3905. {
  3906. Terminal->CalculateFilesSize(FileList, Size, 0, NULL, true, Stats);
  3907. }
  3908. catch(...)
  3909. {
  3910. if (!Terminal->Active)
  3911. {
  3912. Close = true;
  3913. }
  3914. throw;
  3915. }
  3916. }
  3917. }
  3918. //---------------------------------------------------------------------------
  3919. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  3920. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  3921. bool & Close)
  3922. {
  3923. // terminal can be already closed (e.g. dropped connection)
  3924. if (Terminal != NULL)
  3925. {
  3926. Configuration->Usage->Inc(L"ChecksumCalculated");
  3927. try
  3928. {
  3929. Terminal->CalculateFilesChecksum(Alg, FileList, NULL, OnCalculatedChecksum);
  3930. }
  3931. catch(...)
  3932. {
  3933. if (!Terminal->Active)
  3934. {
  3935. Close = true;
  3936. }
  3937. throw;
  3938. }
  3939. }
  3940. }
  3941. //---------------------------------------------------------------------------
  3942. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  3943. {
  3944. bool Result;
  3945. if (Side == osRemote)
  3946. {
  3947. TRemoteTokenList * GroupList = NULL;
  3948. TRemoteTokenList * UserList = NULL;
  3949. try
  3950. {
  3951. TRemoteProperties CurrentProperties;
  3952. if (Terminal->LoadFilesProperties(FileList))
  3953. {
  3954. RemoteDirView->Invalidate();
  3955. }
  3956. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  3957. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  3958. if (CapableGroupChanging || CapableOwnerChanging)
  3959. {
  3960. if (CapableGroupChanging)
  3961. {
  3962. GroupList = Terminal->Groups->Duplicate();
  3963. }
  3964. if (CapableOwnerChanging)
  3965. {
  3966. UserList = Terminal->Users->Duplicate();
  3967. }
  3968. TRemoteDirectory * Files = Terminal->Files;
  3969. int Count = Files->Count;
  3970. if (Count > 100)
  3971. {
  3972. Count = 100;
  3973. }
  3974. for (int Index = 0; Index < Count; Index++)
  3975. {
  3976. TRemoteFile * File = Files->Files[Index];
  3977. if (CapableGroupChanging)
  3978. {
  3979. GroupList->AddUnique(File->Group);
  3980. }
  3981. if (CapableOwnerChanging)
  3982. {
  3983. UserList->AddUnique(File->Owner);
  3984. }
  3985. }
  3986. // if we haven't collected tokens for all files in current directory,
  3987. // make sure we collect them at least for all selected files.
  3988. // (note that so far the files in FileList has to be from current direcotry)
  3989. if (Count < Files->Count)
  3990. {
  3991. for (int Index = 0; Index < FileList->Count; Index++)
  3992. {
  3993. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  3994. if (CapableGroupChanging)
  3995. {
  3996. GroupList->AddUnique(File->Group);
  3997. }
  3998. if (CapableOwnerChanging)
  3999. {
  4000. UserList->AddUnique(File->Owner);
  4001. }
  4002. }
  4003. }
  4004. }
  4005. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4006. int Flags = 0;
  4007. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4008. if (CapableOwnerChanging) Flags |= cpOwner;
  4009. if (CapableGroupChanging) Flags |= cpGroup;
  4010. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4011. if (Terminal->IsCapable[fcCalculatingChecksum])
  4012. {
  4013. CalculateChecksumEvent = CalculateChecksum;
  4014. }
  4015. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4016. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4017. TRemoteProperties NewProperties = CurrentProperties;
  4018. Result =
  4019. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4020. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4021. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4022. CalculateSize, CalculateChecksumEvent);
  4023. if (Result)
  4024. {
  4025. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4026. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4027. }
  4028. }
  4029. __finally
  4030. {
  4031. delete GroupList;
  4032. delete UserList;
  4033. }
  4034. }
  4035. else
  4036. {
  4037. DirView(Side)->DisplayPropertiesMenu();
  4038. Result = true;
  4039. }
  4040. return Result;
  4041. }
  4042. //---------------------------------------------------------------------------
  4043. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4044. {
  4045. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4046. {
  4047. FIgnoreNextDialogChar = Key;
  4048. }
  4049. Key = 0;
  4050. }
  4051. //---------------------------------------------------------------------------
  4052. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4053. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4054. {
  4055. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4056. if (Command != NULL)
  4057. {
  4058. KeyProcessed(Key, Shift);
  4059. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4060. {
  4061. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4062. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4063. false, false, const_cast<TCustomCommandType *>(Command));
  4064. }
  4065. }
  4066. }
  4067. //---------------------------------------------------------------------------
  4068. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4069. {
  4070. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4071. {
  4072. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4073. }
  4074. if (!DirView(osCurrent)->IsEditing())
  4075. {
  4076. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4077. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4078. {
  4079. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4080. if (((Action->ShortCut == KeyShortCut) ||
  4081. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4082. AllowedAction(Action, aaShortCut))
  4083. {
  4084. // Has to be called before the action as the dialog char is already in queue.
  4085. // So when the action consumes message queue, we already need to have the
  4086. // FIgnoreNextDialogChar set
  4087. KeyProcessed(Key, Shift);
  4088. // Reset reference to previous component (when menu/toolbar was clicked).
  4089. // Needed to detect that action was invoked by keyboard shortcut
  4090. // in TNonVisualDataModule::ExplorerActionsExecute
  4091. Action->ActionComponent = NULL;
  4092. Action->Execute();
  4093. return;
  4094. }
  4095. }
  4096. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4097. {
  4098. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4099. {
  4100. KeyProcessed(Key, Shift);
  4101. TTerminalManager::Instance()->ActiveTerminalIndex = i;
  4102. return;
  4103. }
  4104. }
  4105. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4106. {
  4107. KeyProcessed(Key, Shift);
  4108. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4109. }
  4110. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4111. if (IsCustomShortCut(CustomShortCut))
  4112. {
  4113. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4114. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4115. if (WinConfiguration->SharedBookmarks != NULL)
  4116. {
  4117. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4118. if ((Bookmark != NULL) &&
  4119. OpenBookmark(FCurrentSide, Bookmark))
  4120. {
  4121. KeyProcessed(Key, Shift);
  4122. }
  4123. }
  4124. }
  4125. }
  4126. TForm::KeyDown(Key, Shift);
  4127. }
  4128. //---------------------------------------------------------------------------
  4129. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4130. {
  4131. DebugAssert(Terminal != NULL);
  4132. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  4133. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  4134. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4135. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4136. bool SecurityEnabled = !SessionInfo.SecurityProtocolName.IsEmpty();
  4137. SessionStatusBar->Panels->Items[Offset + 0]->Enabled = SecurityEnabled;
  4138. // expanded from ?: to avoid memory leaks
  4139. if (SecurityEnabled)
  4140. {
  4141. SessionStatusBar->Panels->Items[Offset + 0]->Hint =
  4142. FMTLOAD(STATUS_SECURE, (SessionInfo.SecurityProtocolName));
  4143. }
  4144. else
  4145. {
  4146. SessionStatusBar->Panels->Items[Offset + 0]->Hint = LoadStr(STATUS_INSECURE);
  4147. }
  4148. if (FileSystemInfo.ProtocolName.IsEmpty())
  4149. {
  4150. SessionStatusBar->Panels->Items[Offset + 1]->Caption = SessionInfo.ProtocolName;
  4151. }
  4152. else
  4153. {
  4154. SessionStatusBar->Panels->Items[Offset + 1]->Caption = FileSystemInfo.ProtocolName;
  4155. }
  4156. SessionStatusBar->Panels->Items[Offset + 1]->Hint = LoadStr(STATUS_PROTOCOL_HINT);
  4157. SessionStatusBar->Panels->Items[Offset + 2]->Enabled =
  4158. (!SessionInfo.CSCompression.IsEmpty() || !SessionInfo.SCCompression.IsEmpty());
  4159. UnicodeString CSCompressionStr = DefaultStr(SessionInfo.CSCompression, LoadStr(NO_STR));
  4160. UnicodeString SCCompressionStr = DefaultStr(SessionInfo.SCCompression, LoadStr(NO_STR));
  4161. UnicodeString CompressionStr = CSCompressionStr;
  4162. if (CSCompressionStr != SCCompressionStr)
  4163. {
  4164. CompressionStr += UnicodeString(L"/") + SCCompressionStr;
  4165. }
  4166. SessionStatusBar->Panels->Items[Offset + 2]->Hint = FMTLOAD(STATUS_COMPRESSION_HINT, (CompressionStr));
  4167. SessionStatusBar->Panels->Items[Offset + 3]->Hint = LoadStr(STATUS_DURATION_HINT);
  4168. UpdateStatusBar();
  4169. }
  4170. //---------------------------------------------------------------------------
  4171. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4172. {
  4173. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4174. DebugAssert(SessionStatusBar != NULL);
  4175. if (!Terminal || !Terminal->Active || Terminal->Status < ssOpened)
  4176. {
  4177. // note: (Terminal->Status < sshReady) currently never happens here,
  4178. // so STATUS_CONNECTING is never used
  4179. SessionStatusBar->SimplePanel = true;
  4180. SessionStatusBar->SimpleText = LoadStr(
  4181. !Terminal || !Terminal->Active ? STATUS_NOT_CONNECTED : STATUS_CONNECTING);
  4182. }
  4183. else
  4184. {
  4185. DebugAssert(Terminal);
  4186. SessionStatusBar->SimplePanel = false;
  4187. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  4188. if (!FNote.IsEmpty())
  4189. {
  4190. SessionStatusBar->Panels->Items[0]->Caption = FNote;
  4191. }
  4192. else
  4193. {
  4194. UpdateStatusPanelText(SessionStatusBar->Panels->Items[0]);
  4195. }
  4196. SessionStatusBar->Panels->Items[0]->Hint = FNoteHints;
  4197. SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1]->Caption =
  4198. FormatDateTimeSpan(Configuration->TimeFormat, Now() - SessionInfo.LoginTime);
  4199. }
  4200. }
  4201. //---------------------------------------------------------------------------
  4202. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4203. {
  4204. Panel->Caption = L"";
  4205. }
  4206. //---------------------------------------------------------------------------
  4207. void __fastcall TCustomScpExplorerForm::Idle()
  4208. {
  4209. if (FShowing || FStandaloneEditing)
  4210. {
  4211. FEditorManager->Check();
  4212. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4213. // that needs to know if queue view is visible (and it may be closed after queue update)
  4214. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4215. }
  4216. if (FShowing)
  4217. {
  4218. if (!NonVisualDataModule->Busy &&
  4219. // Menu is opened or drag&drop is going on
  4220. (Mouse->Capture == NULL))
  4221. {
  4222. if (FRefreshRemoteDirectory)
  4223. {
  4224. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4225. {
  4226. Terminal->RefreshDirectory();
  4227. }
  4228. FRefreshRemoteDirectory = false;
  4229. }
  4230. if (FRefreshLocalDirectory)
  4231. {
  4232. ReloadLocalDirectory();
  4233. FRefreshLocalDirectory = false;
  4234. }
  4235. if (WinConfiguration->RefreshRemotePanel)
  4236. {
  4237. TManagedTerminal * ManagedTerminal =
  4238. dynamic_cast<TManagedTerminal *>(Terminal);
  4239. if ((ManagedTerminal != NULL) && (Terminal->Status == ssOpened) &&
  4240. (Now() - ManagedTerminal->DirectoryLoaded >
  4241. WinConfiguration->RefreshRemotePanelInterval))
  4242. {
  4243. RemoteDirView->ReloadDirectory();
  4244. }
  4245. }
  4246. }
  4247. }
  4248. if (FShowing || FStandaloneEditing)
  4249. {
  4250. if (FQueueStatusInvalidated)
  4251. {
  4252. UpdateQueueStatus(false);
  4253. }
  4254. RefreshQueueItems();
  4255. }
  4256. if (FShowing)
  4257. {
  4258. UpdateStatusBar();
  4259. }
  4260. FIgnoreNextDialogChar = 0;
  4261. }
  4262. //---------------------------------------------------------------------------
  4263. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4264. {
  4265. try
  4266. {
  4267. FUserActionTimer->Enabled = false;
  4268. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4269. {
  4270. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4271. {
  4272. FPendingQueueActionItem->ProcessUserAction();
  4273. }
  4274. }
  4275. }
  4276. __finally
  4277. {
  4278. FPendingQueueActionItem = NULL;
  4279. }
  4280. }
  4281. //---------------------------------------------------------------------------
  4282. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4283. {
  4284. if (WinConfiguration->MinimizeToTray)
  4285. {
  4286. UpdateTrayIcon();
  4287. FTrayIcon->Visible = true;
  4288. if (Visible)
  4289. {
  4290. ShowWindow(Handle, SW_HIDE);
  4291. }
  4292. }
  4293. }
  4294. //---------------------------------------------------------------------------
  4295. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4296. {
  4297. // WORKAROUND
  4298. // When restoring maximized window from minimization,
  4299. // rarely some controls do not align properly.
  4300. // Two instances seen (both for Commander):
  4301. // - When restoring, window is temporarily narrower (not maximized),
  4302. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4303. // Once maximized already, top dock shinks back, but the session PageControl,
  4304. // do not align up, leaving space between TopDock and PageControl.
  4305. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4306. for (int Index = 0; Index < ControlCount; Index++)
  4307. {
  4308. RealignControl(Controls[Index]);
  4309. }
  4310. if (FTrayIcon->Visible)
  4311. {
  4312. FTrayIcon->Visible = false;
  4313. if (Visible)
  4314. {
  4315. ShowWindow(Handle, SW_SHOW);
  4316. }
  4317. }
  4318. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4319. {
  4320. FNeedSession = false;
  4321. NonVisualDataModule->StartBusy();
  4322. try
  4323. {
  4324. NeedSession(false);
  4325. }
  4326. __finally
  4327. {
  4328. NonVisualDataModule->EndBusy();
  4329. }
  4330. }
  4331. }
  4332. //---------------------------------------------------------------------------
  4333. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4334. {
  4335. FTrayIcon->Hint = GetMainForm()->Caption;
  4336. }
  4337. //---------------------------------------------------------------------------
  4338. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4339. {
  4340. UpdateTrayIcon();
  4341. }
  4342. //---------------------------------------------------------------------------
  4343. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4344. {
  4345. // workaround
  4346. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4347. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4348. // But WM_ACTIVATEAPP message can be received even when
  4349. // the main window is minimized to the tray and internal editor window is focused
  4350. // (after another application was previously active)
  4351. if (::IsIconic(Handle))
  4352. {
  4353. if (!IsAppIconic())
  4354. {
  4355. SetAppIconic(true);
  4356. }
  4357. }
  4358. ::ApplicationRestore();
  4359. Application->BringToFront();
  4360. }
  4361. //---------------------------------------------------------------------------
  4362. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4363. {
  4364. RestoreApp();
  4365. }
  4366. //---------------------------------------------------------------------------
  4367. void __fastcall TCustomScpExplorerForm::NewSession(bool FromSite, const UnicodeString & SessionUrl)
  4368. {
  4369. if (OpenInNewWindow())
  4370. {
  4371. // todo: Pass FromSite
  4372. ExecuteNewInstance(SessionUrl);
  4373. }
  4374. else
  4375. {
  4376. TTerminalManager::Instance()->NewSession(FromSite, SessionUrl);
  4377. }
  4378. }
  4379. //---------------------------------------------------------------------------
  4380. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4381. {
  4382. UnicodeString SessionName = StoredSessions->HiddenPrefix + Terminal->SessionData->SessionName;
  4383. // current working directories become defaults here, what is not right
  4384. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4385. StoredSessions->NewSession(SessionName, SessionData.get());
  4386. // modified only, explicit
  4387. StoredSessions->Save(false, true);
  4388. // encode session name because of slashes in hierarchical sessions
  4389. return EncodeUrlString(SessionName);
  4390. }
  4391. //---------------------------------------------------------------------------
  4392. void __fastcall TCustomScpExplorerForm::DuplicateSession()
  4393. {
  4394. if (OpenInNewWindow())
  4395. {
  4396. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4397. }
  4398. else
  4399. {
  4400. // current working directories become defaults here, what is not right
  4401. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4402. TTerminalManager * Manager = TTerminalManager::Instance();
  4403. TTerminal * Terminal = Manager->NewTerminal(SessionData.get());
  4404. Manager->ActiveTerminal = Terminal;
  4405. }
  4406. }
  4407. //---------------------------------------------------------------------------
  4408. void __fastcall TCustomScpExplorerForm::RenameSession()
  4409. {
  4410. UnicodeString Name = Terminal->SessionData->Name;
  4411. if (InputDialog(LoadStr(RENAME_SESSION_TITLE), LoadStr(RENAME_SESSION_PROMPT), Name, HELP_SESSION_RENAME))
  4412. {
  4413. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  4414. TSessionData::ValidateName(Name);
  4415. // This is inconsistent with how color (for example) is handled.
  4416. Terminal->SessionData->Name = Name;
  4417. UpdateControls();
  4418. // Add/Remove distinguishing paths from sessions of the same name.
  4419. DoTerminalListChanged();
  4420. }
  4421. }
  4422. //---------------------------------------------------------------------------
  4423. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  4424. {
  4425. DebugAssert(Queue != NULL);
  4426. bool Result = Queue->IsEmpty;
  4427. if (!Result)
  4428. {
  4429. SetFocus();
  4430. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  4431. }
  4432. return Result;
  4433. }
  4434. //---------------------------------------------------------------------------
  4435. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  4436. {
  4437. return CanCloseQueue(FQueue);
  4438. }
  4439. //---------------------------------------------------------------------------
  4440. void __fastcall TCustomScpExplorerForm::CloseSession()
  4441. {
  4442. if (CanCloseQueue())
  4443. {
  4444. TTerminalManager::Instance()->FreeActiveTerminal();
  4445. }
  4446. }
  4447. //---------------------------------------------------------------------------
  4448. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  4449. {
  4450. if (OpenInNewWindow())
  4451. {
  4452. // encode session name because of slashes in hierarchical sessions
  4453. ExecuteNewInstance(EncodeUrlString(Data->Name));
  4454. }
  4455. else
  4456. {
  4457. TTerminalManager * Manager = TTerminalManager::Instance();
  4458. TTerminal * Terminal = Manager->NewTerminal(Data);
  4459. Manager->ActiveTerminal = Terminal;
  4460. }
  4461. }
  4462. //---------------------------------------------------------------------------
  4463. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  4464. {
  4465. if (OpenInNewWindow())
  4466. {
  4467. ExecuteNewInstance(Name);
  4468. }
  4469. else
  4470. {
  4471. TTerminalManager * Manager = TTerminalManager::Instance();
  4472. std::unique_ptr<TObjectList> DataList(new TObjectList());
  4473. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  4474. Manager->ActiveTerminal = Manager->NewTerminals(DataList.get());
  4475. }
  4476. }
  4477. //---------------------------------------------------------------------------
  4478. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  4479. bool &CanClose)
  4480. {
  4481. if (Terminal != NULL)
  4482. {
  4483. if (Terminal->Active && WinConfiguration->ConfirmClosingSession)
  4484. {
  4485. unsigned int Result;
  4486. TMessageParams Params(mpNeverAskAgainCheck);
  4487. UnicodeString Message;
  4488. int Answers = qaOK | qaCancel;
  4489. if (TTerminalManager::Instance()->Count > 1)
  4490. {
  4491. if (!WinConfiguration->AutoSaveWorkspace)
  4492. {
  4493. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE2);
  4494. Answers = qaYes | qaNo | qaCancel;
  4495. }
  4496. else
  4497. {
  4498. Message = MainInstructions(LoadStr(CLOSE_SESSIONS));
  4499. }
  4500. }
  4501. else
  4502. {
  4503. Message = MainInstructions(FMTLOAD(CLOSE_SESSION, (Terminal->SessionData->SessionName)));
  4504. }
  4505. if (WinConfiguration->AutoSaveWorkspace)
  4506. {
  4507. Message =
  4508. FORMAT("%s\n\n%s", (Message,
  4509. FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()))));
  4510. }
  4511. SetFocus();
  4512. Result = MessageDialog(Message, qtConfirmation,
  4513. Answers, HELP_NONE, &Params);
  4514. if (Result == qaNeverAskAgain)
  4515. {
  4516. WinConfiguration->ConfirmClosingSession = false;
  4517. }
  4518. if (Result == qaNo)
  4519. {
  4520. CanClose = SaveWorkspace(true);
  4521. // note that the workspace will be saved redundatly again from FormClose
  4522. }
  4523. else
  4524. {
  4525. CanClose =
  4526. (Result == qaOK) ||
  4527. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  4528. (Result == qaNeverAskAgain);
  4529. }
  4530. }
  4531. if (CanClose)
  4532. {
  4533. CanClose = CanCloseQueue();
  4534. }
  4535. }
  4536. if (CanClose)
  4537. {
  4538. CanClose =
  4539. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  4540. FEditorManager->CloseExternalFilesWithoutProcess();
  4541. if (CanClose)
  4542. {
  4543. while (CanClose && (FLocalEditors->Count > 0))
  4544. {
  4545. int PrevCount = FLocalEditors->Count;
  4546. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  4547. CanClose = (FLocalEditors->Count < PrevCount);
  4548. }
  4549. if (CanClose)
  4550. {
  4551. CanClose = FEditorManager->Empty(true);
  4552. if (!CanClose)
  4553. {
  4554. SetFocus();
  4555. CanClose =
  4556. (MessageDialog(
  4557. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  4558. }
  4559. }
  4560. }
  4561. }
  4562. }
  4563. //---------------------------------------------------------------------------
  4564. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  4565. {
  4566. TForm * Form = dynamic_cast<TForm *>(Sender);
  4567. DebugAssert(Form != NULL);
  4568. Form->Close();
  4569. }
  4570. //---------------------------------------------------------------------------
  4571. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  4572. {
  4573. TForm * Form = dynamic_cast<TForm *>(Sender);
  4574. delete Form;
  4575. }
  4576. //---------------------------------------------------------------------------
  4577. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  4578. {
  4579. while (FLocalEditors->Count > 0)
  4580. {
  4581. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  4582. }
  4583. }
  4584. //---------------------------------------------------------------------------
  4585. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  4586. TObject *Sender)
  4587. {
  4588. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  4589. try
  4590. {
  4591. SetProperties(osRemote, FileList);
  4592. }
  4593. __finally
  4594. {
  4595. delete FileList;
  4596. }
  4597. }
  4598. //---------------------------------------------------------------------------
  4599. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  4600. {
  4601. if (value)
  4602. {
  4603. if (Component == fcCustomCommandsBand)
  4604. {
  4605. UpdateCustomCommandsToolbar();
  4606. }
  4607. }
  4608. }
  4609. //---------------------------------------------------------------------------
  4610. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  4611. {
  4612. TControl * Control = GetComponent(Component);
  4613. DebugAssert(Control);
  4614. bool Changed = (Control->Visible != value);
  4615. if (Changed)
  4616. {
  4617. ComponentShowing(Component, value);
  4618. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  4619. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  4620. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  4621. if (value)
  4622. {
  4623. int RemainingHeight = Control->Parent->ClientHeight;
  4624. int RemainingWidth = Control->Parent->ClientWidth;
  4625. for (int i = 0; i < Control->Parent->ControlCount; i++)
  4626. {
  4627. TControl * ChildControl = Control->Parent->Controls[i];
  4628. if (ChildControl->Visible)
  4629. {
  4630. switch (ChildControl->Align)
  4631. {
  4632. case alTop:
  4633. case alBottom:
  4634. RemainingHeight -= ChildControl->Height;
  4635. break;
  4636. case alLeft:
  4637. case alRight:
  4638. RemainingWidth -= ChildControl->Width;
  4639. break;
  4640. }
  4641. }
  4642. }
  4643. int Reserve = ScaleByTextHeight(this, 32);
  4644. // queue in explorer, trees in commander
  4645. if (Control->Height > RemainingHeight - Reserve)
  4646. {
  4647. Control->Height = RemainingHeight / 2;
  4648. }
  4649. if (Control->Width > RemainingWidth - Reserve)
  4650. {
  4651. Control->Width = RemainingWidth / 2;
  4652. }
  4653. }
  4654. Control->Visible = value;
  4655. if (WasFocused && Visible)
  4656. {
  4657. DirView(osCurrent)->SetFocus();
  4658. }
  4659. FixControlsPlacement();
  4660. }
  4661. }
  4662. //---------------------------------------------------------------------------
  4663. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  4664. {
  4665. TControl * Control = GetComponent(Component);
  4666. if (Control == NULL)
  4667. {
  4668. return false;
  4669. }
  4670. else
  4671. {
  4672. return Control->Visible;
  4673. }
  4674. }
  4675. //---------------------------------------------------------------------------
  4676. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  4677. {
  4678. bool Result;
  4679. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  4680. {
  4681. Result = !IsUWP();
  4682. }
  4683. else
  4684. {
  4685. Result = true;
  4686. }
  4687. return Result;
  4688. }
  4689. //---------------------------------------------------------------------------
  4690. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  4691. {
  4692. if (RemoteDirView->ItemFocused != NULL)
  4693. {
  4694. RemoteDirView->ItemFocused->MakeVisible(false);
  4695. }
  4696. QueueSplitter->Visible = QueuePanel->Visible;
  4697. RemotePanelSplitter->Visible = RemoteDriveView->Visible;
  4698. }
  4699. //---------------------------------------------------------------------------
  4700. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  4701. {
  4702. switch (Component) {
  4703. case fcStatusBar: return RemoteStatusBar;
  4704. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  4705. case fcQueueView: return QueuePanel;
  4706. case fcQueueToolbar: return QueueDock;
  4707. case fcRemoteTree: return RemoteDriveView;
  4708. case fcSessionsTabs: return SessionsPageControl;
  4709. default: return NULL;
  4710. }
  4711. }
  4712. //---------------------------------------------------------------------------
  4713. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  4714. TObject *Sender, TListColumn *Column, TPoint &Point)
  4715. {
  4716. DebugAssert(NonVisualDataModule && Column && Sender);
  4717. NonVisualDataModule->ListColumn = Column;
  4718. TPopupMenu * DirViewColumnMenu;
  4719. if (Sender == RemoteDirView)
  4720. {
  4721. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  4722. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible =
  4723. (Column->Index == uvName);
  4724. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible =
  4725. (Column->Index == uvSize);
  4726. }
  4727. else
  4728. {
  4729. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  4730. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible =
  4731. (Column->Index == dvName);
  4732. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible =
  4733. (Column->Index == dvSize);
  4734. }
  4735. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  4736. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  4737. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  4738. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  4739. }
  4740. //---------------------------------------------------------------------------
  4741. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  4742. TObject *Sender, TListItem *Item, bool &AllowExec)
  4743. {
  4744. DoDirViewExecFile(Sender, Item, AllowExec);
  4745. }
  4746. //---------------------------------------------------------------------------
  4747. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  4748. TListItem * Item, bool & AllowExec)
  4749. {
  4750. DebugAssert(Sender && Item && Configuration);
  4751. DebugAssert(AllowExec);
  4752. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  4753. bool Remote = (ADirView == DirView(osRemote));
  4754. bool ResolvedSymlinks = !Remote || Terminal->ResolvingSymlinks;
  4755. TOperationSide Side = (Remote ? osRemote : osLocal);
  4756. // Anything special is done on double click only (not on "open" indicated by FForceExecution),
  4757. // on files only (not directories)
  4758. // and only when symlinks are resolved (apply to remote panel only)
  4759. if (!ADirView->ItemIsDirectory(Item) &&
  4760. (ResolvedSymlinks || FForceExecution || Terminal->IsEncryptingFiles()))
  4761. {
  4762. if ((WinConfiguration->DoubleClickAction != dcaOpen) &&
  4763. !FForceExecution &&
  4764. (ResolvedSymlinks || Terminal->IsEncryptingFiles()))
  4765. {
  4766. if (WinConfiguration->DoubleClickAction == dcaCopy)
  4767. {
  4768. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  4769. UnlockWindow();
  4770. try
  4771. {
  4772. ExecuteFileOperation(
  4773. foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  4774. }
  4775. __finally
  4776. {
  4777. LockWindow();
  4778. }
  4779. AllowExec = false;
  4780. }
  4781. else if (WinConfiguration->DoubleClickAction == dcaEdit)
  4782. {
  4783. if (!Remote || !WinConfiguration->DisableOpenEdit)
  4784. {
  4785. ExecuteFile(Side, efDefaultEditor);
  4786. AllowExec = false;
  4787. }
  4788. }
  4789. else
  4790. {
  4791. DebugFail();
  4792. }
  4793. }
  4794. // if we have not done anything special, fall back to default behavior
  4795. if (AllowExec)
  4796. {
  4797. if (Remote && !WinConfiguration->DisableOpenEdit)
  4798. {
  4799. ExecuteFile(osRemote, efShell);
  4800. AllowExec = false;
  4801. }
  4802. }
  4803. }
  4804. }
  4805. //---------------------------------------------------------------------------
  4806. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  4807. {
  4808. return ((Side == osRemote) || (Side == osCurrent));
  4809. }
  4810. //---------------------------------------------------------------------------
  4811. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  4812. {
  4813. DebugFail();
  4814. }
  4815. //---------------------------------------------------------------------------
  4816. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  4817. {
  4818. DebugFail();
  4819. }
  4820. //---------------------------------------------------------------------------
  4821. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  4822. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, bool UseDefaults)
  4823. {
  4824. TSynchronizeParamType Params;
  4825. Params.LocalDirectory = LocalDirectory;
  4826. Params.RemoteDirectory = RemoteDirectory;
  4827. int UnusedParams =
  4828. (GUIConfiguration->SynchronizeParams &
  4829. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize));
  4830. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  4831. Params.Options = GUIConfiguration->SynchronizeOptions;
  4832. bool SaveSettings = false;
  4833. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  4834. &DoSynchronizeTooManyDirectories);
  4835. DebugAssert(FSynchronizeController == NULL);
  4836. FSynchronizeController = &Controller;
  4837. bool Result;
  4838. try
  4839. {
  4840. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4841. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  4842. int Options =
  4843. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  4844. DebugAssert(FOnFeedSynchronizeError == NULL);
  4845. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  4846. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  4847. FOnFeedSynchronizeError, SynchronizeInNewWindow, UseDefaults);
  4848. if (Result)
  4849. {
  4850. if (SaveSettings)
  4851. {
  4852. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  4853. GUIConfiguration->SynchronizeOptions = Params.Options;
  4854. }
  4855. else
  4856. {
  4857. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  4858. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  4859. FLAGSET(Params.Options, soSynchronize))
  4860. {
  4861. GUIConfiguration->SynchronizeOptions =
  4862. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  4863. soSynchronize;
  4864. }
  4865. }
  4866. LocalDirectory = Params.LocalDirectory;
  4867. RemoteDirectory = Params.RemoteDirectory;
  4868. }
  4869. }
  4870. __finally
  4871. {
  4872. FSynchronizeController = NULL;
  4873. DebugAssert(FOnFeedSynchronizeError == NULL);
  4874. FOnFeedSynchronizeError = NULL;
  4875. }
  4876. return Result;
  4877. }
  4878. //---------------------------------------------------------------------------
  4879. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  4880. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  4881. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  4882. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  4883. TSynchronizeOptions * Options, bool Full)
  4884. {
  4885. // Keep-up-to-date mode
  4886. if (Terminal->Status == ssOpened)
  4887. {
  4888. try
  4889. {
  4890. int PParams = Params.Params;
  4891. if (!Full)
  4892. {
  4893. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  4894. if (FLAGSET(Params.Options, soRecurse))
  4895. {
  4896. PParams |= TTerminal::spSubDirs;
  4897. }
  4898. }
  4899. else
  4900. {
  4901. // if keepuptodate is non-recursive,
  4902. // full sync before has to be non-recursive as well
  4903. if (FLAGCLEAR(Params.Options, soRecurse))
  4904. {
  4905. PParams |= TTerminal::spNoRecurse;
  4906. }
  4907. }
  4908. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  4909. PParams, Checklist, Options);
  4910. }
  4911. catch (Exception & E)
  4912. {
  4913. if (FLAGSET(Params.Options, soContinueOnError) && Terminal->Active &&
  4914. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  4915. {
  4916. // noop, already logged in MoreMessageDialog
  4917. }
  4918. else
  4919. {
  4920. ShowExtendedExceptionEx(Terminal, &E);
  4921. throw;
  4922. }
  4923. }
  4924. }
  4925. }
  4926. //---------------------------------------------------------------------------
  4927. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  4928. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  4929. const UnicodeString ErrorStr)
  4930. {
  4931. if (!Directory.IsEmpty())
  4932. {
  4933. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  4934. }
  4935. else
  4936. {
  4937. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  4938. }
  4939. }
  4940. //---------------------------------------------------------------------------
  4941. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  4942. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  4943. {
  4944. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  4945. {
  4946. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  4947. }
  4948. else
  4949. {
  4950. TMessageParams Params(mpNeverAskAgainCheck);
  4951. unsigned int Result = MessageDialog(
  4952. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  4953. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  4954. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  4955. {
  4956. MaxDirectories *= 2;
  4957. if (Result == qaNeverAskAgain)
  4958. {
  4959. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  4960. }
  4961. }
  4962. else
  4963. {
  4964. Abort();
  4965. }
  4966. }
  4967. }
  4968. //---------------------------------------------------------------------------
  4969. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  4970. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4971. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  4972. TSynchronizeOptions * Options)
  4973. {
  4974. // Keep-up-to-date mode
  4975. DebugAssert(!FAutoOperation);
  4976. void * BatchStorage;
  4977. BatchStart(BatchStorage);
  4978. FAutoOperation = true;
  4979. bool AnyOperation = false;
  4980. TDateTime StartTime = Now();
  4981. TSynchronizeChecklist * AChecklist = NULL;
  4982. try
  4983. {
  4984. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, true);
  4985. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  4986. {
  4987. FSynchronizeProgressForm->Start();
  4988. }
  4989. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  4990. static_cast<TTerminal::TSynchronizeMode>(Mode),
  4991. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  4992. Options);
  4993. SAFE_DESTROY(FSynchronizeProgressForm);
  4994. AnyOperation = (AChecklist->CheckedCount > 0);
  4995. if (AnyOperation)
  4996. {
  4997. TSynchronizeProgress SynchronizeProgress(AChecklist);
  4998. CreateProgressForm(&SynchronizeProgress);
  4999. try
  5000. {
  5001. Terminal->SynchronizeApply(
  5002. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5003. SynchronizeProcessedItem, NULL, NULL, NULL);
  5004. }
  5005. __finally
  5006. {
  5007. DestroyProgressForm();
  5008. }
  5009. }
  5010. }
  5011. __finally
  5012. {
  5013. if (Checklist == NULL)
  5014. {
  5015. delete AChecklist;
  5016. }
  5017. else
  5018. {
  5019. *Checklist = AChecklist;
  5020. }
  5021. FAutoOperation = false;
  5022. SAFE_DESTROY(FSynchronizeProgressForm);
  5023. BatchEnd(BatchStorage);
  5024. ReloadLocalDirectory();
  5025. if (AnyOperation)
  5026. {
  5027. OperationComplete(StartTime);
  5028. }
  5029. }
  5030. }
  5031. //---------------------------------------------------------------------------
  5032. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5033. {
  5034. // can be called from command line
  5035. return Visible &&
  5036. ((DirView(osRemote)->SelCount > 0) ||
  5037. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5038. }
  5039. //---------------------------------------------------------------------------
  5040. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5041. {
  5042. LogSynchronizeEvent(Terminal, Message);
  5043. }
  5044. //---------------------------------------------------------------------------
  5045. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5046. int Params, TSynchronizeOptions & Options)
  5047. {
  5048. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5049. {
  5050. Options.Filter = new TStringList();
  5051. Options.Filter->CaseSensitive = false;
  5052. Options.Filter->Duplicates = Types::dupAccept;
  5053. if (DirView(osRemote)->SelCount > 0)
  5054. {
  5055. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5056. }
  5057. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5058. {
  5059. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5060. }
  5061. Options.Filter->Sort();
  5062. }
  5063. }
  5064. //---------------------------------------------------------------------------
  5065. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5066. {
  5067. TCopyParamType Defaults;
  5068. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5069. ConfigStorage->AccessMode = smRead;
  5070. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false, false))
  5071. {
  5072. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5073. }
  5074. ConfigStorage.reset(NULL);
  5075. std::unique_ptr<TStringList> Options(new TStringList());
  5076. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5077. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5078. UnicodeString Result;
  5079. if (Options->Count > 0)
  5080. {
  5081. Result =
  5082. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5083. }
  5084. return Result;
  5085. }
  5086. //---------------------------------------------------------------------------
  5087. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5088. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5089. {
  5090. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5091. UnicodeString AdditionalParams =
  5092. FORMAT(L"%s \"%s\" \"%s\" %d %d %s%s", (
  5093. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5094. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options,
  5095. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5096. SerializeCopyParamForCommandLine(CopyParams)));
  5097. ExecuteNewInstance(SessionName, AdditionalParams);
  5098. }
  5099. //---------------------------------------------------------------------------
  5100. struct TSynchronizeParams
  5101. {
  5102. UnicodeString LocalDirectory;
  5103. UnicodeString RemoteDirectory;
  5104. TSynchronizeMode Mode;
  5105. TSynchronizeChecklist * Checklist;
  5106. int Params;
  5107. TCopyParamType * CopyParam;
  5108. TDateTime CollectElapsed;
  5109. TDateTime * StartTime;
  5110. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5111. };
  5112. //---------------------------------------------------------------------------
  5113. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5114. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5115. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5116. {
  5117. DebugAssert(!FAutoOperation);
  5118. void * BatchStorage;
  5119. BatchStart(BatchStorage);
  5120. FAutoOperation = true;
  5121. TFileOperationStatistics Statistics;
  5122. TDateTime Start = Now();
  5123. try
  5124. {
  5125. Params.OnProcessedItem = OnProcessedItem;
  5126. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5127. CreateProgressForm(&SynchronizeProgress);
  5128. Terminal->SynchronizeApply(
  5129. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5130. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5131. &Statistics);
  5132. }
  5133. __finally
  5134. {
  5135. Params.OnProcessedItem = NULL;
  5136. FAutoOperation = false;
  5137. DestroyProgressForm();
  5138. BatchEnd(BatchStorage);
  5139. ReloadLocalDirectory();
  5140. }
  5141. if (WinConfiguration->SynchronizeSummary)
  5142. {
  5143. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5144. // The statistics should be 0 anyway in this case
  5145. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5146. {
  5147. Message += L"\n";
  5148. if (Statistics.FilesUploaded > 0)
  5149. {
  5150. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5151. }
  5152. if (Statistics.FilesDownloaded > 0)
  5153. {
  5154. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5155. }
  5156. if (Statistics.FilesDeletedLocal > 0)
  5157. {
  5158. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5159. }
  5160. if (Statistics.FilesDeletedRemote > 0)
  5161. {
  5162. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5163. }
  5164. }
  5165. TDateTime Elapsed = (Now() - Start);
  5166. Message +=
  5167. L"\n" +
  5168. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Configuration->TimeFormat, Params.CollectElapsed))) + L"\n" +
  5169. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Configuration->TimeFormat, Elapsed)));
  5170. TMessageParams Params(mpNeverAskAgainCheck);
  5171. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5172. if (Result == qaNeverAskAgain)
  5173. {
  5174. WinConfiguration->SynchronizeSummary = false;
  5175. }
  5176. }
  5177. }
  5178. //---------------------------------------------------------------------------
  5179. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5180. {
  5181. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5182. {
  5183. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5184. }
  5185. // Not set in keep-up-to-date mode - Synchronize() method
  5186. if (Token != NULL)
  5187. {
  5188. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5189. if (Params.OnProcessedItem != NULL)
  5190. {
  5191. Params.OnProcessedItem(NULL, ChecklistItem);
  5192. }
  5193. }
  5194. }
  5195. //---------------------------------------------------------------------------
  5196. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5197. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5198. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5199. {
  5200. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5201. *Params.StartTime = Now();
  5202. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5203. }
  5204. //---------------------------------------------------------------------------
  5205. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5206. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5207. {
  5208. // terminal can be already closed (e.g. dropped connection)
  5209. if (Terminal != NULL)
  5210. {
  5211. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5212. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5213. }
  5214. }
  5215. //---------------------------------------------------------------------------
  5216. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5217. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5218. {
  5219. TAutoBatch AutoBatch(this);
  5220. TAutoFlag AutoOperationFlag(FAutoOperation);
  5221. if (Side == osRemote)
  5222. {
  5223. std::unique_ptr<TStrings> FileList(new TStringList());
  5224. FileList->AddObject(FileName, RemoteFile);
  5225. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5226. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5227. RemoteDirView->SaveSelection();
  5228. RemoteDirView->SaveSelectedNames();
  5229. try
  5230. {
  5231. Terminal->MoveFiles(FileList.get(), Target, FileMask);
  5232. }
  5233. catch(...)
  5234. {
  5235. RemoteDirView->DiscardSavedSelection();
  5236. throw;
  5237. }
  5238. RemoteDirView->RestoreSelection();
  5239. }
  5240. else if (DebugAlwaysTrue(Side == osLocal))
  5241. {
  5242. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5243. {
  5244. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5245. }
  5246. UnicodeString Directory = ExtractFileDir(FileName);
  5247. ReloadLocalDirectory(Directory);
  5248. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5249. if (!SamePaths(Directory, NewDirectory))
  5250. {
  5251. ReloadLocalDirectory(NewDirectory);
  5252. }
  5253. }
  5254. }
  5255. //---------------------------------------------------------------------------
  5256. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  5257. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  5258. const TCopyParamType * CopyParams)
  5259. {
  5260. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5261. UnicodeString AdditionalParams =
  5262. FORMAT(L"%s \"%s\" \"%s\" %d %d %s%s", (
  5263. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  5264. LocalDirectory, RemoteDirectory, Mode, Params,
  5265. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5266. SerializeCopyParamForCommandLine(CopyParams)));
  5267. ExecuteNewInstance(SessionName, AdditionalParams);
  5268. }
  5269. //---------------------------------------------------------------------------
  5270. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  5271. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  5272. TSynchronizeMode & Mode, int Params, bool & SaveMode, bool UseDefaults)
  5273. {
  5274. int Result;
  5275. bool SaveSettings = false;
  5276. int Options =
  5277. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  5278. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  5279. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5280. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  5281. bool Continue =
  5282. UseDefaults ||
  5283. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  5284. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow);
  5285. if (Continue)
  5286. {
  5287. Configuration->Usage->Inc(L"Synchronizations");
  5288. UpdateCopyParamCounters(CopyParam);
  5289. TSynchronizeOptions SynchronizeOptions;
  5290. GetSynchronizeOptions(Params, SynchronizeOptions);
  5291. if (SaveSettings)
  5292. {
  5293. GUIConfiguration->SynchronizeParams = Params;
  5294. }
  5295. else
  5296. {
  5297. SaveMode = false;
  5298. }
  5299. TDateTime StartTime = Now();
  5300. TSynchronizeChecklist * Checklist = NULL;
  5301. try
  5302. {
  5303. DebugAssert(!FAutoOperation);
  5304. FAutoOperation = true;
  5305. try
  5306. {
  5307. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, true);
  5308. FSynchronizeProgressForm->Start();
  5309. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5310. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5311. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5312. &SynchronizeOptions);
  5313. }
  5314. __finally
  5315. {
  5316. FAutoOperation = false;
  5317. SAFE_DESTROY(FSynchronizeProgressForm);
  5318. }
  5319. TSynchronizeParams SynchronizeParams;
  5320. SynchronizeParams.LocalDirectory = LocalDirectory;
  5321. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  5322. SynchronizeParams.Mode = Mode;
  5323. SynchronizeParams.CopyParam = &CopyParam;
  5324. SynchronizeParams.Params = Params;
  5325. SynchronizeParams.Checklist = Checklist;
  5326. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  5327. SynchronizeParams.StartTime = &StartTime;
  5328. SynchronizeParams.OnProcessedItem = NULL;
  5329. Result = Checklist->Count;
  5330. if (Checklist->Count > 0)
  5331. {
  5332. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  5333. {
  5334. if (!DoSynchronizeChecklistDialog(
  5335. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  5336. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, &SynchronizeParams))
  5337. {
  5338. Result = -1;
  5339. }
  5340. }
  5341. else
  5342. {
  5343. FullSynchronize(SynchronizeParams, NULL, NULL);
  5344. }
  5345. }
  5346. else
  5347. {
  5348. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  5349. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  5350. }
  5351. }
  5352. __finally
  5353. {
  5354. delete Checklist;
  5355. }
  5356. OperationComplete(StartTime);
  5357. }
  5358. else
  5359. {
  5360. Result = -1;
  5361. }
  5362. return Result;
  5363. }
  5364. //---------------------------------------------------------------------------
  5365. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  5366. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  5367. bool & Continue, bool Collect)
  5368. {
  5369. if (Collect)
  5370. {
  5371. DebugAssert(FSynchronizeProgressForm != NULL);
  5372. if (!FSynchronizeProgressForm->Started)
  5373. {
  5374. FSynchronizeProgressForm->Start();
  5375. }
  5376. FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Continue);
  5377. }
  5378. else
  5379. {
  5380. DebugAssert(FSynchronizeProgressForm == NULL);
  5381. DebugAssert(FProgressForm != NULL);
  5382. }
  5383. }
  5384. //---------------------------------------------------------------------------
  5385. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  5386. {
  5387. UnicodeString FullFileName = AbsolutePath(FTerminal->CurrentDirectory, FileName);
  5388. TRemoteFile * File = NULL;
  5389. Terminal->ReadFile(FullFileName, File);
  5390. if (File != NULL)
  5391. {
  5392. std::unique_ptr<TRemoteFile> FileOwner(File);
  5393. TAutoFlag Flag(FStandaloneEditing);
  5394. ExecuteRemoteFile(FullFileName, File, efInternalEditor);
  5395. Application->ShowMainForm = false;
  5396. Application->Run();
  5397. }
  5398. }
  5399. //---------------------------------------------------------------------------
  5400. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory()
  5401. {
  5402. DebugFail();
  5403. }
  5404. //---------------------------------------------------------------------------
  5405. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  5406. {
  5407. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  5408. SessionData->Assign(Terminal->SessionData);
  5409. UpdateSessionData(SessionData.get());
  5410. Terminal->UpdateSessionCredentials(SessionData.get());
  5411. if (!Terminal->SessionData->HasSessionName())
  5412. {
  5413. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  5414. // once IsWorkspace is cleared
  5415. SessionData->Name = UnicodeString();
  5416. SessionData->IsWorkspace = false;
  5417. }
  5418. return SessionData.release();
  5419. }
  5420. //---------------------------------------------------------------------------
  5421. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  5422. {
  5423. TSessionData * SessionData = CloneCurrentSessionData();
  5424. try
  5425. {
  5426. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  5427. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  5428. }
  5429. __finally
  5430. {
  5431. delete SessionData;
  5432. }
  5433. }
  5434. //---------------------------------------------------------------------------
  5435. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  5436. {
  5437. TTerminalManager * Manager = TTerminalManager::Instance();
  5438. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5439. if (DebugAlwaysTrue(Terminal != NULL))
  5440. {
  5441. // Update (Managed)Terminal->StateData
  5442. UpdateTerminal(Terminal);
  5443. }
  5444. Manager->SaveWorkspace(DataList.get());
  5445. return DataList.release();
  5446. }
  5447. //---------------------------------------------------------------------------
  5448. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  5449. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  5450. {
  5451. WinConfiguration->LastWorkspace = Name;
  5452. if (!SavePasswords)
  5453. {
  5454. for (int Index = 0; Index < DataList->Count; Index++)
  5455. {
  5456. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  5457. if (SessionData->Link.IsEmpty())
  5458. {
  5459. SessionData->ClearSessionPasswords();
  5460. }
  5461. }
  5462. }
  5463. StoredSessions->NewWorkspace(Name, DataList);
  5464. // modified only
  5465. StoredSessions->Save(false, Explicit);
  5466. }
  5467. //---------------------------------------------------------------------------
  5468. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  5469. {
  5470. return
  5471. DefaultStr(WinConfiguration->LastWorkspace,
  5472. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  5473. }
  5474. //---------------------------------------------------------------------------
  5475. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  5476. {
  5477. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  5478. bool AnyNonStoredSessionWithPassword = false;
  5479. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  5480. bool AllNonStoredSessionsAnonymous = true;
  5481. TTerminalManager * Manager = TTerminalManager::Instance();
  5482. for (int Index = 0; Index < DataList->Count; Index++)
  5483. {
  5484. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  5485. if (SessionData->Link.IsEmpty())
  5486. {
  5487. if (SessionData->HasAnySessionPassword())
  5488. {
  5489. AnyNonStoredSessionWithPassword = true;
  5490. if (!Manager->Terminals[Index]->SessionData->IsWorkspace)
  5491. {
  5492. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  5493. }
  5494. }
  5495. if (!SameText(SessionData->UserName, AnonymousUserName))
  5496. {
  5497. AllNonStoredSessionsAnonymous = false;
  5498. }
  5499. }
  5500. }
  5501. bool SavePasswords;
  5502. bool * PSavePasswords;
  5503. bool NotRecommendedSavingPasswords =
  5504. !CustomWinConfiguration->UseMasterPassword &&
  5505. !AllNonStoredSessionsAnonymous;
  5506. if (Configuration->DisablePasswordStoring ||
  5507. !AnyNonStoredSessionWithPassword)
  5508. {
  5509. PSavePasswords = NULL;
  5510. SavePasswords = false;
  5511. }
  5512. else
  5513. {
  5514. PSavePasswords = &SavePasswords;
  5515. SavePasswords =
  5516. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  5517. !NotRecommendedSavingPasswords;
  5518. }
  5519. UnicodeString Name = WorkspaceName();
  5520. bool CreateShortcut = false;
  5521. bool Result =
  5522. DoSaveWorkspaceDialog(
  5523. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  5524. EnableAutoSave);
  5525. if (Result)
  5526. {
  5527. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  5528. if (CreateShortcut)
  5529. {
  5530. TOperationVisualizer Visualizer;
  5531. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  5532. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  5533. }
  5534. if (EnableAutoSave)
  5535. {
  5536. WinConfiguration->AutoSaveWorkspace = true;
  5537. WinConfiguration->AutoWorkspace = Name;
  5538. if (PSavePasswords != NULL)
  5539. {
  5540. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  5541. }
  5542. }
  5543. }
  5544. return Result;
  5545. }
  5546. //---------------------------------------------------------------------------
  5547. void __fastcall TCustomScpExplorerForm::UpdateTerminal(TTerminal * Terminal)
  5548. {
  5549. TManagedTerminal * ManagedTerminal = dynamic_cast<TManagedTerminal *>(Terminal);
  5550. DebugAssert(ManagedTerminal != NULL);
  5551. SAFE_DESTROY(ManagedTerminal->RemoteExplorerState);
  5552. if (WinConfiguration->PreservePanelState)
  5553. {
  5554. ManagedTerminal->RemoteExplorerState = RemoteDirView->SaveState();
  5555. }
  5556. UpdateSessionData(ManagedTerminal->StateData);
  5557. }
  5558. //---------------------------------------------------------------------------
  5559. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  5560. {
  5561. // Keep in sync with TSessionData::CopyStateData
  5562. DebugAssert(Data != NULL);
  5563. // This is inconsistent with how color (for example) is handled.
  5564. Data->Name = Terminal->SessionData->Name;
  5565. // cannot use RemoteDirView->Path, because it is empty if connection
  5566. // was already closed
  5567. // also only peek, we may not be connected at all atm
  5568. // so make sure we do not try retrieving current directory from the server
  5569. // (particularly with FTP)
  5570. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  5571. if (!ACurrentDirectory.IsEmpty())
  5572. {
  5573. Data->RemoteDirectory = ACurrentDirectory;
  5574. }
  5575. Data->Color = SessionColor;
  5576. }
  5577. //---------------------------------------------------------------------------
  5578. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  5579. {
  5580. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  5581. DebugAssert(Toolbar != NULL);
  5582. for (int i = 0; i < Toolbar->Items->Count; i++)
  5583. {
  5584. TTBXCustomDropDownItem * DropDownItem;
  5585. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  5586. if (DropDownItem != NULL)
  5587. {
  5588. ToolbarItemResize(DropDownItem,
  5589. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  5590. Toolbar->NonClientWidth);
  5591. break;
  5592. }
  5593. }
  5594. }
  5595. //---------------------------------------------------------------------------
  5596. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  5597. {
  5598. Item->EditWidth = Width;
  5599. }
  5600. //---------------------------------------------------------------------------
  5601. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  5602. TTBCustomToolbar * Toolbar, TPoint & ASize)
  5603. {
  5604. for (int i = 0; i < Toolbar->Items->Count; i++)
  5605. {
  5606. TTBXCustomDropDownItem * DropDownItem;
  5607. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  5608. if (DropDownItem != NULL)
  5609. {
  5610. ASize.x -= DropDownItem->EditWidth;
  5611. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  5612. }
  5613. }
  5614. }
  5615. //---------------------------------------------------------------------------
  5616. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  5617. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  5618. {
  5619. if (WinConfiguration->DDWarnLackOfTempSpace)
  5620. {
  5621. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  5622. if (!ADrive.IsEmpty())
  5623. {
  5624. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  5625. DebugAssert(RequiredSpace >= 0);
  5626. __int64 RequiredWithReserve;
  5627. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  5628. if (FreeSpace < RequiredWithReserve)
  5629. {
  5630. unsigned int Result;
  5631. TMessageParams Params(mpNeverAskAgainCheck);
  5632. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  5633. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  5634. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  5635. if (Result == qaNeverAskAgain)
  5636. {
  5637. WinConfiguration->DDWarnLackOfTempSpace = false;
  5638. }
  5639. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  5640. }
  5641. }
  5642. }
  5643. }
  5644. //---------------------------------------------------------------------------
  5645. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  5646. {
  5647. DoOpenDirectoryDialog(odAddBookmark, Side);
  5648. }
  5649. //---------------------------------------------------------------------------
  5650. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  5651. {
  5652. // we should better use TCustomDirView::FCaseSensitive, but it is private
  5653. TStringList * VisitedDirectories = CreateSortedStringList((Side == osRemote));
  5654. try
  5655. {
  5656. TCustomDirView * DView = DirView(Side);
  5657. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  5658. {
  5659. VisitedDirectories->Add(DView->HistoryPath[Index]);
  5660. }
  5661. }
  5662. catch (...)
  5663. {
  5664. delete VisitedDirectories;
  5665. throw;
  5666. }
  5667. return VisitedDirectories;
  5668. }
  5669. //---------------------------------------------------------------------------
  5670. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  5671. TOpenDirectoryMode Mode, TOperationSide Side)
  5672. {
  5673. bool Continue = true;
  5674. if (Mode == odAddBookmark)
  5675. {
  5676. TMessageParams Params(mpNeverAskAgainCheck);
  5677. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  5678. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  5679. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  5680. unsigned int Answer =
  5681. MessageDialog(Message,
  5682. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  5683. if (Answer == qaNeverAskAgain)
  5684. {
  5685. Continue = true;
  5686. WinConfiguration->UseSharedBookmarks = true;
  5687. }
  5688. else if (Answer == qaOK)
  5689. {
  5690. Continue = true;
  5691. WinConfiguration->UseSharedBookmarks = false;
  5692. }
  5693. else
  5694. {
  5695. Continue = false;
  5696. }
  5697. }
  5698. if (Continue)
  5699. {
  5700. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  5701. try
  5702. {
  5703. UnicodeString Name = DirView(Side)->PathName;
  5704. bool Repeat;
  5705. do
  5706. {
  5707. Repeat = false;
  5708. if (::DoOpenDirectoryDialog(Mode, Side, Name, VisitedDirectories, Terminal,
  5709. // do not allow switching to location profiles,
  5710. // if we are not connected
  5711. HasDirView[osLocal] && (Terminal != NULL)))
  5712. {
  5713. TWindowLock Lock(this);
  5714. if (!TryOpenDirectory(Side, Name))
  5715. {
  5716. Repeat = true;
  5717. Mode = odBrowse;
  5718. }
  5719. }
  5720. }
  5721. while (Repeat);
  5722. }
  5723. __finally
  5724. {
  5725. delete VisitedDirectories;
  5726. }
  5727. }
  5728. }
  5729. //---------------------------------------------------------------------------
  5730. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  5731. {
  5732. DebugAssert(!FTerminal->CommandSessionOpened);
  5733. return TTerminalManager::Instance()->ConnectTerminal(FTerminal->CommandSession);
  5734. }
  5735. //---------------------------------------------------------------------------
  5736. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  5737. {
  5738. bool Result = FTerminal->IsCapable[Capability] ||
  5739. FTerminal->CommandSessionOpened;
  5740. if (!Result)
  5741. {
  5742. DebugAssert(FTerminal->IsCapable[fcSecondaryShell]);
  5743. if (!GUIConfiguration->ConfirmCommandSession)
  5744. {
  5745. Result = true;
  5746. }
  5747. else
  5748. {
  5749. TMessageParams Params(mpNeverAskAgainCheck);
  5750. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  5751. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  5752. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  5753. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  5754. if (Answer == qaNeverAskAgain)
  5755. {
  5756. GUIConfiguration->ConfirmCommandSession = false;
  5757. Result = true;
  5758. }
  5759. else if (Answer == qaOK)
  5760. {
  5761. Result = true;
  5762. }
  5763. }
  5764. if (Result)
  5765. {
  5766. Result = CommandSessionFallback();
  5767. }
  5768. }
  5769. return Result;
  5770. }
  5771. //---------------------------------------------------------------------------
  5772. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  5773. {
  5774. if (EnsureCommandSessionFallback(fcAnyCommand))
  5775. {
  5776. DoConsoleDialog(Terminal, Command);
  5777. }
  5778. }
  5779. //---------------------------------------------------------------------------
  5780. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  5781. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  5782. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  5783. {
  5784. if (IsFileControl(DropSourceControl, osRemote) &&
  5785. (FDDExtMapFile != NULL))
  5786. {
  5787. Accept = true;
  5788. }
  5789. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  5790. DebugAssert(FDDTargetControl != NULL);
  5791. }
  5792. //---------------------------------------------------------------------------
  5793. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  5794. _di_IDataObject DataObj, int KeyState,
  5795. const TPoint & Point, int & Effect, bool & Accept)
  5796. {
  5797. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  5798. }
  5799. //---------------------------------------------------------------------------
  5800. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  5801. _di_IDataObject DataObj, int KeyState,
  5802. const TPoint & Point, int & Effect, bool & Accept)
  5803. {
  5804. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  5805. }
  5806. //---------------------------------------------------------------------------
  5807. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  5808. TObject * Sender)
  5809. {
  5810. DebugUsedParam(Sender);
  5811. DebugAssert(FDDTargetControl == Sender);
  5812. FDDTargetControl = NULL;
  5813. }
  5814. //---------------------------------------------------------------------------
  5815. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  5816. {
  5817. FileControlDDDragLeave(SessionsPageControl);
  5818. }
  5819. //---------------------------------------------------------------------------
  5820. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  5821. {
  5822. FileControlDDDragLeave(QueueView3);
  5823. }
  5824. //---------------------------------------------------------------------------
  5825. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  5826. {
  5827. DebugAssert(GetSide(Side) == osRemote);
  5828. DebugUsedParam(Side);
  5829. bool Edit = false;
  5830. TRemoteFile * File = NULL;
  5831. UnicodeString FileName;
  5832. UnicodeString PointTo;
  5833. bool SymbolicLink = true;
  5834. if (RemoteDirView->ItemFocused)
  5835. {
  5836. DebugAssert(RemoteDirView->ItemFocused->Data);
  5837. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  5838. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  5839. if (Edit)
  5840. {
  5841. FileName = File->FileName;
  5842. PointTo = File->LinkTo;
  5843. }
  5844. else
  5845. {
  5846. PointTo = File->FileName;
  5847. }
  5848. }
  5849. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  5850. Terminal->IsCapable[fcHardLink]))
  5851. {
  5852. Configuration->Usage->Inc(L"RemoteLinksCreated");
  5853. if (Edit)
  5854. {
  5855. DebugAssert(File->FileName == FileName);
  5856. int Params = dfNoRecursive;
  5857. Terminal->ExceptionOnFail = true;
  5858. try
  5859. {
  5860. Terminal->DeleteFile(L"", File, &Params);
  5861. }
  5862. __finally
  5863. {
  5864. Terminal->ExceptionOnFail = false;
  5865. }
  5866. }
  5867. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  5868. }
  5869. }
  5870. //---------------------------------------------------------------------------
  5871. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  5872. {
  5873. return
  5874. (Terminal != NULL) &&
  5875. ((GetSide(Side) != osRemote) ||
  5876. (Terminal->ResolvingSymlinks &&
  5877. Terminal->IsCapable[fcSymbolicLink]));
  5878. }
  5879. //---------------------------------------------------------------------------
  5880. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  5881. {
  5882. return
  5883. (FCurrentSide == osRemote) &&
  5884. (RemoteDirView->ItemFocused != NULL) &&
  5885. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  5886. Terminal->SessionData->ResolveSymlinks;
  5887. }
  5888. //---------------------------------------------------------------------------
  5889. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  5890. {
  5891. DebugAssert(!WinConfiguration->DisableOpenEdit);
  5892. FForceExecution = true;
  5893. try
  5894. {
  5895. DirView(osCurrent)->ExecuteCurrentFile();
  5896. }
  5897. __finally
  5898. {
  5899. FForceExecution = false;
  5900. }
  5901. }
  5902. //---------------------------------------------------------------------------
  5903. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  5904. {
  5905. TEditorData ExternalEditor;
  5906. ExternalEditor.Editor = edExternal;
  5907. bool Remember = false;
  5908. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc,
  5909. (GetSide(osCurrent) == osRemote)))
  5910. {
  5911. if (Remember)
  5912. {
  5913. TEditorList * EditorList = new TEditorList;
  5914. try
  5915. {
  5916. *EditorList = *WinConfiguration->EditorList;
  5917. bool Found = false;
  5918. int i = 0;
  5919. while (!Found && (i < EditorList->Count))
  5920. {
  5921. const TEditorPreferences * Editor = EditorList->Editors[i];
  5922. if ((Editor->Data->Editor == edExternal) &&
  5923. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  5924. {
  5925. Found = true;
  5926. }
  5927. i++;
  5928. }
  5929. if (!Found)
  5930. {
  5931. EditorList->Add(new TEditorPreferences(ExternalEditor));
  5932. WinConfiguration->EditorList = EditorList;
  5933. }
  5934. }
  5935. __finally
  5936. {
  5937. delete EditorList;
  5938. }
  5939. }
  5940. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  5941. }
  5942. }
  5943. //---------------------------------------------------------------------------
  5944. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  5945. {
  5946. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  5947. if (FFileFindTerminal == Sender)
  5948. {
  5949. FFileFindTerminal = NULL;
  5950. HideFileFindDialog();
  5951. }
  5952. if (FClipboardTerminal == Sender)
  5953. {
  5954. ClipboardClear(); // implies ClipboardStop
  5955. }
  5956. }
  5957. //---------------------------------------------------------------------------
  5958. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  5959. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  5960. {
  5961. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  5962. DebugAssert(Terminal != NULL);
  5963. if (Data->Terminal == Terminal)
  5964. {
  5965. Data->Terminal = NULL;
  5966. }
  5967. }
  5968. //---------------------------------------------------------------------------
  5969. void __fastcall TCustomScpExplorerForm::LastTerminalClosed(TObject * /*Sender*/)
  5970. {
  5971. UpdateControls();
  5972. SessionColor = TColor(0);
  5973. UpdateRemotePathComboBox(false);
  5974. NeedSession(true);
  5975. }
  5976. //---------------------------------------------------------------------------
  5977. void __fastcall TCustomScpExplorerForm::NeedSession(bool ReloadSessions)
  5978. {
  5979. try
  5980. {
  5981. try
  5982. {
  5983. TTerminalManager::Instance()->NewSession(false, L"", ReloadSessions, this);
  5984. }
  5985. __finally
  5986. {
  5987. if (!WinConfiguration->KeepOpenWhenNoSession &&
  5988. (!Terminal || !Terminal->Active))
  5989. {
  5990. TerminateApplication();
  5991. }
  5992. }
  5993. }
  5994. catch (EAbort &)
  5995. {
  5996. // swallow
  5997. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  5998. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  5999. }
  6000. }
  6001. //---------------------------------------------------------------------------
  6002. void __fastcall TCustomScpExplorerForm::DoTerminalListChanged()
  6003. {
  6004. TStrings * TerminalList = TTerminalManager::Instance()->TerminalList;
  6005. int ActiveTerminalIndex = TTerminalManager::Instance()->ActiveTerminalIndex;
  6006. Configuration->Usage->SetMax(L"MaxOpenedSessions", TerminalList->Count);
  6007. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6008. try
  6009. {
  6010. while ((SessionsPageControl->PageCount > TerminalList->Count + 1) ||
  6011. // Clear the design time unthemed tab
  6012. ((SessionsPageControl->PageCount > 0) &&
  6013. (dynamic_cast<TThemeTabSheet *>(SessionsPageControl->Pages[SessionsPageControl->PageCount - 1]) == NULL)))
  6014. {
  6015. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6016. }
  6017. for (int Index = 0; Index <= TerminalList->Count; Index++)
  6018. {
  6019. TThemeTabSheet * TabSheet;
  6020. if (Index >= SessionsPageControl->PageCount)
  6021. {
  6022. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6023. TabSheet->PageControl = SessionsPageControl;
  6024. }
  6025. else
  6026. {
  6027. TabSheet = DebugNotNull(dynamic_cast<TThemeTabSheet *>(SessionsPageControl->Pages[Index]));
  6028. }
  6029. bool IsSessionTab = (Index < TerminalList->Count);
  6030. if (IsSessionTab)
  6031. {
  6032. TTerminal * Terminal = dynamic_cast<TTerminal *>(TerminalList->Objects[Index]);
  6033. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6034. UpdateSessionTab(TabSheet);
  6035. }
  6036. else
  6037. {
  6038. TabSheet->ImageIndex = FNewSessionTabImageIndex;
  6039. TabSheet->Tag = 0; // not really needed
  6040. // We know that we are at the last page, sotherwise we could not call this (it assumes that new session tab is the last one)
  6041. UpdateNewSessionTab();
  6042. }
  6043. TabSheet->ShowCloseButton = IsSessionTab;
  6044. }
  6045. }
  6046. __finally
  6047. {
  6048. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6049. }
  6050. SessionsPageControl->ActivePageIndex = ActiveTerminalIndex;
  6051. }
  6052. //---------------------------------------------------------------------------
  6053. void __fastcall TCustomScpExplorerForm::TerminalListChanged(TObject * /*Sender*/)
  6054. {
  6055. DoTerminalListChanged();
  6056. }
  6057. //---------------------------------------------------------------------------
  6058. void __fastcall TCustomScpExplorerForm::UpdateNewSessionTab()
  6059. {
  6060. TTabSheet * TabSheet = SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6061. DebugAssert(TabSheet->ImageIndex == 0);
  6062. TabSheet->Caption =
  6063. WinConfiguration->SelectiveToolbarText ?
  6064. StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewSessionAction->Caption)) :
  6065. UnicodeString();
  6066. }
  6067. //---------------------------------------------------------------------------
  6068. TTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabTerminal(TTabSheet * TabSheet)
  6069. {
  6070. return reinterpret_cast<TTerminal *>(TabSheet->Tag);
  6071. }
  6072. //---------------------------------------------------------------------------
  6073. void __fastcall TCustomScpExplorerForm::UpdateSessionTab(TTabSheet * TabSheet)
  6074. {
  6075. if (DebugAlwaysTrue(TabSheet != NULL))
  6076. {
  6077. TManagedTerminal * ManagedTerminal =
  6078. dynamic_cast<TManagedTerminal *>(GetSessionTabTerminal(TabSheet));
  6079. if (DebugAlwaysTrue(ManagedTerminal != NULL))
  6080. {
  6081. TColor Color = (ManagedTerminal == FTerminal) ? FSessionColor : ManagedTerminal->StateData->Color;
  6082. TabSheet->ImageIndex = AddSessionColor(Color);
  6083. UnicodeString TabCaption = TTerminalManager::Instance()->GetTerminalTitle(ManagedTerminal, true);
  6084. TabSheet->Caption = SessionsPageControl->FormatCaptionWithCloseButton(TabCaption);
  6085. TThemeTabSheet * ThemeTabSheet = dynamic_cast<TThemeTabSheet *>(TabSheet);
  6086. if (DebugAlwaysTrue(ThemeTabSheet != NULL))
  6087. {
  6088. ThemeTabSheet->Shadowed = !ManagedTerminal->Active;
  6089. }
  6090. }
  6091. }
  6092. }
  6093. //---------------------------------------------------------------------------
  6094. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6095. {
  6096. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6097. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->ActivePage);
  6098. bool Result = (Terminal != NULL);
  6099. if (Result)
  6100. {
  6101. TTerminalManager::Instance()->ActiveTerminal = Terminal;
  6102. }
  6103. else
  6104. {
  6105. try
  6106. {
  6107. NewSession(false);
  6108. }
  6109. __finally
  6110. {
  6111. DoTerminalListChanged();
  6112. }
  6113. FSessionsPageControlNewSessionTime = Now();
  6114. }
  6115. return Result;
  6116. }
  6117. //---------------------------------------------------------------------------
  6118. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6119. {
  6120. SessionTabSwitched();
  6121. }
  6122. //---------------------------------------------------------------------------
  6123. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6124. {
  6125. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6126. DebugAssert(TransferList != NULL);
  6127. UnicodeString Name;
  6128. if (TransferList->ItemIndex <= 0)
  6129. {
  6130. Name = L"";
  6131. }
  6132. else
  6133. {
  6134. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  6135. }
  6136. if (FCopyParamAutoSelected.IsEmpty())
  6137. {
  6138. // if previous preset was not autoselected, make new preset the "default"
  6139. FCopyParamDefault = Name;
  6140. }
  6141. GUIConfiguration->CopyParamCurrent = Name;
  6142. }
  6143. //---------------------------------------------------------------------------
  6144. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  6145. {
  6146. // sanity check
  6147. bool ExistingPreset =
  6148. (FTransferListHoverIndex >= 0) &&
  6149. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  6150. DebugAssert(ExistingPreset);
  6151. if (ExistingPreset)
  6152. {
  6153. HDC DC = GetDC(0);
  6154. TCanvas * Canvas = new TCanvas();
  6155. try
  6156. {
  6157. Canvas->Handle = DC;
  6158. Canvas->Font = GetToolbarFont(this);
  6159. UnicodeString Name;
  6160. if (FTransferListHoverIndex == 0)
  6161. {
  6162. Name = L"";
  6163. }
  6164. else
  6165. {
  6166. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  6167. }
  6168. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  6169. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  6170. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  6171. static_cast<TObject*>(GetComponent(fcTransferList)));
  6172. UnicodeString InfoStr =
  6173. GUIConfiguration->CopyParamPreset[Name].
  6174. GetInfoStr(L"; ",
  6175. FLAGMASK(((Terminal != NULL) && Terminal->Active), Terminal->UsableCopyParamAttrs(0).General));
  6176. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  6177. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  6178. {
  6179. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  6180. {
  6181. InfoStr.SetLength(InfoStr.Length() - 1);
  6182. }
  6183. InfoStr += Ellipsis;
  6184. }
  6185. // UpdateCaption does not cause invalidation of whole submenu, while
  6186. // setting Caption property does.
  6187. // also it probably does not resize the label, even if necessary
  6188. // (we do not want that anyway)
  6189. TransferLabel->UpdateCaption(InfoStr);
  6190. }
  6191. __finally
  6192. {
  6193. Canvas->Handle = NULL;
  6194. ReleaseDC(0, DC);
  6195. delete Canvas;
  6196. }
  6197. }
  6198. }
  6199. //---------------------------------------------------------------------------
  6200. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  6201. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  6202. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  6203. {
  6204. if (FTransferListHoverIndex != AHoverIndex)
  6205. {
  6206. FTransferListHoverIndex = AHoverIndex;
  6207. UpdateTransferLabel();
  6208. }
  6209. }
  6210. //---------------------------------------------------------------------------
  6211. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  6212. {
  6213. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  6214. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  6215. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  6216. {
  6217. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  6218. {
  6219. OpenDirectory(GetSide(osCurrent));
  6220. Message.Result = 1;
  6221. }
  6222. else
  6223. {
  6224. TForm::Dispatch(&Message);
  6225. }
  6226. }
  6227. else
  6228. {
  6229. TForm::Dispatch(&Message);
  6230. }
  6231. }
  6232. //---------------------------------------------------------------------------
  6233. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  6234. {
  6235. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  6236. if ((FIgnoreNextDialogChar != 0) &&
  6237. (toupper(Message.CharCode) == toupper(FIgnoreNextDialogChar)))
  6238. {
  6239. Message.Result = 1;
  6240. }
  6241. else
  6242. {
  6243. TForm::Dispatch(&Message);
  6244. }
  6245. FIgnoreNextDialogChar = 0;
  6246. }
  6247. //---------------------------------------------------------------------------
  6248. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  6249. {
  6250. // The four low-order bits are used internally by Windows
  6251. unsigned int Cmd = (Message.WParam & 0xFFF0);
  6252. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  6253. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  6254. // 61730 - restore thru double click - undocumented
  6255. // 61490 - maximize thru double click - undocumented
  6256. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  6257. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  6258. {
  6259. SysResizing(Cmd);
  6260. }
  6261. TForm::Dispatch(&Message);
  6262. }
  6263. //---------------------------------------------------------------------------
  6264. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  6265. {
  6266. // We were actually never able to make ENDSESSION_CRITICAL happen.
  6267. // Also there no point returning TRUE as we are not able to
  6268. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  6269. // Hence the process termination might be safer :)
  6270. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  6271. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  6272. {
  6273. Message.Result = FALSE;
  6274. }
  6275. else
  6276. {
  6277. Message.Result = TRUE;
  6278. }
  6279. // Do not call default handling as that triggers OnCloseQuery,
  6280. // where our implementation will popup confirmation dialogs, what we do not want,
  6281. // as per Vista guidelines:
  6282. // https://docs.microsoft.com/en-us/windows/desktop/shutdown/shutting-down
  6283. }
  6284. //---------------------------------------------------------------------------
  6285. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  6286. {
  6287. if (Message.EndSession && IsApplicationMinimized())
  6288. {
  6289. // WORKAROUND
  6290. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  6291. // when it receives WM_ENDSESSION,
  6292. // but that sometimes (particularly when application is minimized) cause crashes.
  6293. // Crash popups message that blocks log off.
  6294. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  6295. // so we call ExitProcess() immediately, not even trying to cleanup.
  6296. // It still causes beep, so there's likely some popup, but it does not block
  6297. // log off.
  6298. ExitProcess(0);
  6299. }
  6300. TForm::Dispatch(&Message);
  6301. }
  6302. #ifdef _DEBUG
  6303. //---------------------------------------------------------------------------
  6304. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  6305. {
  6306. TForm::Dispatch(&Message);
  6307. }
  6308. #endif
  6309. //---------------------------------------------------------------------------
  6310. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  6311. {
  6312. }
  6313. //---------------------------------------------------------------------------
  6314. void __fastcall TCustomScpExplorerForm::DoShow()
  6315. {
  6316. // only now are the controls resized finally, so the size constraints
  6317. // will not conflict with possibly very small window size
  6318. RestoreFormParams();
  6319. FixControlsPlacement();
  6320. if (Position == poDefaultPosOnly)
  6321. {
  6322. CutFormToDesktop(this);
  6323. }
  6324. TForm::DoShow();
  6325. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  6326. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  6327. if (Terminal == NULL)
  6328. {
  6329. StartingDisconnected();
  6330. }
  6331. UpdatePixelsPerInchMainWindowCounter();
  6332. FShowing = true;
  6333. }
  6334. //---------------------------------------------------------------------------
  6335. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  6336. {
  6337. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  6338. }
  6339. //---------------------------------------------------------------------------
  6340. void __fastcall TCustomScpExplorerForm::StartingDisconnected()
  6341. {
  6342. DoTerminalListChanged();
  6343. }
  6344. //---------------------------------------------------------------------------
  6345. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  6346. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  6347. TNotifyEvent OnBalloonClick, TObject * UserData)
  6348. {
  6349. bool Do;
  6350. UnicodeString Message;
  6351. if (E == NULL)
  6352. {
  6353. Message = Str;
  6354. Do = true;
  6355. }
  6356. else
  6357. {
  6358. Do = ExceptionMessage(E, Message);
  6359. }
  6360. if (Do && WinConfiguration->BalloonNotifications)
  6361. {
  6362. UnicodeString Title;
  6363. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  6364. {
  6365. Message = TrimLeft(Message);
  6366. }
  6367. else
  6368. {
  6369. Message = UnformatMessage(Message);
  6370. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  6371. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  6372. Title = LoadResourceString(Captions[Type]);
  6373. if (Terminal != NULL)
  6374. {
  6375. Title = FORMAT(L"%s - %s",
  6376. (TTerminalManager::Instance()->GetTerminalTitle(Terminal, true), Title));
  6377. }
  6378. }
  6379. if (Seconds == 0)
  6380. {
  6381. Seconds = WinConfiguration->NotificationsTimeout;
  6382. }
  6383. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  6384. }
  6385. }
  6386. //---------------------------------------------------------------------------
  6387. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  6388. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  6389. UnicodeString HelpKeyword, const TMessageParams * Params,
  6390. TTerminal * Terminal)
  6391. {
  6392. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  6393. (FOnFeedSynchronizeError != NULL)) &&
  6394. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  6395. {
  6396. if (FOnFeedSynchronizeError != NULL)
  6397. {
  6398. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  6399. }
  6400. else
  6401. {
  6402. DebugAssert(FErrorList != NULL);
  6403. TStringList * MoreMessagesCopy = NULL;
  6404. if (MoreMessages)
  6405. {
  6406. MoreMessagesCopy = new TStringList();
  6407. MoreMessagesCopy->Assign(MoreMessages);
  6408. }
  6409. FErrorList->AddObject(Message, MoreMessagesCopy);
  6410. }
  6411. PopupTrayBalloon(Terminal, Message, Type);
  6412. return ContinueAnswer(Answers);
  6413. }
  6414. else
  6415. {
  6416. bool UseBalloon = FTrayIcon->Visible;
  6417. if (UseBalloon)
  6418. {
  6419. PopupTrayBalloon(Terminal, Message, Type);
  6420. }
  6421. unsigned int Result;
  6422. try
  6423. {
  6424. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  6425. }
  6426. __finally
  6427. {
  6428. // cancel only balloon we popped up, otherwise we may cancel notification
  6429. // balloon that was there before the message dialog
  6430. // (such as "dd confirmation opt in balloon)
  6431. if (UseBalloon)
  6432. {
  6433. FTrayIcon->CancelBalloon();
  6434. }
  6435. }
  6436. return Result;
  6437. }
  6438. }
  6439. //---------------------------------------------------------------------------
  6440. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  6441. TTerminal * Terminal, Exception * E)
  6442. {
  6443. if (FTrayIcon->Visible)
  6444. {
  6445. PopupTrayBalloon(Terminal, L"", qtError, E);
  6446. }
  6447. // particularly prevent opening new session from jump list,
  6448. // while exception is shown
  6449. NonVisualDataModule->StartBusy();
  6450. try
  6451. {
  6452. ShowExtendedExceptionEx(Terminal, E);
  6453. }
  6454. __finally
  6455. {
  6456. NonVisualDataModule->EndBusy();
  6457. FTrayIcon->CancelBalloon();
  6458. }
  6459. }
  6460. //---------------------------------------------------------------------------
  6461. void __fastcall TCustomScpExplorerForm::TerminalReady()
  6462. {
  6463. // cannot rely on active page being page for active terminal,
  6464. // as it can happen that active page is the "new session" page
  6465. // (e.g. when reconnecting active terminal, while login dialog
  6466. // invoked from "new session" page is modal)
  6467. int ActiveTerminalIndex = TTerminalManager::Instance()->ActiveTerminalIndex;
  6468. UpdateSessionTab(SessionsPageControl->Pages[ActiveTerminalIndex]);
  6469. }
  6470. //---------------------------------------------------------------------------
  6471. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  6472. TTerminal * Terminal, Exception * E)
  6473. {
  6474. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  6475. if (!Terminal->Active)
  6476. {
  6477. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  6478. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  6479. {
  6480. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  6481. }
  6482. }
  6483. }
  6484. //---------------------------------------------------------------------------
  6485. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  6486. UnicodeString Message, TQueryType Type,
  6487. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  6488. {
  6489. if ((E == NULL) ||
  6490. ExceptionMessage(E, Message))
  6491. {
  6492. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  6493. if (Important)
  6494. {
  6495. Seconds *= 5;
  6496. }
  6497. UnicodeString NoteMessage(UnformatMessage(Message));
  6498. if (Terminal != NULL)
  6499. {
  6500. NoteMessage = FORMAT(L"%s: %s",
  6501. (TTerminalManager::Instance()->GetTerminalTitle(Terminal, true), NoteMessage));
  6502. }
  6503. if (WinConfiguration->BalloonNotifications)
  6504. {
  6505. AddNote(NoteMessage);
  6506. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  6507. }
  6508. else
  6509. {
  6510. FlashOnBackground();
  6511. PostNote(NoteMessage, Seconds, OnClick, UserData);
  6512. }
  6513. }
  6514. }
  6515. //---------------------------------------------------------------------------
  6516. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  6517. {
  6518. RestoreApp();
  6519. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  6520. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  6521. !NonVisualDataModule->Busy)
  6522. {
  6523. TTerminal * Terminal = TerminalNoteData->Terminal;
  6524. TTerminalManager::Instance()->ActiveTerminal = Terminal;
  6525. if (!ComponentVisible[fcQueueView])
  6526. {
  6527. ToggleQueueVisibility();
  6528. GoToQueue();
  6529. }
  6530. }
  6531. }
  6532. //---------------------------------------------------------------------------
  6533. void __fastcall TCustomScpExplorerForm::QueueEvent(TTerminal * ATerminal,
  6534. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  6535. {
  6536. TManagedTerminal * ManagedTerminal = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  6537. UnicodeString Message;
  6538. TNotifyEvent OnClick = NULL;
  6539. TObject * UserData = NULL;
  6540. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  6541. switch (Event)
  6542. {
  6543. case qeEmptyButMonitored:
  6544. if ((ATerminal != Terminal) || QueueInvisible)
  6545. {
  6546. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  6547. OnClick = QueueEmptyNoteClicked;
  6548. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  6549. TerminalNoteData->Terminal = ATerminal;
  6550. UserData = TerminalNoteData;
  6551. }
  6552. break;
  6553. case qeEmpty:
  6554. OperationComplete(ManagedTerminal->QueueOperationStart);
  6555. break;
  6556. case qePendingUserAction:
  6557. if ((ATerminal != Terminal) ||
  6558. (QueueInvisible && !IsQueueAutoPopup()))
  6559. {
  6560. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  6561. }
  6562. break;
  6563. default:
  6564. DebugFail();
  6565. }
  6566. if (!Message.IsEmpty())
  6567. {
  6568. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  6569. }
  6570. }
  6571. //---------------------------------------------------------------------------
  6572. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  6573. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  6574. {
  6575. if (FDDExtMapFile != NULL)
  6576. {
  6577. CloseHandle(FDDExtMapFile);
  6578. FDDExtMapFile = NULL;
  6579. }
  6580. if (WinConfiguration->DDFakeFile)
  6581. {
  6582. DDFakeFileInitDrag(FileList, Created);
  6583. }
  6584. }
  6585. //---------------------------------------------------------------------------
  6586. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  6587. {
  6588. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  6589. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  6590. {
  6591. FFakeFileDropTarget = FileName;
  6592. }
  6593. }
  6594. //---------------------------------------------------------------------------
  6595. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  6596. {
  6597. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  6598. if (!ForceDirectories(ApiPath(Result)))
  6599. {
  6600. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  6601. }
  6602. FileSetAttr(ApiPath(Result), faHidden);
  6603. return Result;
  6604. }
  6605. //---------------------------------------------------------------------------
  6606. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  6607. bool & Created)
  6608. {
  6609. FFakeFileDropTarget = UnicodeString();
  6610. FDragFakeDirectory = CreateFakeTransferDirectory();
  6611. FileList->AddItem(NULL, FDragFakeDirectory);
  6612. Created = true;
  6613. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  6614. {
  6615. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  6616. }
  6617. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  6618. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  6619. {
  6620. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  6621. TDragExtCommStruct* CommStruct;
  6622. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  6623. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  6624. DebugAssert(CommStruct != NULL);
  6625. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  6626. CommStruct->Dragging = true;
  6627. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  6628. LENOF(CommStruct->DropDest));
  6629. NULL_TERMINATE(CommStruct->DropDest);
  6630. UnmapViewOfFile(CommStruct);
  6631. }
  6632. }
  6633. //---------------------------------------------------------------------------
  6634. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  6635. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  6636. {
  6637. bool Result;
  6638. if (Sender == RemoteDirView)
  6639. {
  6640. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  6641. }
  6642. else
  6643. {
  6644. DebugAssert(Sender == RemoteDriveView);
  6645. TStrings * FileList = RemoteDriveView->DragFileList();
  6646. try
  6647. {
  6648. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  6649. }
  6650. __finally
  6651. {
  6652. delete FileList;
  6653. }
  6654. }
  6655. if (FDDTargetControl == RemoteDriveView)
  6656. {
  6657. RemoteDriveView->UpdateDropTarget();
  6658. }
  6659. // foRemoteMove happens when file/dir is dragged within the remote tree view
  6660. // or from tree view to dir view.
  6661. // foMove happens when file/dir is dragged from remote tree view outside of
  6662. // application via dragex
  6663. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  6664. (DropSourceControl == RemoteDriveView))
  6665. {
  6666. RemoteDriveView->UpdateDropSource();
  6667. }
  6668. return Result;
  6669. }
  6670. //---------------------------------------------------------------------------
  6671. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  6672. {
  6673. // This also handles drops of remote files to queue.
  6674. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  6675. SAFE_DESTROY(FDDFileList);
  6676. if (!FFakeFileDropTarget.IsEmpty())
  6677. {
  6678. RemoveDir(ApiPath(FFakeFileDropTarget));
  6679. }
  6680. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  6681. {
  6682. try
  6683. {
  6684. TDragResult DDResult = (Sender == RemoteDirView) ?
  6685. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  6686. // Focus is moved to the target application,
  6687. // but as we are going to present the UI, we need to steal the focus back.
  6688. // This most likely won't work though (windows does not allow application
  6689. // to steal focus most of the time)
  6690. Application->BringToFront();
  6691. // On older version of Windows we never got drMove here, see also comment below.
  6692. // On Windows 10, we get the "move".
  6693. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  6694. {
  6695. UnicodeString TargetDirectory;
  6696. TFileOperation Operation;
  6697. // drInvalid may mean drMove, see comment below
  6698. switch (DDResult)
  6699. {
  6700. case drCopy:
  6701. Operation = foCopy;
  6702. break;
  6703. case drMove:
  6704. Operation = foMove;
  6705. break;
  6706. default:
  6707. DebugFail();
  6708. case drInvalid:
  6709. // prefer "copy" for safety
  6710. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  6711. break;
  6712. }
  6713. TTransferOperationParam Param;
  6714. UnicodeString CounterName;
  6715. bool ForceQueue;
  6716. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  6717. {
  6718. // we get drInvalid both if d&d was intercepted by ddext,
  6719. // and when users drops on no-drop location.
  6720. // we tell the difference by existence of response from ddext,
  6721. // so we ignore absence of response in this case
  6722. if (DDResult != drInvalid)
  6723. {
  6724. // here we know that the extension is installed,
  6725. // as it is checked as soon as drag&drop starts from
  6726. // RemoteFileControlDDCreateDragFileList
  6727. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  6728. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  6729. {
  6730. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  6731. }
  6732. else
  6733. {
  6734. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  6735. }
  6736. }
  6737. }
  6738. else
  6739. {
  6740. // download using fake file
  6741. Param.Temp = false;
  6742. Param.DragDrop = true;
  6743. if (ForceQueue)
  6744. {
  6745. Param.Queue = asOn;
  6746. }
  6747. if (Sender == RemoteDirView)
  6748. {
  6749. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  6750. }
  6751. if (RemoteFileControlFileOperation(Sender, Operation,
  6752. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  6753. {
  6754. Configuration->Usage->Inc(CounterName);
  6755. }
  6756. }
  6757. }
  6758. }
  6759. __finally
  6760. {
  6761. CloseHandle(FDDExtMapFile);
  6762. FDDExtMapFile = NULL;
  6763. delete FDragFakeMonitors;
  6764. FDragFakeMonitors = NULL;
  6765. RemoveDir(ApiPath(FDragFakeDirectory));
  6766. FDragFakeDirectory = L"";
  6767. FFakeFileDropTarget = UnicodeString();
  6768. }
  6769. }
  6770. if (FDragDropSshTerminate.get() != NULL)
  6771. {
  6772. FDragDropSshTerminate->Rethrow();
  6773. }
  6774. }
  6775. //---------------------------------------------------------------------------
  6776. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  6777. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  6778. {
  6779. // Remember drop effect so we know (when user drops files), if we copy or move
  6780. FLastDropEffect = dwEffect;
  6781. }
  6782. //---------------------------------------------------------------------------
  6783. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  6784. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  6785. {
  6786. bool Result;
  6787. if (FDDTargetControl == QueueView3)
  6788. {
  6789. Directory = DefaultDownloadTargetDirectory();
  6790. Result = true;
  6791. CounterName = L"DownloadsDragDropQueue";
  6792. ForceQueue = true;
  6793. }
  6794. else if (!FFakeFileDropTarget.IsEmpty())
  6795. {
  6796. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  6797. Result = true;
  6798. ForceQueue = false;
  6799. CounterName = L"DownloadsDragDropFakeFile";
  6800. }
  6801. else
  6802. {
  6803. ForceQueue = false;
  6804. Enabled = false;
  6805. try
  6806. {
  6807. int Timer = 0;
  6808. Result = false;
  6809. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  6810. {
  6811. {
  6812. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  6813. TDragExtCommStruct* CommStruct;
  6814. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  6815. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  6816. DebugAssert(CommStruct != NULL);
  6817. Result = !CommStruct->Dragging;
  6818. if (Result)
  6819. {
  6820. Directory = ExtractFilePath(CommStruct->DropDest);
  6821. CounterName = L"DownloadsDragDropExternalExt";
  6822. }
  6823. UnmapViewOfFile(CommStruct);
  6824. }
  6825. if (!Result)
  6826. {
  6827. Sleep(50);
  6828. Timer += 50;
  6829. Application->ProcessMessages();
  6830. }
  6831. }
  6832. }
  6833. __finally
  6834. {
  6835. Enabled = true;
  6836. }
  6837. }
  6838. return Result;
  6839. }
  6840. //---------------------------------------------------------------------------
  6841. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  6842. const UnicodeString TempDir, int SecDelay)
  6843. {
  6844. TDateTime Alarm = Now() + (double)((double)SecDelay*OneMillisecond);
  6845. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  6846. if (FDelayedDeletionTimer == NULL)
  6847. {
  6848. DebugAssert(HandleAllocated());
  6849. FDelayedDeletionTimer = new TTimer(this);
  6850. FDelayedDeletionTimer->Interval = 10000;
  6851. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  6852. }
  6853. else
  6854. {
  6855. FDelayedDeletionTimer->Enabled = true;
  6856. }
  6857. }
  6858. //---------------------------------------------------------------------------
  6859. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  6860. {
  6861. DebugAssert(FDelayedDeletionList != NULL);
  6862. TDateTime N = Now();
  6863. TDateTime Alert;
  6864. UnicodeString Directory;
  6865. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  6866. {
  6867. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  6868. if ((N >= Alert) || (Sender == NULL))
  6869. {
  6870. Directory = FDelayedDeletionList->Strings[Index];
  6871. if (DeleteDirectory(ExcludeTrailingBackslash(Directory)))
  6872. {
  6873. FDelayedDeletionList->Delete(Index);
  6874. }
  6875. }
  6876. }
  6877. if (FDelayedDeletionList->Count == 0)
  6878. {
  6879. FDelayedDeletionTimer->Enabled = false;
  6880. }
  6881. }
  6882. //---------------------------------------------------------------------------
  6883. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  6884. {
  6885. if (IsFileControl(FDDTargetControl, osRemote) ||
  6886. (FDDTargetControl == SessionsPageControl))
  6887. {
  6888. TTerminal * TargetTerminal = NULL;
  6889. TFileOperation Operation = foNone;
  6890. if (FDDTargetControl == SessionsPageControl)
  6891. {
  6892. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  6893. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  6894. // do not allow dropping on the "+" tab
  6895. TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  6896. if (TargetTerminal != NULL)
  6897. {
  6898. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  6899. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  6900. {
  6901. Operation = foRemoteMove;
  6902. }
  6903. else
  6904. {
  6905. Operation = foRemoteCopy;
  6906. }
  6907. }
  6908. }
  6909. else
  6910. {
  6911. if (FLastDropEffect == DROPEFFECT_MOVE)
  6912. {
  6913. Operation = foRemoteMove;
  6914. }
  6915. else if (FLastDropEffect == DROPEFFECT_COPY)
  6916. {
  6917. Operation = foRemoteCopy;
  6918. }
  6919. }
  6920. if (Operation != foNone)
  6921. {
  6922. RemoteFileControlFileOperation(DropSourceControl,
  6923. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  6924. }
  6925. // abort drag&drop
  6926. Abort();
  6927. }
  6928. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  6929. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  6930. (FDDTargetControl != QueueView3))
  6931. {
  6932. DebugAssert(!FDragTempDir.IsEmpty());
  6933. TTransferType Type;
  6934. UnicodeString TempDir = FDragTempDir;
  6935. // We clear FDragTempDir before calling
  6936. // just in case it fail (raises exception)
  6937. FDragTempDir = L"";
  6938. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  6939. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  6940. // empty directory parameter means temp directory -> don't display it!
  6941. UnicodeString TargetDir = L"";
  6942. int Options = 0;
  6943. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  6944. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  6945. {
  6946. Abort();
  6947. }
  6948. // TargetDir is set when dropped on local file control
  6949. // (this was workaround for legacy dirview event handling, now it should be
  6950. // made prettier)
  6951. if (TargetDir.IsEmpty())
  6952. {
  6953. TargetDir = TempDir;
  6954. if (ForceDirectories(ApiPath(TargetDir)))
  6955. {
  6956. DebugAssert(Terminal && !TargetDir.IsEmpty());
  6957. FPendingTempSpaceWarn = true;
  6958. try
  6959. {
  6960. FDragDropOperation = true;
  6961. int Params = cpTemporary |
  6962. (Type == ttMove ? cpDelete : 0);
  6963. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  6964. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  6965. }
  6966. __finally
  6967. {
  6968. FDragDropOperation = false;
  6969. FPendingTempSpaceWarn = false;
  6970. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  6971. }
  6972. }
  6973. else
  6974. {
  6975. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  6976. }
  6977. }
  6978. }
  6979. }
  6980. //---------------------------------------------------------------------------
  6981. void __fastcall TCustomScpExplorerForm::DDDownload(
  6982. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params)
  6983. {
  6984. TAutoBatch AutoBatch(this);
  6985. UpdateCopyParamCounters(*CopyParam);
  6986. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  6987. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  6988. {
  6989. RemoteDriveView->UpdateDropSource();
  6990. }
  6991. }
  6992. //---------------------------------------------------------------------------
  6993. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  6994. {
  6995. public:
  6996. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  6997. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  6998. {
  6999. }
  7000. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7001. {
  7002. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7003. TDataObjectFilesEx::AllowData(FormatEtc);
  7004. }
  7005. };
  7006. //---------------------------------------------------------------------------
  7007. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7008. TObject * Sender, TDataObject *& DataObject)
  7009. {
  7010. if (FDDExtMapFile != NULL)
  7011. {
  7012. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7013. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7014. {
  7015. Abort();
  7016. }
  7017. if (FileList->Count > 0)
  7018. {
  7019. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7020. if (!FilesObject->IsValid(true, true))
  7021. {
  7022. FilesObject->_Release();
  7023. }
  7024. else
  7025. {
  7026. DataObject = FilesObject;
  7027. }
  7028. }
  7029. }
  7030. }
  7031. //---------------------------------------------------------------------------
  7032. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7033. {
  7034. DebugFail();
  7035. }
  7036. //---------------------------------------------------------------------------
  7037. void __fastcall TCustomScpExplorerForm::GoToTree()
  7038. {
  7039. ComponentVisible[fcRemoteTree] = true;
  7040. RemoteDriveView->SetFocus();
  7041. }
  7042. //---------------------------------------------------------------------------
  7043. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7044. TPanelExport Export)
  7045. {
  7046. TCustomDirView * DirView = this->DirView(Side);
  7047. std::unique_ptr<TStrings> ExportData(new TStringList());
  7048. switch (Export)
  7049. {
  7050. case pePath:
  7051. ExportData->Add(DirView->PathName);
  7052. break;
  7053. case peFileList:
  7054. case peFullFileList:
  7055. {
  7056. bool FullPath = (Export == peFullFileList);
  7057. DirView->CreateFileList(false, FullPath, ExportData.get());
  7058. for (int Index = 0; Index < ExportData->Count; Index++)
  7059. {
  7060. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7061. {
  7062. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7063. }
  7064. }
  7065. }
  7066. break;
  7067. default:
  7068. DebugFail();
  7069. }
  7070. return ExportData.release();
  7071. }
  7072. //---------------------------------------------------------------------------
  7073. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7074. TPanelExport Export, TPanelExportDestination Destination)
  7075. {
  7076. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7077. PanelExportStore(Side, Export, Destination, ExportData.get());
  7078. }
  7079. //---------------------------------------------------------------------------
  7080. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7081. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7082. TStrings * ExportData)
  7083. {
  7084. if (Destination == pedClipboard)
  7085. {
  7086. TInstantOperationVisualizer Visualizer;
  7087. CopyToClipboard(ExportData);
  7088. }
  7089. else
  7090. {
  7091. DebugFail();
  7092. }
  7093. }
  7094. //---------------------------------------------------------------------------
  7095. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  7096. {
  7097. TCustomDirView * DirView = this->DirView(Side);
  7098. UnicodeString Mask = DirView->Mask;
  7099. if (DoFilterMaskDialog(DirView, Mask))
  7100. {
  7101. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  7102. Configuration->Usage->Inc(L"Filters");
  7103. }
  7104. }
  7105. //---------------------------------------------------------------------------
  7106. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  7107. {
  7108. return FQueueController->DefaultOperation();
  7109. }
  7110. //---------------------------------------------------------------------------
  7111. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  7112. TQueueOperation Operation, void ** Param)
  7113. {
  7114. switch (Operation)
  7115. {
  7116. case qoPreferences:
  7117. return true;
  7118. case qoGoTo:
  7119. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  7120. case qoOnceEmpty:
  7121. return !FQueueController->Empty;
  7122. default:
  7123. return FQueueController->AllowOperation(Operation, Param);
  7124. }
  7125. }
  7126. //---------------------------------------------------------------------------
  7127. void __fastcall TCustomScpExplorerForm::GoToQueue()
  7128. {
  7129. if (DebugAlwaysTrue(QueueView3->Visible))
  7130. {
  7131. QueueView3->SetFocus();
  7132. }
  7133. }
  7134. //---------------------------------------------------------------------------
  7135. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  7136. TQueueOperation Operation, void * Param)
  7137. {
  7138. if (Operation == qoGoTo)
  7139. {
  7140. GoToQueue();
  7141. }
  7142. else if (Operation == qoPreferences)
  7143. {
  7144. PreferencesDialog(pmQueue);
  7145. }
  7146. else
  7147. {
  7148. FQueueController->ExecuteOperation(Operation, Param);
  7149. }
  7150. }
  7151. //---------------------------------------------------------------------------
  7152. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  7153. {
  7154. return (Queue != NULL) && Queue->Enabled;
  7155. }
  7156. //---------------------------------------------------------------------------
  7157. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  7158. {
  7159. DebugAssert(Queue != NULL);
  7160. if (Queue != NULL)
  7161. {
  7162. Queue->Enabled = !Queue->Enabled;
  7163. }
  7164. }
  7165. //---------------------------------------------------------------------------
  7166. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  7167. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  7168. {
  7169. FQueueActedItem = QueueView3->ItemFocused;
  7170. }
  7171. //---------------------------------------------------------------------------
  7172. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  7173. {
  7174. return TopDock->Height + QueueSplitter->Height;
  7175. }
  7176. //---------------------------------------------------------------------------
  7177. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  7178. TObject * /*Sender*/, int & NewSize, bool & Accept)
  7179. {
  7180. // when queue is hidden by double-clicking splitter, stray attempt to
  7181. // resize the panel with strange value arrives, make sure it is ignored
  7182. if (ComponentVisible[fcQueueView])
  7183. {
  7184. int HeightLimit = ClientHeight - GetStaticComponentsHeight() -
  7185. RemotePanel->Constraints->MinHeight;
  7186. if (NewSize > HeightLimit)
  7187. {
  7188. NewSize = HeightLimit;
  7189. }
  7190. }
  7191. else
  7192. {
  7193. Accept = false;
  7194. }
  7195. }
  7196. //---------------------------------------------------------------------------
  7197. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  7198. TDragObject *& /*DragObject*/)
  7199. {
  7200. FQueueActedItem = QueueView3->ItemFocused;
  7201. }
  7202. //---------------------------------------------------------------------------
  7203. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  7204. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  7205. {
  7206. Accept = true;
  7207. if (Source == QueueView3)
  7208. {
  7209. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  7210. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  7211. if (Accept)
  7212. {
  7213. TQueueItemProxy * QueueItem;
  7214. TQueueItemProxy * DestQueueItem;
  7215. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  7216. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  7217. Accept = (QueueItem != DestQueueItem) &&
  7218. (QueueItem->Status == TQueueItem::qsPending) &&
  7219. (DestQueueItem->Status == TQueueItem::qsPending);
  7220. }
  7221. }
  7222. }
  7223. //---------------------------------------------------------------------------
  7224. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  7225. TObject * /*Source*/, int /*X*/, int /*Y*/)
  7226. {
  7227. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  7228. {
  7229. TQueueItemProxy * QueueItem;
  7230. TQueueItemProxy * DestQueueItem;
  7231. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  7232. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  7233. QueueItem->Move(DestQueueItem);
  7234. }
  7235. }
  7236. //---------------------------------------------------------------------------
  7237. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  7238. {
  7239. if ((QueueView3->ItemFocused == NULL) &&
  7240. (QueueView3->Items->Count > 0))
  7241. {
  7242. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  7243. }
  7244. QueueLabelUpdateStatus();
  7245. }
  7246. //---------------------------------------------------------------------------
  7247. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  7248. {
  7249. QueueLabelUpdateStatus();
  7250. }
  7251. //---------------------------------------------------------------------------
  7252. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  7253. {
  7254. QueueLabel->UpdateStatus();
  7255. }
  7256. //---------------------------------------------------------------------------
  7257. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  7258. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  7259. {
  7260. if (Selected)
  7261. {
  7262. NonVisualDataModule->UpdateNonVisibleActions();
  7263. }
  7264. }
  7265. //---------------------------------------------------------------------------
  7266. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  7267. {
  7268. TDragDropFilesEx * Result = NULL;
  7269. if (Sender == SessionsPageControl)
  7270. {
  7271. Result = FSessionsDragDropFilesEx;
  7272. }
  7273. else if (Sender == QueueView3)
  7274. {
  7275. Result = FQueueDragDropFilesEx;
  7276. }
  7277. else
  7278. {
  7279. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  7280. if (DirView != NULL)
  7281. {
  7282. Result = DirView->DragDropFilesEx;
  7283. }
  7284. else
  7285. {
  7286. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  7287. if (DriveView != NULL)
  7288. {
  7289. Result = DriveView->DragDropFilesEx;
  7290. }
  7291. }
  7292. }
  7293. DebugAssert(Result != NULL);
  7294. return Result;
  7295. }
  7296. //---------------------------------------------------------------------------
  7297. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  7298. {
  7299. return (DView->SelCount == DView->FilesCount);
  7300. }
  7301. //---------------------------------------------------------------------------
  7302. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  7303. {
  7304. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  7305. }
  7306. //---------------------------------------------------------------------------
  7307. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  7308. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  7309. {
  7310. TFileOperation Operation;
  7311. switch (Effect)
  7312. {
  7313. case DROPEFFECT_MOVE:
  7314. Operation = foMove;
  7315. break;
  7316. case DROPEFFECT_COPY:
  7317. // occures on WinXP (reported by user)
  7318. default:
  7319. Operation = foCopy;
  7320. break;
  7321. };
  7322. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  7323. // see a comment in TUnixDirView::PerformItemDragDropOperation
  7324. if (DragDropFilesEx->FileList->Count > 0)
  7325. {
  7326. TStrings * FileList = new TStringList();
  7327. try
  7328. {
  7329. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  7330. {
  7331. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  7332. }
  7333. FDragDropOperation = true;
  7334. TTransferOperationParam Param;
  7335. Param.TargetDirectory = TargetPath;
  7336. // upload, no temp dirs
  7337. Param.Temp = false;
  7338. Param.DragDrop = DragDrop;
  7339. Param.Options =
  7340. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  7341. if (ForceQueue)
  7342. {
  7343. Param.Queue = asOn;
  7344. }
  7345. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  7346. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  7347. {
  7348. if (IsFileControl(DropSourceControl, osLocal))
  7349. {
  7350. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  7351. }
  7352. else
  7353. {
  7354. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  7355. }
  7356. }
  7357. }
  7358. __finally
  7359. {
  7360. FDragDropOperation = false;
  7361. delete FileList;
  7362. }
  7363. }
  7364. }
  7365. //---------------------------------------------------------------------------
  7366. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  7367. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  7368. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  7369. {
  7370. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  7371. }
  7372. //---------------------------------------------------------------------------
  7373. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  7374. TObject * Sender, int grfKeyState, int & dwEffect)
  7375. {
  7376. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  7377. if ((dwEffect != DROPEFFECT_None) &&
  7378. IsFileControl(DropSourceControl, osRemote))
  7379. {
  7380. // do not allow drop on remote panel (on free space, still allow drop on directories)
  7381. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  7382. (RemoteDirView->DropTarget == NULL))
  7383. {
  7384. dwEffect = DROPEFFECT_None;
  7385. }
  7386. else
  7387. {
  7388. if (dwEffect == DROPEFFECT_Copy)
  7389. {
  7390. bool MoveCapable = FTerminal->IsCapable[fcRemoteMove];
  7391. // currently we support copying always (at least via temporary directory);
  7392. // remove associated checks once this all proves stable and working
  7393. bool CopyCapable = true;
  7394. // if we do not support neither of operations, there's no discussion
  7395. if (!MoveCapable && !CopyCapable)
  7396. {
  7397. dwEffect = DROPEFFECT_None;
  7398. }
  7399. else
  7400. {
  7401. // The default effect inside remote panel is move,
  7402. // unless we do not support it, but support copy
  7403. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  7404. {
  7405. dwEffect = MoveCapable ? DROPEFFECT_Move : DROPEFFECT_Copy;
  7406. }
  7407. else
  7408. {
  7409. // with ctrl-down, we want copy unless it is not supported
  7410. dwEffect = CopyCapable ? DROPEFFECT_Copy : DROPEFFECT_None;
  7411. }
  7412. }
  7413. }
  7414. }
  7415. }
  7416. }
  7417. //---------------------------------------------------------------------------
  7418. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  7419. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  7420. {
  7421. if (FDDTotalSize >= 0)
  7422. {
  7423. if (File->IsDirectory)
  7424. {
  7425. FDDTotalSize = -1;
  7426. }
  7427. else
  7428. {
  7429. FDDTotalSize += File->Size;
  7430. }
  7431. }
  7432. DebugAssert(!FDragTempDir.IsEmpty());
  7433. // TODO: this is quite ineffective
  7434. // TODO: what if invalid character replacement is disabled?
  7435. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  7436. UnicodeString TransferFileName;
  7437. if (Sender == RemoteDriveView)
  7438. {
  7439. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  7440. }
  7441. else
  7442. {
  7443. TransferFileName = File->FileName;
  7444. }
  7445. FDDFileList->AddObject(TransferFileName, File);
  7446. }
  7447. //---------------------------------------------------------------------------
  7448. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  7449. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  7450. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  7451. {
  7452. // sometimes we do not get DDEnd so the list is not released
  7453. SAFE_DESTROY(FDDFileList);
  7454. FDDFileList = new TStringList();
  7455. FDragTempDir = WinConfiguration->TemporaryDir();
  7456. FDDTotalSize = 0;
  7457. FDragDropSshTerminate.reset(NULL);
  7458. }
  7459. //---------------------------------------------------------------------------
  7460. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  7461. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  7462. HRESULT & Result)
  7463. {
  7464. if (Result == DRAGDROP_S_DROP)
  7465. {
  7466. try
  7467. {
  7468. GlobalDragImageList->HideDragImage();
  7469. try
  7470. {
  7471. RemoteFileControlDDTargetDrop();
  7472. }
  7473. catch(ESshTerminate & E)
  7474. {
  7475. FDragDropSshTerminate.reset(E.Clone());
  7476. }
  7477. }
  7478. catch (Exception &E)
  7479. {
  7480. // If downloading fails we need to cancel drag&drop, otherwise
  7481. // Explorer shows error
  7482. // But by the way exception probably never reach this point as
  7483. // it's catched on way.
  7484. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  7485. Result = DRAGDROP_S_CANCEL;
  7486. ShowExtendedException(Terminal, &E);
  7487. }
  7488. }
  7489. }
  7490. //---------------------------------------------------------------------------
  7491. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  7492. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  7493. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  7494. {
  7495. TFileMasks::TParams MaskParams;
  7496. MaskParams.Size = Size;
  7497. MaskParams.Modification = Modification;
  7498. // this does not re-parse the mask if it is the same as the last time
  7499. FDirViewMatchMask = Masks;
  7500. bool ImplicitMatch;
  7501. Matches =
  7502. // RecurseInclude parameter has no effect as the Path is empty
  7503. FDirViewMatchMask.Matches(FileName, Directory, UnicodeString(L""), &MaskParams, true, ImplicitMatch) &&
  7504. (AllowImplicitMatches || !ImplicitMatch);
  7505. }
  7506. //---------------------------------------------------------------------------
  7507. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  7508. TObject * Sender, TListItem * Item, WORD & Indexes)
  7509. {
  7510. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  7511. UnicodeString Ext;
  7512. if (DirView == RemoteDirView)
  7513. {
  7514. Ext = UnixExtractFileExt(DirView->ItemFileName(Item));
  7515. }
  7516. else
  7517. {
  7518. Ext = ExtractFileExt(DirView->ItemFileName(Item));
  7519. }
  7520. if (SameText(Ext, Configuration->PartialExt))
  7521. {
  7522. Indexes |= oiPartial;
  7523. }
  7524. }
  7525. //---------------------------------------------------------------------------
  7526. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  7527. {
  7528. return
  7529. DirViewEnabled(osCurrent) &&
  7530. DirView(osCurrent)->CanPasteFromClipBoard();
  7531. }
  7532. //---------------------------------------------------------------------------
  7533. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  7534. {
  7535. bool Result = false;
  7536. if (CanPasteToDirViewFromClipBoard())
  7537. {
  7538. Result = true;
  7539. }
  7540. else
  7541. {
  7542. UnicodeString ClipboardText;
  7543. if (NonEmptyTextFromClipboard(ClipboardText))
  7544. {
  7545. if (StoredSessions->IsUrl(ClipboardText))
  7546. {
  7547. Result = true;
  7548. }
  7549. else
  7550. {
  7551. Result = DirViewEnabled(osCurrent);
  7552. }
  7553. }
  7554. }
  7555. return Result;
  7556. }
  7557. //---------------------------------------------------------------------------
  7558. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  7559. {
  7560. if (DoesClipboardContainOurFiles())
  7561. {
  7562. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  7563. {
  7564. TTerminalManager * Manager = TTerminalManager::Instance();
  7565. TTerminal * TergetTerminal = Manager->ActiveTerminal;
  7566. Manager->ActiveTerminal = FClipboardTerminal;
  7567. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TergetTerminal);
  7568. }
  7569. }
  7570. else if (CanPasteToDirViewFromClipBoard())
  7571. {
  7572. DirView(osCurrent)->PasteFromClipBoard();
  7573. }
  7574. else
  7575. {
  7576. UnicodeString ClipboardText;
  7577. if (NonEmptyTextFromClipboard(ClipboardText))
  7578. {
  7579. if (StoredSessions->IsUrl(ClipboardText))
  7580. {
  7581. NewSession(false, ClipboardText);
  7582. }
  7583. else
  7584. {
  7585. DirView(osCurrent)->Path = ClipboardText;
  7586. }
  7587. }
  7588. }
  7589. }
  7590. //---------------------------------------------------------------------------
  7591. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  7592. {
  7593. // TBD
  7594. }
  7595. //---------------------------------------------------------------------------
  7596. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  7597. {
  7598. TCustomDirView * ADirView = DirView(Side);
  7599. ADirView->SelectAll(Mode);
  7600. ADirView->SetFocus();
  7601. }
  7602. //---------------------------------------------------------------------------
  7603. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  7604. {
  7605. TCustomDirView * ADirView = DirView(Side);
  7606. TFileFilter Filter;
  7607. DefaultFileFilter(Filter);
  7608. if (DoSelectMaskDialog(ADirView, Select, Filter))
  7609. {
  7610. Configuration->Usage->Inc(L"MaskSelections");
  7611. ADirView->SelectFiles(Filter, Select);
  7612. ADirView->SetFocus();
  7613. }
  7614. }
  7615. //---------------------------------------------------------------------------
  7616. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  7617. {
  7618. TCustomDirView * ADirView = DirView(Side);
  7619. ADirView->RestoreSelectedNames();
  7620. ADirView->SetFocus();
  7621. }
  7622. //---------------------------------------------------------------------------
  7623. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  7624. {
  7625. TCustomDirView * CurrentDirView = DirView(osCurrent);
  7626. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  7627. {
  7628. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  7629. UnicodeString Ext;
  7630. if (GetSide(osCurrent) == osRemote)
  7631. {
  7632. Ext = UnixExtractFileExt(FileName);
  7633. }
  7634. else
  7635. {
  7636. Ext = ExtractFileExt(FileName);
  7637. }
  7638. if (Ext.IsEmpty())
  7639. {
  7640. Ext = L".";
  7641. }
  7642. TFileFilter Filter;
  7643. Filter.Masks = FORMAT(L"*%s", (Ext));
  7644. Filter.Directories = false;
  7645. CurrentDirView->SelectFiles(Filter, Select);
  7646. }
  7647. }
  7648. //---------------------------------------------------------------------------
  7649. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  7650. const TStatusFileInfo & FileInfo, TOperationSide Side)
  7651. {
  7652. UnicodeString Result;
  7653. if ((Side == osRemote) && (Terminal == NULL))
  7654. {
  7655. // noop
  7656. }
  7657. else
  7658. {
  7659. Result =
  7660. FMTLOAD(FILE_INFO_FORMAT,
  7661. (FormatBytes(FileInfo.SelectedSize),
  7662. FormatBytes(FileInfo.FilesSize),
  7663. FormatNumber(FileInfo.SelectedCount),
  7664. FormatNumber(FileInfo.FilesCount)));
  7665. }
  7666. return Result;
  7667. }
  7668. //---------------------------------------------------------------------------
  7669. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  7670. TTBXStatusPanel * Panel, TOperationSide Side)
  7671. {
  7672. if (Panel->Index == 1)
  7673. {
  7674. ToggleShowHiddenFiles();
  7675. }
  7676. else if (Panel->Index == 2)
  7677. {
  7678. Filter(Side);
  7679. }
  7680. }
  7681. //---------------------------------------------------------------------------
  7682. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  7683. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  7684. {
  7685. DebugAssert(!StatusBar->SimplePanel);
  7686. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  7687. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  7688. }
  7689. //---------------------------------------------------------------------------
  7690. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  7691. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  7692. {
  7693. DebugAssert(StatusBar->Panels->Count >= 3);
  7694. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  7695. if (FileInfo.HiddenCount > 0)
  7696. {
  7697. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  7698. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  7699. }
  7700. else
  7701. {
  7702. HiddenFilesPanel->ViewPriority = 0;
  7703. // not really necessary, just to cleanup no-longer-valid data
  7704. HiddenFilesPanel->Caption = L"";
  7705. }
  7706. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  7707. if (FileInfo.FilteredCount > 0)
  7708. {
  7709. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  7710. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  7711. }
  7712. else
  7713. {
  7714. FilteredFilesPanel->ViewPriority = 0;
  7715. // not really necessary, just to cleanup no-longer-valid data
  7716. FilteredFilesPanel->Caption = L"";
  7717. }
  7718. }
  7719. //---------------------------------------------------------------------------
  7720. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  7721. TObject * /*Sender*/)
  7722. {
  7723. if (RemoteDirView->Enabled)
  7724. {
  7725. RemoteDirView->SetFocus();
  7726. }
  7727. }
  7728. //---------------------------------------------------------------------------
  7729. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  7730. {
  7731. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  7732. switch (Config.Show)
  7733. {
  7734. case qvShow:
  7735. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  7736. {
  7737. Config.Show = qvHide;
  7738. }
  7739. else
  7740. {
  7741. Config.Show = Config.LastHideShow;
  7742. }
  7743. break;
  7744. case qvHideWhenEmpty:
  7745. if (ComponentVisible[fcQueueView])
  7746. {
  7747. Config.Show = qvHide;
  7748. }
  7749. else
  7750. {
  7751. Config.LastHideShow = Config.Show;
  7752. Config.Show = qvShow;
  7753. }
  7754. break;
  7755. case qvHide:
  7756. Config.LastHideShow = Config.Show;
  7757. Config.Show = qvShow;
  7758. break;
  7759. }
  7760. WinConfiguration->QueueView = Config;
  7761. }
  7762. //---------------------------------------------------------------------------
  7763. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  7764. {
  7765. UnicodeString Result;
  7766. if (FTerminal != NULL)
  7767. {
  7768. switch (WinConfiguration->PathInCaption)
  7769. {
  7770. case picShort:
  7771. Result = TTerminalManager::Instance()->GetTerminalShortPath(FTerminal);
  7772. break;
  7773. case picFull:
  7774. Result = FTerminal->CurrentDirectory;
  7775. break;
  7776. }
  7777. }
  7778. return Result;
  7779. }
  7780. //---------------------------------------------------------------------------
  7781. TColor __fastcall TCustomScpExplorerForm::DefaultPanelColor()
  7782. {
  7783. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x20, 0x20, 0x20)) : clWindow);
  7784. return Result;
  7785. }
  7786. //---------------------------------------------------------------------------
  7787. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  7788. {
  7789. TColor Result = (FSessionColor != 0 ? FSessionColor : DefaultPanelColor());
  7790. return Result;
  7791. }
  7792. //---------------------------------------------------------------------------
  7793. TColor __fastcall TCustomScpExplorerForm::PanelFontColor(TColor BackgroundColor)
  7794. {
  7795. TColor Result = (IsDarkColor(BackgroundColor) ? clWhite : clWindowText);
  7796. SetContrast(Result, BackgroundColor, 180);
  7797. return Result;
  7798. }
  7799. //---------------------------------------------------------------------------
  7800. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  7801. {
  7802. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  7803. return Result;
  7804. }
  7805. //---------------------------------------------------------------------------
  7806. void __fastcall TCustomScpExplorerForm::UpdateControls()
  7807. {
  7808. TTerminalManager::Instance()->UpdateAppTitle();
  7809. // WORAKRDOUND: Disabling list view when it is not showing yet does not set its
  7810. // background to gray on Windows 7 (works on Windows 10).
  7811. // See also EnableControl
  7812. if (Showing)
  7813. {
  7814. bool HasTerminal = (Terminal != NULL) && Terminal->Active;
  7815. if (HasTerminal)
  7816. {
  7817. // Update path when it changes
  7818. if ((SessionsPageControl->ActivePage != NULL) && (GetSessionTabTerminal(SessionsPageControl->ActivePage) == Terminal))
  7819. {
  7820. UpdateSessionTab(SessionsPageControl->ActivePage);
  7821. }
  7822. if (!RemoteDirView->Enabled)
  7823. {
  7824. RemoteDirView->Enabled = true;
  7825. if (FRemoteDirViewWasFocused)
  7826. {
  7827. ActiveControl = RemoteDirView;
  7828. }
  7829. }
  7830. RemoteDirView->Color = PanelColor();
  7831. }
  7832. else
  7833. {
  7834. if (RemoteDirView->Enabled)
  7835. {
  7836. // This is first called when the form is being constructed
  7837. // (not anymore due to Showing test above)
  7838. // but the false is overriden in the constructor later.
  7839. // An even later in TScpCommanderForm::DoShow()
  7840. FRemoteDirViewWasFocused = (ActiveControl == RemoteDirView);
  7841. RemoteDirView->Enabled = false;
  7842. RemoteDirView->Color = DisabledPanelColor();
  7843. }
  7844. }
  7845. RemoteDirView->Font->Color = PanelFontColor(RemoteDirView->Color);
  7846. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  7847. RemoteDriveView->Color = RemoteDirView->Color;
  7848. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  7849. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fsBackgroundTransfers];
  7850. QueueView3->Color = QueueView3->Enabled ? DefaultPanelColor() : DisabledPanelColor();
  7851. QueueLabelUpdateStatus();
  7852. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  7853. AllowDarkModeForWindow(RemoteDirView, UseDarkTheme);
  7854. AllowDarkModeForWindow(RemoteDriveView, UseDarkTheme);
  7855. AllowDarkModeForWindow(SessionsPageControl, UseDarkTheme);
  7856. if (QueueView3->HandleAllocated())
  7857. {
  7858. AllowDarkModeForWindow(QueueView3, UseDarkTheme);
  7859. }
  7860. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal;
  7861. }
  7862. }
  7863. //---------------------------------------------------------------------------
  7864. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  7865. {
  7866. UpdateControls();
  7867. }
  7868. //---------------------------------------------------------------------------
  7869. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  7870. TObject * Sender)
  7871. {
  7872. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  7873. DebugAssert(DirView != NULL);
  7874. DoDirViewLoaded(DirView);
  7875. TransferPresetAutoSelect();
  7876. }
  7877. //---------------------------------------------------------------------------
  7878. void __fastcall TCustomScpExplorerForm::StartUpdates()
  7879. {
  7880. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  7881. // first run after installation
  7882. if (double(Updates.LastCheck) == 0)
  7883. {
  7884. // make sure next time there will be an update (if enabled)
  7885. Updates.LastCheck = TDateTime(1);
  7886. WinConfiguration->Updates = Updates;
  7887. }
  7888. else if ((double(Updates.Period) > 0) &&
  7889. (Now() - Updates.LastCheck >= Updates.Period))
  7890. {
  7891. TThreadMethod OnUpdatesChecked = NULL;
  7892. if (!IsUWP())
  7893. {
  7894. OnUpdatesChecked = UpdatesChecked;
  7895. }
  7896. StartUpdateThread(OnUpdatesChecked);
  7897. }
  7898. }
  7899. //---------------------------------------------------------------------------
  7900. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  7901. {
  7902. UnicodeString Message;
  7903. bool New;
  7904. TQueryType Type;
  7905. GetUpdatesMessage(Message, New, Type, false);
  7906. if (!Message.IsEmpty())
  7907. {
  7908. if (New)
  7909. {
  7910. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  7911. }
  7912. if (!New && (Type != qtWarning))
  7913. {
  7914. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  7915. }
  7916. else
  7917. {
  7918. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  7919. }
  7920. if (New)
  7921. {
  7922. Configuration->Usage->Inc(L"UpdateNotifications");
  7923. }
  7924. }
  7925. }
  7926. //---------------------------------------------------------------------------
  7927. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  7928. {
  7929. RestoreApp();
  7930. bool CanDisplay = !NonVisualDataModule->Busy;
  7931. if (!CanDisplay && (Screen->ActiveForm != NULL))
  7932. {
  7933. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  7934. }
  7935. if (CanDisplay)
  7936. {
  7937. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  7938. CheckForUpdates(true);
  7939. }
  7940. else
  7941. {
  7942. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  7943. }
  7944. }
  7945. //---------------------------------------------------------------------------
  7946. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  7947. TCopyParamRuleData & Data)
  7948. {
  7949. DebugAssert(Terminal != NULL);
  7950. Data.HostName = Terminal->SessionData->HostNameExpanded;
  7951. Data.UserName = Terminal->SessionData->UserNameExpanded;
  7952. Data.RemoteDirectory = RemoteDirView->PathName;
  7953. }
  7954. //---------------------------------------------------------------------------
  7955. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  7956. {
  7957. // Terminal can be null when we are changing local directory implicitly,
  7958. // because it has been deleted, while no session is connected
  7959. // (Login dialog is open)
  7960. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  7961. {
  7962. TCopyParamRuleData Data;
  7963. GetTransferPresetAutoSelectData(Data);
  7964. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  7965. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  7966. if (CopyParamIndex < 0)
  7967. {
  7968. // there is no preset that matches autoselection
  7969. // set preset that we consider "default"
  7970. FCopyParamAutoSelected = L""; // forget last autoselected preset
  7971. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  7972. }
  7973. else
  7974. {
  7975. // there is preset matching autoselection
  7976. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  7977. if (CopyParamName == FCopyParamAutoSelected)
  7978. {
  7979. // autoselected the same preset as the last time
  7980. // make no change (i.e. preserve custom user preset, if any)
  7981. }
  7982. else
  7983. {
  7984. // autoselected the different preset then the last time (or there
  7985. // was default preset set)
  7986. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  7987. GUIConfiguration->CopyParamCurrent = CopyParamName;
  7988. }
  7989. }
  7990. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  7991. {
  7992. if (CopyParamIndex >= 0)
  7993. {
  7994. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  7995. }
  7996. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  7997. try
  7998. {
  7999. int Fmt =
  8000. (CopyParamIndex < 0) ?
  8001. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8002. COPY_PARAM_AUTOSELECTED;
  8003. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8004. Data->Message = MainInstructions(Message);
  8005. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8006. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8007. CopyParamAttrs);
  8008. if (CopyParamIndex >= 0)
  8009. {
  8010. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8011. Info = FORMAT(L"%s\n \n%s", (Info,
  8012. FMTLOAD(COPY_PARAM_RULE,
  8013. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8014. }
  8015. Data->Message += L"\n\n" + Info;
  8016. if (WinConfiguration->CopyParamAutoSelectNotice)
  8017. {
  8018. TransferPresetNoteMessage(Data, true);
  8019. }
  8020. else
  8021. {
  8022. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  8023. Data = NULL; // ownership passed
  8024. }
  8025. }
  8026. __finally
  8027. {
  8028. delete Data;
  8029. }
  8030. }
  8031. }
  8032. }
  8033. //---------------------------------------------------------------------------
  8034. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  8035. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  8036. {
  8037. DebugAssert(NoteData != NULL);
  8038. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  8039. TQueryButtonAlias Aliases[1];
  8040. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  8041. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  8042. Params.Aliases = Aliases;
  8043. Params.AliasesCount = LENOF(Aliases);
  8044. unsigned int Result =
  8045. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  8046. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  8047. switch (Result)
  8048. {
  8049. case qaNeverAskAgain:
  8050. DebugAssert(AllowNeverAskAgain);
  8051. WinConfiguration->CopyParamAutoSelectNotice = false;
  8052. break;
  8053. case qaIgnore:
  8054. PreferencesDialog(pmPresets);
  8055. break;
  8056. }
  8057. }
  8058. //---------------------------------------------------------------------------
  8059. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  8060. {
  8061. // as of now useless, as this is used for notes only, never for balloons, ...
  8062. RestoreApp();
  8063. // .. and we should never be busy here
  8064. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  8065. {
  8066. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  8067. }
  8068. }
  8069. //---------------------------------------------------------------------------
  8070. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  8071. TPreferencesMode APreferencesMode)
  8072. {
  8073. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  8074. TCopyParamRuleData Data;
  8075. if (Terminal != NULL)
  8076. {
  8077. PreferencesData.reset(new TPreferencesDialogData());
  8078. GetTransferPresetAutoSelectData(Data);
  8079. PreferencesData->CopyParamRuleData = &Data;
  8080. }
  8081. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  8082. }
  8083. //---------------------------------------------------------------------------
  8084. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  8085. const TCustomCommandType & Command)
  8086. {
  8087. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  8088. {
  8089. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE, (Command.Command)));
  8090. }
  8091. }
  8092. //---------------------------------------------------------------------------
  8093. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  8094. {
  8095. bool RemoteAllowed = CustomCommandRemoteAllowed();
  8096. TCustomCommandType Command;
  8097. // make sure we use local custom command when remote are not supported
  8098. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  8099. {
  8100. Command = FLastCustomCommand;
  8101. }
  8102. else
  8103. {
  8104. Command.Params = Command.Params | ccLocal;
  8105. }
  8106. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  8107. FEditingFocusedAdHocCommand = OnFocused;
  8108. bool LocalSide = (FCurrentSide == osLocal);
  8109. int Options =
  8110. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  8111. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  8112. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  8113. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  8114. {
  8115. FLastCustomCommand = Command;
  8116. UpdateCustomCommandsToolbar();
  8117. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  8118. }
  8119. }
  8120. //---------------------------------------------------------------------------
  8121. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  8122. {
  8123. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  8124. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  8125. DebugAssert(State > 0);
  8126. if (State <= 0)
  8127. {
  8128. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE, (FLastCustomCommand.Command)));
  8129. }
  8130. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  8131. }
  8132. //---------------------------------------------------------------------------
  8133. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  8134. TCustomCommandType & Command, int & State)
  8135. {
  8136. bool Result = !FLastCustomCommand.Command.IsEmpty();
  8137. if (Result)
  8138. {
  8139. Command = FLastCustomCommand;
  8140. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  8141. }
  8142. return Result;
  8143. }
  8144. //---------------------------------------------------------------------------
  8145. void __fastcall TCustomScpExplorerForm::BeforeAction()
  8146. {
  8147. if (RemoteDirView->ItemFocused != NULL)
  8148. {
  8149. RemoteDirView->ItemFocused->CancelEdit();
  8150. }
  8151. }
  8152. //---------------------------------------------------------------------------
  8153. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  8154. {
  8155. DebugAssert(ComponentVisible[Component]);
  8156. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  8157. }
  8158. //---------------------------------------------------------------------------
  8159. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  8160. {
  8161. // when queue panel is resized here directly, the status bar is stretched
  8162. // over whole space the panel occupied
  8163. PostComponentHide(fcQueueView);
  8164. }
  8165. //---------------------------------------------------------------------------
  8166. void __fastcall TCustomScpExplorerForm::WMWinIniChange(TMessage & Message)
  8167. {
  8168. WinConfiguration->ResetSysDarkTheme();
  8169. ConfigurationChanged();
  8170. ConfigureInterface();
  8171. TForm::Dispatch(&Message);
  8172. }
  8173. //---------------------------------------------------------------------------
  8174. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  8175. {
  8176. TMessage * M = static_cast<TMessage*>(Message);
  8177. switch (M->Msg)
  8178. {
  8179. case CM_DIALOGCHAR:
  8180. CMDialogChar(*M);
  8181. break;
  8182. case WM_APPCOMMAND:
  8183. WMAppCommand(*M);
  8184. break;
  8185. case WM_SYSCOMMAND:
  8186. WMSysCommand(*M);
  8187. break;
  8188. case WM_QUERYENDSESSION:
  8189. WMQueryEndSession(*M);
  8190. break;
  8191. case WM_ENDSESSION:
  8192. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  8193. break;
  8194. #ifdef _DEBUG
  8195. case WM_WINDOWPOSCHANGED:
  8196. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  8197. break;
  8198. case CM_CUSTOMSTYLECHANGED:
  8199. TForm::Dispatch(Message);
  8200. break;
  8201. #endif
  8202. case WM_COMPONENT_HIDE:
  8203. {
  8204. Byte Component = static_cast<Byte>(M->WParam);
  8205. // sanity check
  8206. if (ComponentVisible[Component])
  8207. {
  8208. // special treatment
  8209. if (Component == fcQueueView)
  8210. {
  8211. ToggleQueueVisibility();
  8212. DebugAssert(!ComponentVisible[fcQueueView]);
  8213. }
  8214. else
  8215. {
  8216. ComponentVisible[Component] = false;
  8217. }
  8218. }
  8219. }
  8220. break;
  8221. case WM_COPYDATA:
  8222. WMCopyData(*M);
  8223. break;
  8224. case WM_MANAGES_CAPTION:
  8225. // caption managed in TTerminalManager::UpdateAppTitle()
  8226. M->Result = 1;
  8227. break;
  8228. case WM_WANTS_MOUSEWHEEL:
  8229. M->Result = 1;
  8230. break;
  8231. case CM_SHOWINGCHANGED:
  8232. CMShowingChanged(*M);
  8233. break;
  8234. case WM_CLOSE:
  8235. WMClose(*M);
  8236. break;
  8237. case WM_DPICHANGED:
  8238. WMDpiChanged(*M);
  8239. break;
  8240. case CM_DPICHANGED:
  8241. CMDpiChanged(*M);
  8242. break;
  8243. case WM_WININICHANGE:
  8244. WMWinIniChange(*M);
  8245. break;
  8246. default:
  8247. TForm::Dispatch(Message);
  8248. break;
  8249. }
  8250. }
  8251. //---------------------------------------------------------------------------
  8252. void __fastcall TCustomScpExplorerForm::UpdateImages()
  8253. {
  8254. // noop
  8255. }
  8256. //---------------------------------------------------------------------------
  8257. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  8258. {
  8259. TForm::Dispatch(&Message);
  8260. FSessionColors->Clear();
  8261. AddFixedSessionImages();
  8262. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  8263. UpdateImages();
  8264. }
  8265. //---------------------------------------------------------------------------
  8266. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  8267. {
  8268. TForm::Dispatch(&Message);
  8269. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  8270. UpdatePixelsPerInchMainWindowCounter();
  8271. }
  8272. //---------------------------------------------------------------------------
  8273. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  8274. {
  8275. // Cannot close window while we are busy.
  8276. // We cannot test this in FormCloseQuery as that is called also from
  8277. // Close(), which is called by CloseApplicationAction. So we can be busy
  8278. // there already even, when it is legitimate to close the application.
  8279. // Possibly a better place to handle this would be WMSysCommand.
  8280. if (NonVisualDataModule->Busy)
  8281. {
  8282. Message.Result = 1;
  8283. }
  8284. else
  8285. {
  8286. TForm::Dispatch(&Message);
  8287. }
  8288. }
  8289. //---------------------------------------------------------------------------
  8290. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  8291. {
  8292. TForm::Dispatch(&Message);
  8293. if (Showing && (Terminal == NULL))
  8294. {
  8295. // When we are starting minimized (i.e. from an installer),
  8296. // postpone showing Login dialog until we get restored.
  8297. // Otherwise the Login dialog (and Authentication window) show restored
  8298. // over invidible (minimized) main window.
  8299. if (WindowState == wsMinimized)
  8300. {
  8301. FNeedSession = true;
  8302. }
  8303. else
  8304. {
  8305. // This happens before application ever goes idle, so the toolbars would
  8306. // stay enabled (initial state) until the Login dialog is dismissed.
  8307. UpdateActions();
  8308. NonVisualDataModule->StartBusy();
  8309. try
  8310. {
  8311. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  8312. // otherwise the dialog does not receive focus.
  8313. // With Commander interface the ProcessMessages is called already
  8314. // by TDriveView, but with Explorer interface, we need to call it explicily
  8315. Application->ProcessMessages();
  8316. // do not reload sessions, they have been loaded just now (optimization)
  8317. NeedSession(false);
  8318. }
  8319. __finally
  8320. {
  8321. NonVisualDataModule->EndBusy();
  8322. }
  8323. }
  8324. }
  8325. }
  8326. //---------------------------------------------------------------------------
  8327. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  8328. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  8329. int & MaxHeight)
  8330. {
  8331. // workaround for bug in TWinControl.CalcConstraints
  8332. // Check for empty rect (restore from iconic state) is done there only after
  8333. // call to AdjustClientRect, which enlarges the rect (for forms).
  8334. TRect R = GetClientRect();
  8335. // when restoring from iconic state, place no restrictions
  8336. if (IsRectEmpty(R))
  8337. {
  8338. MinWidth = 0;
  8339. MinHeight = 0;
  8340. MaxWidth = 32000;
  8341. MaxHeight = 32000;
  8342. }
  8343. }
  8344. //---------------------------------------------------------------------------
  8345. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  8346. TSpaceAvailable & ASpaceAvailable, bool & Close)
  8347. {
  8348. // terminal can be already closed (e.g. dropped connection)
  8349. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  8350. {
  8351. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  8352. try
  8353. {
  8354. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  8355. }
  8356. catch(...)
  8357. {
  8358. if (!Terminal->Active)
  8359. {
  8360. Close = true;
  8361. }
  8362. throw;
  8363. }
  8364. }
  8365. }
  8366. //---------------------------------------------------------------------------
  8367. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  8368. {
  8369. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  8370. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  8371. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  8372. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  8373. {
  8374. OnGetSpaceAvailable = GetSpaceAvailable;
  8375. }
  8376. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  8377. OnGetSpaceAvailable);
  8378. }
  8379. //---------------------------------------------------------------------------
  8380. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  8381. {
  8382. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  8383. Terminal->FillSessionDataForCode(Data.get());
  8384. return Data.release();
  8385. }
  8386. //---------------------------------------------------------------------------
  8387. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  8388. {
  8389. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  8390. DoGenerateUrlDialog(Data.get(), Paths);
  8391. }
  8392. //---------------------------------------------------------------------------
  8393. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  8394. {
  8395. GenerateUrl(NULL);
  8396. }
  8397. //---------------------------------------------------------------------------
  8398. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  8399. {
  8400. std::unique_ptr<TStrings> Paths(new TStringList());
  8401. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  8402. GenerateUrl(Paths.get());
  8403. }
  8404. //---------------------------------------------------------------------------
  8405. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  8406. {
  8407. FSessionColor = value;
  8408. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  8409. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  8410. static_cast<TObject *>(GetComponent(fcColorMenu)));
  8411. DebugAssert(ColorItem != NULL);
  8412. ColorItem->Color = C;
  8413. NonVisualDataModule->ColorMenuItem->Color = C;
  8414. UpdateControls();
  8415. }
  8416. //---------------------------------------------------------------------------
  8417. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  8418. {
  8419. if (value != FSessionColor)
  8420. {
  8421. UpdateSessionColor(value);
  8422. // Is null when called from LastTerminalClosed
  8423. if (Terminal != NULL)
  8424. {
  8425. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  8426. }
  8427. }
  8428. }
  8429. //---------------------------------------------------------------------------
  8430. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  8431. {
  8432. bool Result = FNoteTimer->Enabled;
  8433. if (Result)
  8434. {
  8435. // cannot cancel note too early
  8436. bool NotEarly =
  8437. (Now() - FNoteShown >
  8438. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  8439. if (Force || NotEarly)
  8440. {
  8441. FNoteTimer->Enabled = false;
  8442. FNote = L"";
  8443. SAFE_DESTROY(FNoteData);
  8444. FOnNoteClick = NULL;
  8445. FNoteHints = FNotes->Text;
  8446. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8447. UpdateStatusBar();
  8448. }
  8449. }
  8450. return Result;
  8451. }
  8452. //---------------------------------------------------------------------------
  8453. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  8454. {
  8455. DebugAssert(FNoteTimer->Enabled);
  8456. CancelNote(true);
  8457. }
  8458. //---------------------------------------------------------------------------
  8459. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  8460. {
  8461. int P = Note.Pos(L"\n");
  8462. if (P > 0)
  8463. {
  8464. Note.SetLength(P - 1);
  8465. }
  8466. FNotes->Add(FORMAT(L"[%s] %s",
  8467. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  8468. while (FNotes->Count > 10)
  8469. {
  8470. FNotes->Delete(0);
  8471. }
  8472. if (UpdateNow)
  8473. {
  8474. FNoteHints = FNotes->Text;
  8475. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8476. UpdateStatusBar();
  8477. }
  8478. }
  8479. //---------------------------------------------------------------------------
  8480. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  8481. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  8482. {
  8483. int P = Note.Pos(L"\n");
  8484. if (P > 0)
  8485. {
  8486. Note.SetLength(P - 1);
  8487. }
  8488. FNoteHints = FNotes->Text;
  8489. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  8490. FNote = Note;
  8491. SAFE_DESTROY(FNoteData);
  8492. FNoteData = NoteData;
  8493. FOnNoteClick = OnNoteClick;
  8494. AddNote(Note, false);
  8495. UpdateStatusBar();
  8496. FNoteShown = Now();
  8497. FNoteTimer->Enabled = false;
  8498. if (Seconds == 0)
  8499. {
  8500. Seconds = WinConfiguration->NotificationsTimeout;
  8501. }
  8502. FNoteTimer->Interval = Seconds * MSecsPerSec;
  8503. FNoteTimer->Enabled = true;
  8504. }
  8505. //---------------------------------------------------------------------------
  8506. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  8507. {
  8508. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  8509. }
  8510. //---------------------------------------------------------------------------
  8511. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  8512. {
  8513. if (NonVisualDataModule->SynchronizeBrowsingAction->Checked)
  8514. {
  8515. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  8516. }
  8517. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  8518. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  8519. (NonVisualDataModule->SynchronizeBrowsingAction->Checked ? 2 : 3)))),
  8520. 0, NULL, NULL);
  8521. }
  8522. //---------------------------------------------------------------------------
  8523. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  8524. {
  8525. WinConfiguration->ShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  8526. PostNote(FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1),
  8527. (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE,
  8528. (WinConfiguration->ShowHiddenFiles ? 2 : 3)))), 0, NULL, NULL);
  8529. }
  8530. //---------------------------------------------------------------------------
  8531. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  8532. {
  8533. WinConfiguration->FormatSizeBytes = Style;
  8534. }
  8535. //---------------------------------------------------------------------------
  8536. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  8537. {
  8538. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  8539. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  8540. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  8541. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  8542. }
  8543. //---------------------------------------------------------------------------
  8544. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  8545. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  8546. {
  8547. if (Panel->Index == 0)
  8548. {
  8549. if (FOnNoteClick != NULL)
  8550. {
  8551. // prevent the user data from being freed by possible call
  8552. // to CancelNote or PostNote during call to OnNoteClick
  8553. std::unique_ptr<TObject> NoteData(FNoteData);
  8554. TNotifyEvent OnNoteClick = FOnNoteClick;
  8555. FNoteData = NULL;
  8556. // need to cancel the note as we are going to delete its user data
  8557. CancelNote(true);
  8558. OnNoteClick(NoteData.get());
  8559. }
  8560. }
  8561. if (Panel->Index >= Sender->Panels->Count - SessionPanelCount)
  8562. {
  8563. FileSystemInfo();
  8564. }
  8565. }
  8566. //---------------------------------------------------------------------------
  8567. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  8568. {
  8569. // workaround:
  8570. // 1) for unknown reason, disabling window, while minimized,
  8571. // prevents it from restoring, even if it was enabled again meanwhile
  8572. // 2) when disabling the main window, while another has focus
  8573. // minimize is no longer possible
  8574. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  8575. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  8576. // Shouldn't we use IsApplicationMinimized() here?
  8577. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  8578. {
  8579. Enabled = false;
  8580. }
  8581. FLockLevel++;
  8582. }
  8583. //---------------------------------------------------------------------------
  8584. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  8585. {
  8586. DebugAssert(FLockLevel > 0);
  8587. FLockLevel--;
  8588. if (FLockLevel == 0)
  8589. {
  8590. DebugAssert(FLockSuspendLevel == 0);
  8591. Enabled = true;
  8592. }
  8593. }
  8594. //---------------------------------------------------------------------------
  8595. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  8596. {
  8597. // We need to make sure that window is enabled when the last modal window closes
  8598. // otherwise focus is not restored correctly.
  8599. // So we re-enable the window when modal window opens and
  8600. // disable it back after is closes
  8601. if (FLockLevel > 0)
  8602. {
  8603. // while we have nesting counter, we know that we never be called
  8604. // recursivelly as Application->OnModalBegin is called only
  8605. // for the top-level modal window
  8606. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  8607. {
  8608. // won't be disabled when conditions in LockWindow() were not satisfied
  8609. FDisabledOnLockSuspend = !Enabled;
  8610. // When minimized to tray (or actually when set to SW_HIDE),
  8611. // setting Enabled makes the window focusable even when there's
  8612. // modal window over it
  8613. if (!FTrayIcon->Visible)
  8614. {
  8615. Enabled = true;
  8616. }
  8617. }
  8618. FLockSuspendLevel++;
  8619. }
  8620. }
  8621. //---------------------------------------------------------------------------
  8622. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  8623. {
  8624. if (FLockSuspendLevel > 0)
  8625. {
  8626. DebugAssert(FLockLevel > 0);
  8627. FLockSuspendLevel--;
  8628. // see comment in SuspendWindowLock
  8629. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  8630. {
  8631. // Note that window can be enabled here, when we were minized to tray when
  8632. // was SuspendWindowLock() called.
  8633. // We should possibly do the same check as in LockWindow(),
  8634. // if it is ever possible that the consitions change between
  8635. // SuspendWindowLock() and ResumeWindowLock()
  8636. Enabled = !FDisabledOnLockSuspend;
  8637. }
  8638. }
  8639. }
  8640. //---------------------------------------------------------------------------
  8641. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  8642. {
  8643. if (!TextOnly)
  8644. {
  8645. TTBXComboBoxItem * RemotePathComboBox =
  8646. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  8647. TStrings * Items = RemotePathComboBox->Strings;
  8648. Items->BeginUpdate();
  8649. try
  8650. {
  8651. Items->Clear();
  8652. if (Terminal != NULL)
  8653. {
  8654. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  8655. while (!IsUnixRootPath(APath))
  8656. {
  8657. int P = APath.LastDelimiter(L'/');
  8658. DebugAssert(P >= 0);
  8659. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  8660. APath.SetLength(P - 1);
  8661. }
  8662. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  8663. }
  8664. }
  8665. __finally
  8666. {
  8667. RemotePathComboBox->ItemIndex = Items->Count - 1;
  8668. // Setting ItemIndex to -1 does not reset its text
  8669. if (Items->Count == 0)
  8670. {
  8671. RemotePathComboBox->Text = L"";
  8672. }
  8673. Items->EndUpdate();
  8674. }
  8675. }
  8676. }
  8677. //---------------------------------------------------------------------------
  8678. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  8679. TTBXComboBoxItem * Sender, const UnicodeString /*AText*/, int AIndex,
  8680. int & ImageIndex)
  8681. {
  8682. if (AIndex < 0)
  8683. {
  8684. AIndex = Sender->ItemIndex;
  8685. }
  8686. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  8687. }
  8688. //---------------------------------------------------------------------------
  8689. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  8690. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  8691. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  8692. {
  8693. ARect.Left += (10 * AIndex);
  8694. }
  8695. //---------------------------------------------------------------------------
  8696. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  8697. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  8698. {
  8699. AWidth += (10 * AIndex);
  8700. }
  8701. //---------------------------------------------------------------------------
  8702. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(
  8703. TObject * Sender)
  8704. {
  8705. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  8706. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  8707. int Index = RemotePathComboBox->ItemIndex;
  8708. while (Index < RemotePathComboBox->Strings->Count - 1)
  8709. {
  8710. APath = UnixExtractFileDir(APath);
  8711. Index++;
  8712. }
  8713. // VanDyke style paths
  8714. if (APath.IsEmpty())
  8715. {
  8716. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  8717. APath = ROOTDIRECTORY;
  8718. }
  8719. if (RemoteDirView->Path != APath)
  8720. {
  8721. RemoteDirView->Path = APath;
  8722. }
  8723. }
  8724. //---------------------------------------------------------------------------
  8725. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  8726. {
  8727. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  8728. DebugUsedParam(Sender);
  8729. UpdateRemotePathComboBox(true);
  8730. }
  8731. //---------------------------------------------------------------------------
  8732. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  8733. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  8734. {
  8735. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8736. DebugAssert(DirView != NULL);
  8737. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  8738. {
  8739. HWND Edit = ListView_GetEditControl(DirView->Handle);
  8740. // OnEditing is called also from TCustomListView::CanEdit
  8741. if (Edit != NULL)
  8742. {
  8743. EditSelectBaseName(Edit);
  8744. }
  8745. }
  8746. }
  8747. //---------------------------------------------------------------------------
  8748. //---------------------------------------------------------------------------
  8749. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  8750. {
  8751. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  8752. Result->AutoDetectDnD = false;
  8753. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  8754. Result->RenderDataOn = rdoEnterAndDropSync;
  8755. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  8756. return Result;
  8757. }
  8758. //---------------------------------------------------------------------------
  8759. void __fastcall TCustomScpExplorerForm::CreateWnd()
  8760. {
  8761. TForm::CreateWnd();
  8762. if (FSessionsDragDropFilesEx == NULL)
  8763. {
  8764. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  8765. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  8766. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  8767. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  8768. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  8769. }
  8770. if (FQueueDragDropFilesEx == NULL)
  8771. {
  8772. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  8773. // No need to set OnDragOver as we do not have any restrictions
  8774. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  8775. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  8776. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  8777. }
  8778. }
  8779. //---------------------------------------------------------------------------
  8780. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  8781. {
  8782. TForm::DestroyWnd();
  8783. FSessionsDragDropFilesEx->DragDropControl = NULL;
  8784. FQueueDragDropFilesEx->DragDropControl = NULL;
  8785. }
  8786. //---------------------------------------------------------------------------
  8787. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  8788. {
  8789. SideEnter(FCurrentSide);
  8790. FEverShown = true;
  8791. }
  8792. //---------------------------------------------------------------------------
  8793. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  8794. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  8795. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  8796. {
  8797. if (!NonVisualDataModule->Busy)
  8798. {
  8799. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8800. Configuration->Usage->Inc(L"FileFinds");
  8801. LockWindow(true);
  8802. NonVisualDataModule->StartBusy();
  8803. WinConfiguration->LockedInterface = true;
  8804. try
  8805. {
  8806. FTerminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  8807. }
  8808. __finally
  8809. {
  8810. WinConfiguration->LockedInterface = false;
  8811. NonVisualDataModule->EndBusy();
  8812. UnlockWindow();
  8813. }
  8814. }
  8815. }
  8816. //---------------------------------------------------------------------------
  8817. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  8818. {
  8819. if (!NonVisualDataModule->Busy)
  8820. {
  8821. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8822. SetFocus();
  8823. RemoteDirView->Path = UnixExtractFilePath(Path);
  8824. TListItem * Item = RemoteDirView->FindFileItem(UnixExtractFileName(Path));
  8825. if (Item != NULL)
  8826. {
  8827. RemoteDirView->ItemFocused = Item;
  8828. RemoteDirView->ItemFocused->MakeVisible(false);
  8829. RemoteDirView->SetFocus();
  8830. }
  8831. }
  8832. }
  8833. //---------------------------------------------------------------------------
  8834. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  8835. {
  8836. bool Result = !NonVisualDataModule->Busy;
  8837. if (Result)
  8838. {
  8839. TTerminalManager::Instance()->ActiveTerminal = ATerminal;
  8840. }
  8841. return Result;
  8842. }
  8843. //---------------------------------------------------------------------------
  8844. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  8845. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8846. {
  8847. if (CanOperateOnFoundFiles(ATerminal))
  8848. {
  8849. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  8850. FOnFileOperationFinished = OnFileOperationFinished;
  8851. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  8852. }
  8853. }
  8854. //---------------------------------------------------------------------------
  8855. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  8856. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8857. {
  8858. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  8859. }
  8860. //---------------------------------------------------------------------------
  8861. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  8862. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8863. {
  8864. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  8865. }
  8866. //---------------------------------------------------------------------------
  8867. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  8868. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  8869. {
  8870. if (CanOperateOnFoundFiles(ATerminal))
  8871. {
  8872. for (int Index = 0; Index < FileList->Count; Index++)
  8873. {
  8874. UnicodeString FileName = FileList->Strings[Index];
  8875. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  8876. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  8877. OnFileOperationFinished(FileName, true);
  8878. }
  8879. }
  8880. }
  8881. //---------------------------------------------------------------------------
  8882. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  8883. {
  8884. FFileFindTerminal = Terminal;
  8885. ShowFileFindDialog(
  8886. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  8887. DoDownloadFoundFiles, DoEditFoundFiles);
  8888. }
  8889. //---------------------------------------------------------------------------
  8890. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  8891. {
  8892. FTaskbarList = TaskbarList;
  8893. }
  8894. //---------------------------------------------------------------------------
  8895. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  8896. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  8897. {
  8898. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  8899. if (Index >= 0)
  8900. {
  8901. if (Button == mbLeft)
  8902. {
  8903. // "Mouse down" is raised only after tab is switched.
  8904. // If switching tab (switching session) takes long enough for user
  8905. // to actually release the button, "mouse down" is still raised,
  8906. // but we do not get "mouse up" event, so dragging is not cancelled,
  8907. // prevent that by not beginning dragging in the first place.
  8908. if (IsKeyPressed(VK_LBUTTON))
  8909. {
  8910. // when user clicks the "+", we get mouse down only after the session
  8911. // is closed, when new session tab is already on X:Y, so dragging
  8912. // starts, prevent that
  8913. if (MilliSecondsBetween(Now(), FSessionsPageControlNewSessionTime) > 500)
  8914. {
  8915. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8916. if (Terminal != NULL)
  8917. {
  8918. SessionsPageControl->BeginDrag(false);
  8919. }
  8920. }
  8921. }
  8922. }
  8923. else if (Button == mbMiddle)
  8924. {
  8925. // ignore middle-click for "New session tab"
  8926. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8927. if (Terminal != NULL)
  8928. {
  8929. CloseSessionTab(Index);
  8930. }
  8931. }
  8932. }
  8933. }
  8934. //---------------------------------------------------------------------------
  8935. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  8936. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  8937. {
  8938. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  8939. // do not allow dropping on the "+" tab
  8940. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8941. if ((TargetTerminal != NULL) &&
  8942. (SessionsPageControl->ActivePage->PageIndex != Index))
  8943. {
  8944. Configuration->Usage->Inc(L"SessionTabMoves");
  8945. // this is almost redundant as we would recreate tabs in DoTerminalListChanged,
  8946. // but we want to actually prevent that to avoid flicker
  8947. SessionsPageControl->ActivePage->PageIndex = Index;
  8948. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->ActivePage);
  8949. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  8950. }
  8951. }
  8952. //---------------------------------------------------------------------------
  8953. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  8954. TObject * Sender, TObject * Source, int X, int Y,
  8955. TDragState /*State*/, bool & Accept)
  8956. {
  8957. Accept = (Sender == Source);
  8958. if (Accept)
  8959. {
  8960. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  8961. TTerminal * Terminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8962. // do not allow dragging to the "+" tab
  8963. Accept = (Terminal != NULL);
  8964. }
  8965. }
  8966. //---------------------------------------------------------------------------
  8967. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(int /*KeyState*/,
  8968. const TPoint & Point, int & Effect)
  8969. {
  8970. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  8971. if (Index < 0)
  8972. {
  8973. Effect = DROPEFFECT_None;
  8974. }
  8975. else
  8976. {
  8977. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8978. // do not allow dropping on the "+" tab
  8979. if (TargetTerminal == NULL)
  8980. {
  8981. Effect = DROPEFFECT_None;
  8982. }
  8983. else if ((TargetTerminal != Terminal) && (Effect == DROPEFFECT_Move))
  8984. {
  8985. Effect = DROPEFFECT_Copy;
  8986. }
  8987. }
  8988. }
  8989. //---------------------------------------------------------------------------
  8990. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  8991. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  8992. {
  8993. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  8994. // do not allow dropping on the "+" tab
  8995. TTerminal * TargetTerminal = GetSessionTabTerminal(SessionsPageControl->Pages[Index]);
  8996. if (TargetTerminal != NULL)
  8997. {
  8998. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  8999. if (!IsFileControl(DropSourceControl, osRemote))
  9000. {
  9001. TTerminalManager::Instance()->ActiveTerminal = TargetTerminal;
  9002. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  9003. // Why don't we use Terminal->CurrentDirectory directly?
  9004. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  9005. // do not force queue, drag drop
  9006. false, true);
  9007. }
  9008. }
  9009. }
  9010. //---------------------------------------------------------------------------
  9011. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  9012. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  9013. {
  9014. // Downloads are handled in RemoteFileControlDDEnd
  9015. if (!IsFileControl(DropSourceControl, osRemote))
  9016. {
  9017. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  9018. Terminal->CurrentDirectory,
  9019. // force queue, drag drop
  9020. true, true);
  9021. }
  9022. }
  9023. //---------------------------------------------------------------------------
  9024. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  9025. {
  9026. FShowing = false;
  9027. // Do not save empty workspace
  9028. if (WinConfiguration->AutoSaveWorkspace && (Terminal != NULL))
  9029. {
  9030. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  9031. UnicodeString Name = WorkspaceName();
  9032. DoSaveWorkspace(
  9033. Name, DataList.get(),
  9034. !Configuration->DisablePasswordStoring &&
  9035. WinConfiguration->AutoSaveWorkspacePasswords, false);
  9036. WinConfiguration->LastStoredSession = Name;
  9037. }
  9038. }
  9039. //---------------------------------------------------------------------------
  9040. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  9041. {
  9042. TManagedTerminal * ManagedTerminal =
  9043. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  9044. if (ManagedTerminal != NULL)
  9045. {
  9046. ManagedTerminal->DirectoryLoaded = Now();
  9047. }
  9048. }
  9049. //---------------------------------------------------------------------------
  9050. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  9051. TListItem * /*Item*/, bool /*Selected*/)
  9052. {
  9053. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  9054. switch (DirView->LastSelectMethod)
  9055. {
  9056. case smKeyboard:
  9057. Configuration->Usage->Inc(L"KeyboardSelections");
  9058. break;
  9059. case smMouse:
  9060. Configuration->Usage->Inc(L"MouseSelections");
  9061. break;
  9062. }
  9063. }
  9064. //---------------------------------------------------------------------------
  9065. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  9066. {
  9067. if (Color != 0)
  9068. {
  9069. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  9070. }
  9071. else
  9072. {
  9073. return FSessionTabImageIndex;
  9074. }
  9075. }
  9076. //---------------------------------------------------------------------------
  9077. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  9078. {
  9079. TPngImageCollectionItem * Item =
  9080. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  9081. FSessionColors->AddPng(Item->PngImage);
  9082. return FSessionColors->Count - 1;
  9083. }
  9084. //---------------------------------------------------------------------------
  9085. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  9086. {
  9087. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  9088. FNewSessionTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewSessionAction->ImageIndex);
  9089. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  9090. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  9091. }
  9092. //---------------------------------------------------------------------------
  9093. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  9094. {
  9095. for (int Index = 0; Index < Control->ControlCount; Index++)
  9096. {
  9097. TControl * AControl = Control->Controls[Index];
  9098. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  9099. if (WinControl != NULL)
  9100. {
  9101. CollectItemsWithTextDisplayMode(WinControl);
  9102. }
  9103. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  9104. if (Toolbar != NULL)
  9105. {
  9106. // we care for top-level items only
  9107. TTBCustomItem * Items = Toolbar->Items;
  9108. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  9109. {
  9110. TTBCustomItem * Item = Items->Items[ItemIndex];
  9111. if (((Item->DisplayMode == nbdmImageAndText) ||
  9112. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  9113. EligibleForImageDisplayMode(Item))
  9114. {
  9115. FItemsWithTextDisplayMode.insert(Item);
  9116. }
  9117. }
  9118. }
  9119. }
  9120. }
  9121. //---------------------------------------------------------------------------
  9122. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  9123. {
  9124. return true;
  9125. }
  9126. //---------------------------------------------------------------------------
  9127. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  9128. {
  9129. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  9130. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  9131. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  9132. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  9133. bool Result = true;
  9134. while (Result && (i != FItemsWithTextDisplayMode.end()))
  9135. {
  9136. TTBCustomItem * Item = *i;
  9137. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  9138. if (Label != NULL)
  9139. {
  9140. // optimization
  9141. if (Label->Visible == SelectiveToolbarText)
  9142. {
  9143. Result = false;
  9144. }
  9145. else
  9146. {
  9147. Label->Visible = SelectiveToolbarText;
  9148. }
  9149. }
  9150. else
  9151. {
  9152. // optimization
  9153. if (Item->DisplayMode == DisplayMode)
  9154. {
  9155. Result = false;
  9156. }
  9157. else
  9158. {
  9159. Item->DisplayMode = DisplayMode;
  9160. }
  9161. }
  9162. ++i;
  9163. }
  9164. if (Result)
  9165. {
  9166. UpdateNewSessionTab();
  9167. }
  9168. return Result;
  9169. }
  9170. //---------------------------------------------------------------------------
  9171. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  9172. {
  9173. DebugFail();
  9174. }
  9175. //---------------------------------------------------------------------------
  9176. bool __fastcall TCustomScpExplorerForm::IsBusy()
  9177. {
  9178. // Among other, a lock level is non zero, while directory is being loaded,
  9179. // even when it happens as a result of dirview navigation,
  9180. // i.e. when TNonVisualDataModule is NOT FBusy.
  9181. // That's why the TNonVisualDataModule::GetBusy calls this method.
  9182. // Among other this prevents a panel auto update to occur while
  9183. // directory is changing.
  9184. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  9185. }
  9186. //---------------------------------------------------------------------------
  9187. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * /*Action*/, TActionAllowed Allowed)
  9188. {
  9189. // While the window is disabled, we still seem to process menu shortcuts at least,
  9190. // so stop it at least here.
  9191. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  9192. return
  9193. (Allowed == aaUpdate) ||
  9194. !NonVisualDataModule->Busy;
  9195. }
  9196. //---------------------------------------------------------------------------
  9197. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  9198. {
  9199. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  9200. }
  9201. //---------------------------------------------------------------------------
  9202. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  9203. {
  9204. // This is somewhat redundant to LockWindow() call from
  9205. // TTerminalManager::TerminalReadDirectoryProgress.
  9206. // But disabling window is known not to block keyboard shorcuts
  9207. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  9208. if (Busy > 0)
  9209. {
  9210. if (NonVisualDataModule->Busy)
  9211. {
  9212. State = false;
  9213. }
  9214. else
  9215. {
  9216. NonVisualDataModule->StartBusy();
  9217. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  9218. LockWindow();
  9219. }
  9220. }
  9221. else if (Busy < 0)
  9222. {
  9223. UnlockWindow();
  9224. NonVisualDataModule->EndBusy();
  9225. }
  9226. else
  9227. {
  9228. State = NonVisualDataModule->Busy;
  9229. }
  9230. }
  9231. //---------------------------------------------------------------------------
  9232. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  9233. {
  9234. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  9235. // no context menu for "New session tab"
  9236. if ((Index >= 0) && (GetSessionTabTerminal(SessionsPageControl->Pages[Index]) != NULL))
  9237. {
  9238. SessionsPageControl->ActivePageIndex = Index;
  9239. if (DebugAlwaysTrue(SessionTabSwitched()))
  9240. {
  9241. // copied from TControl.WMContextMenu
  9242. SendCancelMode(SessionsPageControl);
  9243. // explicit popup instead of using PopupMenu property
  9244. // to avoid menu to popup somewhere within SessionTabSwitched above,
  9245. // while connecting yet not-connected session and hence
  9246. // allowing an access to commands over not-completelly connected session
  9247. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  9248. TPopupMenu * PopupMenu = NonVisualDataModule->SessionsPopup;
  9249. PopupMenu->PopupComponent = SessionsPageControl;
  9250. PopupMenu->Popup(Point.x, Point.y);
  9251. }
  9252. }
  9253. Handled = true;
  9254. }
  9255. //---------------------------------------------------------------------------
  9256. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  9257. {
  9258. return (Terminal != NULL) && Terminal->Active && Terminal->IsCapable[fcChangePassword];
  9259. }
  9260. //---------------------------------------------------------------------------
  9261. void __fastcall TCustomScpExplorerForm::ChangePassword()
  9262. {
  9263. Configuration->Usage->Inc(L"PasswordChanges");
  9264. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  9265. ChangePasswordData->DisableAuthentationsExceptPassword();
  9266. ChangePasswordData->ChangePassword = true;
  9267. std::unique_ptr<TTerminal> ChangePasswordSession(
  9268. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  9269. ChangePasswordSession->AutoReadDirectory = false;
  9270. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  9271. {
  9272. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  9273. }
  9274. else
  9275. {
  9276. Configuration->Usage->Inc(L"PasswordChangesFailed");
  9277. }
  9278. }
  9279. //---------------------------------------------------------------------------
  9280. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  9281. {
  9282. // No nice way to assert SSH2
  9283. return (Terminal != NULL) && Terminal->Active && (Terminal->FSProtocol == cfsSFTP);
  9284. }
  9285. //---------------------------------------------------------------------------
  9286. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  9287. {
  9288. TOperationVisualizer OperationVisualizer;
  9289. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  9290. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  9291. }
  9292. //---------------------------------------------------------------------------
  9293. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  9294. {
  9295. TForm::ChangeScale(M, D);
  9296. int APixelsPerInch = GetControlPixelsPerInch(this);
  9297. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  9298. try
  9299. {
  9300. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  9301. }
  9302. __finally
  9303. {
  9304. GUIConfiguration->ChangeResourceModule(ResourceModule);
  9305. }
  9306. }
  9307. //---------------------------------------------------------------------------
  9308. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  9309. {
  9310. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  9311. }
  9312. //---------------------------------------------------------------------
  9313. class TPublicControl : public TControl
  9314. {
  9315. friend class TCustomScpExplorerForm;
  9316. };
  9317. //---------------------------------------------------------------------------
  9318. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  9319. {
  9320. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  9321. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  9322. }
  9323. //---------------------------------------------------------------------------
  9324. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  9325. {
  9326. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  9327. OpenBookmark(Side, Bookmark);
  9328. }
  9329. //---------------------------------------------------------------------------
  9330. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  9331. {
  9332. DoBookmarkClick(osLocal, Sender);
  9333. }
  9334. //---------------------------------------------------------------------------
  9335. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  9336. {
  9337. DoBookmarkClick(osRemote, Sender);
  9338. }
  9339. //---------------------------------------------------------------------------
  9340. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  9341. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  9342. {
  9343. if (BookmarkList != NULL)
  9344. {
  9345. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  9346. if (!WinConfiguration->UseLocationProfiles)
  9347. {
  9348. std::unique_ptr<TStringList> Directories(new TStringList());
  9349. Directories->CaseSensitive = (Side == osRemote);
  9350. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9351. {
  9352. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9353. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  9354. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  9355. {
  9356. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  9357. Item->Caption = EscapeHotkey(Directory);
  9358. Item->ShortCut = Bookmark->ShortCut;
  9359. Item->OnClick = OnBookmarkClick;
  9360. Item->Tag = reinterpret_cast<int>(Bookmark);
  9361. Directories->Add(Directory);
  9362. Menu->Add(Item.release());
  9363. }
  9364. }
  9365. }
  9366. else
  9367. {
  9368. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  9369. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9370. {
  9371. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9372. if (!Bookmark->Node.IsEmpty())
  9373. {
  9374. Folders->Add(Bookmark->Node);
  9375. }
  9376. }
  9377. for (int Index = 0; Index < Folders->Count; Index++)
  9378. {
  9379. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  9380. Item->Caption = Folders->Strings[Index];
  9381. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction->ImageIndex;
  9382. Folders->Objects[Index] = Item.get();
  9383. Menu->Add(Item.release());
  9384. }
  9385. for (int Index = 0; Index < BookmarkList->Count; Index++)
  9386. {
  9387. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  9388. TTBCustomItem * Parent;
  9389. if (!Bookmark->Node.IsEmpty())
  9390. {
  9391. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  9392. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  9393. }
  9394. else
  9395. {
  9396. Parent = Menu;
  9397. }
  9398. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  9399. Item->Caption = Bookmark->Name;
  9400. Item->ShortCut = Bookmark->ShortCut;
  9401. Item->OnClick = OnBookmarkClick;
  9402. Item->Tag = reinterpret_cast<int>(Bookmark);
  9403. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  9404. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  9405. {
  9406. // No hint for location profiles that are actually mere "bookmarks"
  9407. }
  9408. else
  9409. {
  9410. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  9411. UnicodeString LongHint;
  9412. if (!Bookmark->Local.IsEmpty())
  9413. {
  9414. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  9415. }
  9416. if (!Bookmark->Remote.IsEmpty())
  9417. {
  9418. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  9419. }
  9420. AddToList(Hint, LongHint, L"|");
  9421. Item->Hint = Hint;
  9422. }
  9423. Parent->Add(Item.release());
  9424. }
  9425. }
  9426. AddMenuSeparator(Menu);
  9427. }
  9428. }
  9429. //---------------------------------------------------------------------------
  9430. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  9431. {
  9432. Menu->Clear();
  9433. std::unique_ptr<TTBCustomItem> Item;
  9434. Item.reset(new TTBXItem(Owner));
  9435. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  9436. Item->Options = Item->Options << tboDefault;
  9437. Menu->Add(Item.release());
  9438. AddMenuSeparator(Menu);
  9439. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  9440. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  9441. Item.reset(new TTBXItem(Owner));
  9442. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction : NonVisualDataModule->RemoteAddBookmarkAction;
  9443. Menu->Add(Item.release());
  9444. }
  9445. //---------------------------------------------------------------------------
  9446. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  9447. {
  9448. bool Result = true;
  9449. try
  9450. {
  9451. if (Side == osRemote)
  9452. {
  9453. Terminal->ExceptionOnFail = true;
  9454. }
  9455. try
  9456. {
  9457. DirView(Side)->Path = Path;
  9458. }
  9459. __finally
  9460. {
  9461. if (Side == osRemote)
  9462. {
  9463. Terminal->ExceptionOnFail = false;
  9464. }
  9465. }
  9466. }
  9467. catch (Exception & E)
  9468. {
  9469. if ((Side != osRemote) || Terminal->Active)
  9470. {
  9471. ShowExtendedExceptionEx(Terminal, &E);
  9472. Result = false;
  9473. }
  9474. else
  9475. {
  9476. throw;
  9477. }
  9478. }
  9479. return Result;
  9480. }
  9481. //---------------------------------------------------------------------------
  9482. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  9483. {
  9484. // Make sure there some feedback even when loading tine local folders
  9485. TInstantOperationVisualizer Visualizer;
  9486. DirView(Side)->ReloadDirectory();
  9487. }
  9488. //---------------------------------------------------------------------------
  9489. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  9490. {
  9491. if (Index == SessionsPageControl->TabIndex)
  9492. {
  9493. CloseSession();
  9494. }
  9495. else
  9496. {
  9497. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  9498. TTerminal * Terminal = GetSessionTabTerminal(TabSheet);
  9499. TTerminalManager * Manager = TTerminalManager::Instance();
  9500. if (!Terminal->Active)
  9501. {
  9502. Manager->FreeTerminal(Terminal);
  9503. }
  9504. else
  9505. {
  9506. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  9507. if (CanCloseQueue(Queue))
  9508. {
  9509. Manager->FreeTerminal(Terminal);
  9510. }
  9511. }
  9512. }
  9513. }
  9514. //---------------------------------------------------------------------------
  9515. void __fastcall TCustomScpExplorerForm::SessionsPageControlCloseButtonClick(TPageControl * /*Sender*/, int Index)
  9516. {
  9517. CloseSessionTab(Index);
  9518. }
  9519. //---------------------------------------------------------------------------
  9520. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side)
  9521. {
  9522. if (DebugAlwaysTrue(GetSide(Side) == osRemote))
  9523. {
  9524. TInstantOperationVisualizer Visualizer;
  9525. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  9526. // before we create a new data object
  9527. ClipboardClear();
  9528. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  9529. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  9530. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  9531. FClipboardFakeMonitors.reset(StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated));
  9532. if (FClipboardDragDropFilesEx.get() == NULL)
  9533. {
  9534. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  9535. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  9536. }
  9537. FClipboardDragDropFilesEx->FileList->Clear();
  9538. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  9539. FClipboardDragDropFilesEx->CopyToClipboard();
  9540. FClipboardTerminal = FTerminal;
  9541. // Need full paths, as cwd can be different once files are pasted
  9542. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(false, true)));
  9543. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  9544. {
  9545. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  9546. }
  9547. }
  9548. }
  9549. //---------------------------------------------------------------------------
  9550. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  9551. {
  9552. if (OpenClipboard(0))
  9553. {
  9554. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  9555. CloseClipboard();
  9556. }
  9557. }
  9558. //---------------------------------------------------------------------------
  9559. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  9560. {
  9561. return !FClipboardFakeDirectory.IsEmpty();
  9562. }
  9563. //---------------------------------------------------------------------------
  9564. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  9565. {
  9566. RemoveDir(ApiPath(FClipboardFakeDirectory));
  9567. FClipboardFakeDirectory = UnicodeString();
  9568. FClipboardTerminal = NULL;
  9569. // Also called in Idle()
  9570. FClipboardFakeMonitors.reset(NULL);
  9571. }
  9572. //---------------------------------------------------------------------------
  9573. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  9574. {
  9575. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  9576. {
  9577. ClipboardStop();
  9578. }
  9579. }
  9580. //---------------------------------------------------------------------------
  9581. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  9582. {
  9583. TTerminalManager * Manager = TTerminalManager::Instance();
  9584. Manager->ActiveTerminal = FClipboardTerminal;
  9585. TTransferOperationParam Params;
  9586. Params.TargetDirectory = TargetDirectory;
  9587. Params.DragDrop = DragDrop;
  9588. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  9589. }
  9590. //---------------------------------------------------------------------------
  9591. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  9592. {
  9593. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  9594. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  9595. {
  9596. RemoveDir(ApiPath(FileName));
  9597. if (!NonVisualDataModule->Busy)
  9598. {
  9599. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  9600. ClipboardDownload(ExtractFilePath(FileName), NoConfirmation, true);
  9601. }
  9602. }
  9603. }
  9604. //---------------------------------------------------------------------------
  9605. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  9606. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  9607. {
  9608. TFileMasks::TParams MaskParams;
  9609. MaskParams.Size = Size;
  9610. MaskParams.Modification = Modification;
  9611. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  9612. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  9613. {
  9614. bool ImplicitMatch;
  9615. if (Iter->FileMask.Matches(FileName, Directory, DirView->PathName, &MaskParams, false, ImplicitMatch) &&
  9616. !ImplicitMatch)
  9617. {
  9618. Color = Iter->Color;
  9619. break;
  9620. }
  9621. }
  9622. }
  9623. //---------------------------------------------------------------------------