CustomScpExplorer.cpp 405 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <Common.h>
  6. #include "CustomScpExplorer.h"
  7. #include <algorithm>
  8. #include <Bookmarks.h>
  9. #include <Interface.h>
  10. #include <Exceptions.h>
  11. #include <CoreMain.h>
  12. #include <FileSystems.h>
  13. #include <TextsCore.h>
  14. #include <TextsWin.h>
  15. #include <HelpWin.h>
  16. #include <VCLCommon.h>
  17. #include <Progress.h>
  18. #include <SynchronizeProgress.h>
  19. #include <DragExt.h>
  20. #include <WinApi.h>
  21. #include "GUITools.h"
  22. #include "NonVisual.h"
  23. #include "Glyphs.h"
  24. #include "Tools.h"
  25. #include "WinConfiguration.h"
  26. #include "TerminalManager.h"
  27. #include "EditorManager.h"
  28. #include "ProgParams.h"
  29. #include "Setup.h"
  30. #include <Consts.hpp>
  31. #include <DateUtils.hpp>
  32. #include <TB2Common.hpp>
  33. #include <DirectoryMonitor.hpp>
  34. #include <System.IOUtils.hpp>
  35. //---------------------------------------------------------------------------
  36. #pragma package(smart_init)
  37. #pragma link "CustomDirView"
  38. #pragma link "CustomUnixDirView"
  39. #pragma link "IEListView"
  40. #pragma link "NortonLikeListView"
  41. #pragma link "UnixDirView"
  42. #pragma link "CustomDriveView"
  43. #pragma link "UnixDriveView"
  44. #pragma link "CustomDriveView"
  45. #pragma link "TB2Dock"
  46. #pragma link "TBXStatusBars"
  47. #pragma link "TB2Item"
  48. #pragma link "TB2Toolbar"
  49. #pragma link "ThemePageControl"
  50. #pragma link "PathLabel"
  51. #pragma resource "*.dfm"
  52. //---------------------------------------------------------------------------
  53. #define WM_COMPONENT_HIDE (WM_WINSCP_USER + 4)
  54. #define WM_PASTE_FILES (WM_WINSCP_USER + 14)
  55. static const int SessionPanelCount = 3;
  56. //---------------------------------------------------------------------------
  57. class TMutexGuard
  58. {
  59. public:
  60. TMutexGuard(HANDLE AMutex, int Message = MUTEX_RELEASE_TIMEOUT,
  61. int Timeout = 5000)
  62. {
  63. FMutex = NULL;
  64. unsigned long WaitResult = WaitForSingleObject(AMutex, Timeout);
  65. if (WaitResult == WAIT_TIMEOUT)
  66. {
  67. throw Exception(LoadStr(MUTEX_RELEASE_TIMEOUT));
  68. }
  69. else
  70. {
  71. FMutex = AMutex;
  72. }
  73. }
  74. ~TMutexGuard()
  75. {
  76. if (FMutex != NULL)
  77. {
  78. ReleaseMutex(FMutex);
  79. }
  80. }
  81. private:
  82. HANDLE FMutex;
  83. };
  84. //---------------------------------------------------------------------------
  85. class TWindowLock
  86. {
  87. public:
  88. TWindowLock(TCustomScpExplorerForm * Form) :
  89. FForm(Form)
  90. {
  91. FForm->LockWindow();
  92. }
  93. ~TWindowLock()
  94. {
  95. FForm->UnlockWindow();
  96. }
  97. private:
  98. TCustomScpExplorerForm * FForm;
  99. };
  100. //---------------------------------------------------------------------------
  101. TAutoBatch::TAutoBatch(TCustomScpExplorerForm * Form) :
  102. FForm(Form)
  103. {
  104. FForm->BatchStart(FBatchStorage);
  105. }
  106. //---------------------------------------------------------------------------
  107. TAutoBatch::~TAutoBatch()
  108. {
  109. FForm->BatchEnd(FBatchStorage);
  110. }
  111. //---------------------------------------------------------------------------
  112. struct TTransferOperationParam
  113. {
  114. TTransferOperationParam();
  115. UnicodeString TargetDirectory;
  116. bool Temp;
  117. bool DragDrop;
  118. int Options;
  119. TAutoSwitch Queue;
  120. };
  121. //---------------------------------------------------------------------------
  122. TTransferOperationParam::TTransferOperationParam()
  123. {
  124. Temp = false;
  125. DragDrop = false;
  126. Options = 0;
  127. Queue = asAuto;
  128. }
  129. //---------------------------------------------------------------------------
  130. class TTransferPresetNoteData : public TObject
  131. {
  132. public:
  133. UnicodeString Message;
  134. };
  135. //---------------------------------------------------------------------------
  136. class TTerminalNoteData : public TObject
  137. {
  138. public:
  139. TManagedTerminal * Terminal;
  140. };
  141. //---------------------------------------------------------------------------
  142. __fastcall TCustomScpExplorerForm::TCustomScpExplorerForm(TComponent* Owner):
  143. FFormRestored(false),
  144. TForm(Owner)
  145. {
  146. AddStartupSequence(L"F");
  147. FInvalid = false;
  148. FCurrentSide = osRemote;
  149. FEverShown = false;
  150. FDocks = new TList();
  151. InitControls();
  152. DebugAssert(NonVisualDataModule && !NonVisualDataModule->ScpExplorer);
  153. // So that UpdateCustomCommandsToolbar called from RestoreParams works
  154. NonVisualDataModule->ScpExplorer = this;
  155. RestoreParams();
  156. ConfigurationChanged();
  157. RemoteDirView->Invalidate();
  158. FAutoOperation = false;
  159. FOnFileOperationFinished = NULL;
  160. FPrimaryOperation = foNone;
  161. FForceExecution = false;
  162. FIgnoreNextDialogChar = 0;
  163. FErrorList = NULL;
  164. FSynchronizeProgressForm = NULL;
  165. FProgressForm = NULL;
  166. FRefreshLocalDirectory = false;
  167. FRefreshRemoteDirectory = false;
  168. FDDExtMapFile = NULL;
  169. // CreateMutexW keeps failing with ERROR_NOACCESS
  170. FDDExtMutex = CreateMutexA(NULL, false, AnsiString(DRAG_EXT_MUTEX).c_str());
  171. DebugAssert(FDDExtMutex != NULL);
  172. FDDTargetControl = NULL;
  173. FDelayedDeletionTimer = NULL;
  174. FDelayedDeletionList = new TStringList();
  175. FDDFileList = NULL;
  176. FPendingTempSpaceWarn = false;
  177. FCapturedLog = NULL;
  178. FDragDropOperation = false;
  179. memset(&FHistoryMenu, 0, sizeof(FHistoryMenu));
  180. FAllowTransferPresetAutoSelect = true;
  181. FSessionChanging = false;
  182. FCopyParamDefault = L"";
  183. FSynchronizeController = NULL;
  184. FPendingQueueActionItem = NULL;
  185. FLockLevel = 0;
  186. FLockSuspendLevel = 0;
  187. FDisabledOnLockSuspend = false;
  188. FAlternativeDelete = false;
  189. FTrayIcon = new ::TTrayIcon(0);
  190. FTrayIcon->OnClick = TrayIconClick;
  191. FMaxQueueLength = 0;
  192. FLastContextPopupScreenPoint = TPoint(-1, -1);
  193. FTransferResumeList = NULL;
  194. FDeletedFiles = NULL;
  195. FMoveToQueue = false;
  196. StandaloneOperation = false;
  197. FOnFeedSynchronizeError = NULL;
  198. FOnSynchronizeAbort = NULL;
  199. FSynchronizeTerminal = NULL;
  200. FNeedSession = false;
  201. FDoNotIdleCurrentTerminal = 0;
  202. FIncrementalSearching = 0;
  203. FIncrementalSearchHaveNext = false;
  204. FQueueFileList.reset(new TQueueFileList());
  205. FProgressSide = osCurrent;
  206. FCalculateSizeOperation = NULL;
  207. FDownloadingFromClipboard = false;
  208. FClipboardFakeMonitorsPendingReset = false;
  209. FHiContrastTheme = NULL;
  210. FEditorManager = new TEditorManager();
  211. FEditorManager->OnFileChange = ExecutedFileChanged;
  212. FEditorManager->OnFileReload = ExecutedFileReload;
  213. FEditorManager->OnFileEarlyClosed = ExecutedFileEarlyClosed;
  214. FEditorManager->OnFileUploadComplete = ExecutedFileUploadComplete;
  215. FLocalEditors = new TList();
  216. FQueueStatus = NULL;
  217. FQueueStatusSection = new TCriticalSection();
  218. FQueueStatusInvalidated = false;
  219. FQueueItemInvalidated = false;
  220. FQueueStatusUpdating = false;
  221. FQueueActedItem = NULL;
  222. FQueueController = new TQueueController(QueueView3);
  223. FQueueScrollOnDragOver = new TListViewScrollOnDragOver(QueueView3, true);
  224. FUserActionTimer = new TTimer(this);
  225. FUserActionTimer->Enabled = false;
  226. FUserActionTimer->Interval = 10;
  227. FUserActionTimer->OnTimer = UserActionTimer;
  228. FNotes = new TStringList();
  229. FNoteTimer = new TTimer(this);
  230. FNoteTimer->Enabled = false;
  231. FNoteTimer->OnTimer = NoteTimer;
  232. FOnNoteClick = NULL;
  233. FOle32Library = LoadLibrary(L"Ole32.dll");
  234. FDragMoveCursor = FOle32Library != NULL ?
  235. LoadCursor(FOle32Library, MAKEINTRESOURCE(2)) : NULL;
  236. UseSystemSettings(this);
  237. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  238. static_cast<TObject*>(GetComponent(fcTransferList)));
  239. DebugAssert(TransferList != NULL);
  240. FTransferListHoverIndex = -1;
  241. TransferList->OnChange = TransferListChange;
  242. TransferList->OnDrawItem = TransferListDrawItem;
  243. SetSubmenu(dynamic_cast<TTBXCustomItem *>(static_cast<TObject *>(GetComponent(fcColorMenu))), true);
  244. SetSubmenu(NonVisualDataModule->ColorMenuItem, true);
  245. UseDesktopFont(SessionsPageControl);
  246. UpdateSessionsPageControlHeight();
  247. UseDesktopFont(RemoteDirView);
  248. UseDesktopFont(RemoteDriveView);
  249. UseDesktopFont(QueueView3);
  250. UseDesktopFont(QueueFileList);
  251. UseDesktopFont(QueueLabel);
  252. UseDesktopFont(RemoteStatusBar);
  253. reinterpret_cast<TLabel*>(QueueSplitter)->OnDblClick = QueueSplitterDblClick;
  254. QueueSplitter->ShowHint = true;
  255. reinterpret_cast<TLabel*>(QueueFileListSplitter)->OnDblClick = QueueFileListSplitterDblClick;
  256. QueueFileListSplitter->ShowHint = true;
  257. RemotePanelSplitter->ShowHint = true;
  258. UpdateImages();
  259. FCustomCommandMenu = CreateTBXPopupMenu(this);
  260. FCustomCommandLocalFileList = NULL;
  261. FCustomCommandRemoteFileList = NULL;
  262. FSessionColors = new TPngImageList(this);
  263. FSessionColors->ColorDepth = cd32Bit;
  264. AddFixedSessionImages();
  265. SessionsPageControl->Images = FSessionColors;
  266. UpdateQueueLabel();
  267. CheckStoreTransition();
  268. CreateHiddenWindow();
  269. StartUpdates();
  270. // Start loading drive data, so that they are ready once we need them for StartCreationDirectoryMonitorsOnEachDrive
  271. // (necessary for "explorer" only, as "commander" loads it for its drive menu)
  272. DriveInfo->NeedData();
  273. }
  274. //---------------------------------------------------------------------------
  275. __fastcall TCustomScpExplorerForm::~TCustomScpExplorerForm()
  276. {
  277. FInvalid = true;
  278. ReleaseHiContrastTheme();
  279. if (FClipboardTerminal != NULL)
  280. {
  281. ClipboardClear(); // implies ClipboardStop
  282. }
  283. // this has to be one of the very first things to do
  284. StopUpdateThread();
  285. // This is needed when shuting down Windows only. Otherwise it's already set NULL from Execute()
  286. TTerminalManager::Instance()->ScpExplorer = NULL;
  287. delete FCustomCommandLocalFileList;
  288. delete FCustomCommandRemoteFileList;
  289. delete FCustomCommandMenu;
  290. delete FTrayIcon;
  291. FTrayIcon = NULL;
  292. FEditorManager->CloseInternalEditors(ForceCloseInternalEditor);
  293. delete FEditorManager;
  294. ForceCloseLocalEditors();
  295. delete FLocalEditors;
  296. HideFileFindDialog();
  297. if (FDelayedDeletionTimer)
  298. {
  299. DoDelayedDeletion(NULL);
  300. SAFE_DESTROY(FDelayedDeletionTimer);
  301. }
  302. SAFE_DESTROY(FDelayedDeletionList);
  303. // sometimes we do not get DDEnd so the list is not released
  304. SAFE_DESTROY(FDDFileList);
  305. DebugAssert(FSynchronizeController == NULL);
  306. CloseHandle(FDDExtMutex);
  307. FDDExtMutex = NULL;
  308. FreeLibrary(FOle32Library);
  309. FOle32Library = NULL;
  310. FDragMoveCursor = NULL;
  311. DebugAssert(!FErrorList);
  312. if (FEverShown)
  313. {
  314. // when window is never shown (like when running command-line operation),
  315. // particularly window site is not restored correctly (BoundsRect value set
  316. // in RestoreForm gets lost during handle allocation), so we do not want
  317. // it to be stored
  318. StoreParams();
  319. }
  320. ManagedSession = NULL;
  321. Queue = NULL;
  322. DebugAssert(NonVisualDataModule && (NonVisualDataModule->ScpExplorer == this));
  323. NonVisualDataModule->ScpExplorer = NULL;
  324. delete FQueueScrollOnDragOver;
  325. FQueueScrollOnDragOver = NULL;
  326. delete FQueueController;
  327. FQueueController = NULL;
  328. delete FQueueStatusSection;
  329. FQueueStatusSection = NULL;
  330. delete FQueueStatus;
  331. FQueueStatus = NULL;
  332. delete FUserActionTimer;
  333. FUserActionTimer = NULL;
  334. delete FNoteTimer;
  335. delete FNotes;
  336. delete FNoteData;
  337. SAFE_DESTROY(FDocks);
  338. SessionsPageControl->Images = NULL;
  339. // only after clearing Terminal (after SessionListChanged => ... => AddSessionColor is called)
  340. SAFE_DESTROY(FSessionColors);
  341. SAFE_DESTROY(FSessionsDragDropFilesEx);
  342. SAFE_DESTROY(FHistoryMenu[0][0]);
  343. SAFE_DESTROY(FHistoryMenu[0][1]);
  344. SAFE_DESTROY(FHistoryMenu[1][0]);
  345. SAFE_DESTROY(FHistoryMenu[1][1]);
  346. if (FHiddenWindow != NULL)
  347. {
  348. DestroyWindow(FHiddenWindow);
  349. FHiddenWindow = NULL;
  350. }
  351. }
  352. //---------------------------------------------------------------------------
  353. void TCustomScpExplorerForm::ReleaseHiContrastTheme()
  354. {
  355. if (FHiContrastTheme != NULL)
  356. {
  357. ReleaseTBXTheme(FHiContrastTheme);
  358. FHiContrastTheme = NULL;
  359. }
  360. }
  361. //---------------------------------------------------------------------------
  362. void __fastcall TCustomScpExplorerForm::RefreshPanel(const UnicodeString & Session, const UnicodeString & Path)
  363. {
  364. std::unique_ptr<TSessionData> Data;
  365. if (!Session.IsEmpty())
  366. {
  367. bool DefaultsOnly;
  368. Data.reset(StoredSessions->ParseUrl(Session, NULL, DefaultsOnly));
  369. }
  370. TTerminalManager * Manager = TTerminalManager::Instance();
  371. for (int Index = 0; Index < Manager->Count; Index++)
  372. {
  373. TTerminal * Terminal = Manager->Sessions[Index];
  374. if (Session.IsEmpty() ||
  375. Manager->IsActiveTerminalForSite(Terminal, Data.get()))
  376. {
  377. if (Path.IsEmpty())
  378. {
  379. Terminal->ClearCaches();
  380. }
  381. else
  382. {
  383. Terminal->DirectoryModified(Path, true);
  384. }
  385. }
  386. }
  387. // We should flag a pending refresh for the background terminals or busy foreground terminals
  388. if (HasActiveTerminal() &&
  389. CanCommandLineFromAnotherInstance() &&
  390. (Session.IsEmpty() || Manager->IsActiveTerminalForSite(Terminal, Data.get())) &&
  391. (Path.IsEmpty() || UnixIsChildPath(Path, Terminal->CurrentDirectory)))
  392. {
  393. Terminal->ReloadDirectory();
  394. }
  395. }
  396. //---------------------------------------------------------------------------
  397. void __fastcall TCustomScpExplorerForm::WMCopyData(TMessage & Message)
  398. {
  399. PCOPYDATASTRUCT CopyData = reinterpret_cast<PCOPYDATASTRUCT>(Message.LParam);
  400. AppLogFmt(L"Received copy data message with size %d", (int(CopyData->cbData)));
  401. size_t MessageSize = sizeof(TCopyDataMessage);
  402. bool Result = DebugAlwaysTrue(CopyData->cbData == MessageSize);
  403. if (Result)
  404. {
  405. const TCopyDataMessage & Message = *reinterpret_cast<const TCopyDataMessage *>(CopyData->lpData);
  406. Result = (Message.Version == TCopyDataMessage::Version1);
  407. if (Result)
  408. {
  409. switch (Message.Command)
  410. {
  411. case TCopyDataMessage::CommandCanCommandLine:
  412. Result = CanCommandLineFromAnotherInstance();
  413. if (Result)
  414. {
  415. AppLog(L"Can process command-line from other instance");
  416. }
  417. else
  418. {
  419. AppLog(L"Cannot process command-line from other instance");
  420. }
  421. break;
  422. case TCopyDataMessage::CommandCommandLine:
  423. {
  424. UnicodeString CommandLine(Message.CommandLine);
  425. Result = CommandLineFromAnotherInstance(CommandLine);
  426. }
  427. break;
  428. case TCopyDataMessage::RefreshPanel:
  429. RefreshPanel(Message.Refresh.Session, Message.Refresh.Path);
  430. break;
  431. case TCopyDataMessage::MainWindowCheck:
  432. Result = true;
  433. break;
  434. default:
  435. Result = false;
  436. break;
  437. }
  438. }
  439. }
  440. Message.Result = Result ? 1 : 0;
  441. }
  442. //---------------------------------------------------------------------------
  443. void __fastcall TCustomScpExplorerForm::CreateHiddenWindow()
  444. {
  445. WNDCLASS WindowClass = {0};
  446. WindowClass.lpfnWndProc = DefWindowProc;
  447. WindowClass.hInstance = HInstance;
  448. WindowClass.lpszClassName = HIDDEN_WINDOW_NAME;
  449. FHiddenWindow = NULL;
  450. if (RegisterClass(&WindowClass))
  451. {
  452. FHiddenWindow = CreateWindow(HIDDEN_WINDOW_NAME, L"",
  453. WS_POPUP, 0, 0, 0, 0, 0, 0, HInstance, NULL);
  454. }
  455. }
  456. //---------------------------------------------------------------------------
  457. bool __fastcall TCustomScpExplorerForm::CanConsole()
  458. {
  459. return
  460. HasActiveTerminal() &&
  461. (Terminal->IsCapable[fcAnyCommand] || Terminal->IsCapable[fcSecondaryShell]);
  462. }
  463. //---------------------------------------------------------------------------
  464. bool __fastcall TCustomScpExplorerForm::CanCommandLineFromAnotherInstance()
  465. {
  466. bool Result = Visible && !NonVisualDataModule->Busy;
  467. return Result;
  468. }
  469. //---------------------------------------------------------------------------
  470. bool __fastcall TCustomScpExplorerForm::CommandLineFromAnotherInstance(
  471. const UnicodeString & CommandLine)
  472. {
  473. TProgramParams Params(CommandLine);
  474. bool Result = CanCommandLineFromAnotherInstance() && DebugAlwaysTrue(Params.ParamCount > 0);
  475. if (Result)
  476. {
  477. NonVisualDataModule->StartBusy();
  478. try
  479. {
  480. // this action is initiated from another process,
  481. // so it's likely that our window is not visible,
  482. // and user won't see what is going on
  483. Application->BringToFront();
  484. // reload sessions as we may be asked to open a session
  485. // just stored by another instance
  486. StoredSessions->Reload();
  487. UnicodeString SessionName = Params.Param[1];
  488. std::unique_ptr<TObjectList> DataList(new TObjectList());
  489. try
  490. {
  491. UnicodeString DownloadFile; // unused
  492. int Flags = GetCommandLineParseUrlFlags(&Params);
  493. GetLoginData(SessionName, &Params, DataList.get(), DownloadFile, true, this, Flags);
  494. }
  495. catch (EAbort &)
  496. {
  497. // Happens when opening session in PuTTY and in other situations,
  498. // in which we do not want to fail WM_COPYDATA, as that would cause master instance
  499. // to process the command-line on its own (or to pass it to yet another instance)
  500. }
  501. if (DataList->Count > 0)
  502. {
  503. TTerminalManager * Manager = TTerminalManager::Instance();
  504. Manager->ActiveSession = Manager->NewSessions(DataList.get());
  505. }
  506. }
  507. __finally
  508. {
  509. NonVisualDataModule->EndBusy();
  510. }
  511. }
  512. return Result;
  513. }
  514. //---------------------------------------------------------------------------
  515. TManagedTerminal * TCustomScpExplorerForm::GetTerminal()
  516. {
  517. TManagedTerminal * Result;
  518. if ((FManagedSession != NULL) && !FManagedSession->LocalBrowser)
  519. {
  520. Result = FManagedSession;
  521. }
  522. else
  523. {
  524. Result = NULL;
  525. }
  526. return Result;
  527. }
  528. //---------------------------------------------------------------------------
  529. void __fastcall TCustomScpExplorerForm::SetManagedSession(TManagedTerminal * value)
  530. {
  531. if (FManagedSession != value)
  532. {
  533. TWindowLock Lock(this);
  534. SessionChanging();
  535. DoSetManagedSession(value, false);
  536. }
  537. }
  538. //---------------------------------------------------------------------------
  539. void __fastcall TCustomScpExplorerForm::DoSetManagedSession(TManagedTerminal * value, bool Replace)
  540. {
  541. DebugAssert(!Replace || ((value != NULL) && !value->LocalBrowser));
  542. FManagedSession = value;
  543. {
  544. TValueRestorer<bool> AllowTransferPresetAutoSelectRestorer(FAllowTransferPresetAutoSelect, false);
  545. TAutoFlag SessionChangingFlag(FSessionChanging);
  546. SessionChanged(Replace);
  547. }
  548. if (Terminal != NULL)
  549. {
  550. TransferPresetAutoSelect();
  551. }
  552. // Update app and tab titles, prevented above by FSessionChanging.
  553. UpdateControls();
  554. }
  555. //---------------------------------------------------------------------------
  556. void __fastcall TCustomScpExplorerForm::ReplaceTerminal(TManagedTerminal * value)
  557. {
  558. FEditorManager->ProcessFiles(FileTerminalReplaced, value);
  559. DoSetManagedSession(value, true);
  560. }
  561. //---------------------------------------------------------------------------
  562. void __fastcall TCustomScpExplorerForm::SessionChanging()
  563. {
  564. if (ManagedSession != NULL)
  565. {
  566. UpdateSession(ManagedSession);
  567. }
  568. }
  569. //---------------------------------------------------------------------------
  570. void __fastcall TCustomScpExplorerForm::SessionChanged(bool Replaced)
  571. {
  572. if (ManagedSession != NULL)
  573. {
  574. UpdateSessionColor(static_cast<TColor>(ManagedSession->StateData->Color));
  575. }
  576. if (!TTerminalManager::Instance()->Updating)
  577. {
  578. SessionListChanged();
  579. }
  580. if (Terminal != NULL)
  581. {
  582. TObject * State = NULL;
  583. if (WinConfiguration->PreservePanelState)
  584. {
  585. State = Terminal->RemoteExplorerState;
  586. DirView(osRemote)->AnnounceState(State);
  587. }
  588. try
  589. {
  590. if (Replaced)
  591. {
  592. RemoteDirView->ReplaceTerminal(Terminal);
  593. }
  594. else
  595. {
  596. RemoteDirView->Terminal = Terminal;
  597. }
  598. if (Terminal->Active)
  599. {
  600. Terminal->RefreshDirectory();
  601. }
  602. if (State != NULL)
  603. {
  604. DirView(osRemote)->RestoreState(State);
  605. }
  606. }
  607. __finally
  608. {
  609. DirView(osRemote)->AnnounceState(NULL);
  610. }
  611. }
  612. else
  613. {
  614. RemoteDirView->Terminal = NULL;
  615. }
  616. InitStatusBar();
  617. UpdateTransferList();
  618. // Update panels Enable state before refreshing the labels
  619. UpdateControls();
  620. }
  621. //---------------------------------------------------------------------------
  622. void __fastcall TCustomScpExplorerForm::SetQueue(TTerminalQueue * value)
  623. {
  624. if (Queue != value)
  625. {
  626. if (FQueue != NULL)
  627. {
  628. FQueue->OnListUpdate = NULL;
  629. FQueue->OnQueueItemUpdate = NULL;
  630. }
  631. FQueue = value;
  632. if (FQueue != NULL)
  633. {
  634. DebugAssert(FQueue->OnListUpdate == NULL);
  635. FQueue->OnListUpdate = QueueListUpdate;
  636. DebugAssert(FQueue->OnQueueItemUpdate == NULL);
  637. FQueue->OnQueueItemUpdate = QueueItemUpdate;
  638. }
  639. QueueChanged();
  640. }
  641. }
  642. //---------------------------------------------------------------------------
  643. void __fastcall TCustomScpExplorerForm::QueueView3Deletion(TObject * /*Sender*/,
  644. TListItem * Item)
  645. {
  646. if (FQueueActedItem == Item)
  647. {
  648. FQueueActedItem = NULL;
  649. if ((QueueView3->PopupMenu != NULL) &&
  650. (QueueView3->PopupMenu->PopupComponent == QueueView3))
  651. {
  652. // rather "trick", suggested by Jordan on jrsoftware.toolbar2000
  653. ReleaseCapture();
  654. }
  655. }
  656. if (Item->Data == FPendingQueueActionItem)
  657. {
  658. FPendingQueueActionItem = NULL;
  659. }
  660. }
  661. //---------------------------------------------------------------------------
  662. bool TCustomScpExplorerForm::IsAnythingQueued()
  663. {
  664. return (FQueueStatus != NULL) && (FQueueStatus->ActiveAndPendingPrimaryCount > 0);
  665. }
  666. //---------------------------------------------------------------------------
  667. void __fastcall TCustomScpExplorerForm::UpdateQueueStatus(bool QueueChanging)
  668. {
  669. {
  670. TGuard Guard(FQueueStatusSection);
  671. FQueueStatusInvalidated = false;
  672. if (FQueue != NULL)
  673. {
  674. FQueueStatus = FQueue->CreateStatus(FQueueStatus);
  675. }
  676. }
  677. if ((FQueueStatus != NULL) && (FQueueStatus->Count > FMaxQueueLength))
  678. {
  679. FMaxQueueLength = FQueueStatus->Count;
  680. Configuration->Usage->SetMax(L"MaxQueueLength", FMaxQueueLength);
  681. }
  682. {
  683. TAutoFlag Flag(FQueueStatusUpdating);
  684. FQueueController->UpdateQueueStatus(FQueueStatus);
  685. }
  686. UpdateQueueFileList();
  687. SetQueueProgress();
  688. UpdateQueueView();
  689. bool IsEmpty = !IsAnythingQueued();
  690. if (IsEmpty && (Terminal != NULL))
  691. {
  692. TOnceDoneOperation OnceDoneOperation =
  693. NonVisualDataModule->CurrentQueueOnceEmptyOperation();
  694. NonVisualDataModule->ResetQueueOnceEmptyOperation();
  695. if ((FQueue != NULL) && !WinConfiguration->EnableQueueByDefault && !QueueChanging)
  696. {
  697. FQueue->Enabled = false;
  698. }
  699. if ((OnceDoneOperation != odoIdle) && !NonVisualDataModule->Busy)
  700. {
  701. Terminal->CloseOnCompletion(OnceDoneOperation, LoadStr(CLOSED_ON_QUEUE_EMPTY));
  702. }
  703. }
  704. }
  705. //---------------------------------------------------------------------------
  706. UnicodeString __fastcall TCustomScpExplorerForm::GetQueueProgressTitle()
  707. {
  708. UnicodeString Result;
  709. if (FQueueStatus != NULL)
  710. {
  711. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  712. {
  713. TFileOperationProgressType * ProgressData =
  714. FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  715. if ((ProgressData != NULL) && ProgressData->InProgress)
  716. {
  717. Result = TProgressForm::ProgressStr(NULL, ProgressData);
  718. }
  719. }
  720. else if (FQueueStatus->ActiveAndPendingPrimaryCount > 1)
  721. {
  722. Result = FMTLOAD(PROGRESS_IN_QUEUE, (FQueueStatus->ActiveAndPendingPrimaryCount));
  723. }
  724. }
  725. return Result;
  726. }
  727. //---------------------------------------------------------------------------
  728. void __fastcall TCustomScpExplorerForm::UpdateQueueView()
  729. {
  730. ComponentVisible[fcQueueView] =
  731. !IsLocalBrowserMode() &&
  732. ((WinConfiguration->QueueView.Show == qvShow) ||
  733. ((WinConfiguration->QueueView.Show == qvHideWhenEmpty) &&
  734. (FQueueStatus != NULL) && (FQueueStatus->Count > 0)));
  735. }
  736. //---------------------------------------------------------------------------
  737. void __fastcall TCustomScpExplorerForm::QueueChanged()
  738. {
  739. if (FQueueStatus != NULL)
  740. {
  741. // UpdateFileList implementation relies on the status being recreated when session changes
  742. delete FQueueStatus;
  743. FQueueStatus = NULL;
  744. }
  745. UpdateQueueStatus(true);
  746. }
  747. //---------------------------------------------------------------------------
  748. void __fastcall TCustomScpExplorerForm::QueueListUpdate(TTerminalQueue * Queue)
  749. {
  750. if (FQueue == Queue)
  751. {
  752. FQueueStatusInvalidated = true;
  753. }
  754. }
  755. //---------------------------------------------------------------------------
  756. void __fastcall TCustomScpExplorerForm::QueueItemUpdate(TTerminalQueue * Queue,
  757. TQueueItem * Item)
  758. {
  759. if (FQueue == Queue)
  760. {
  761. TGuard Guard(FQueueStatusSection);
  762. // this may be running in parallel with QueueChanged
  763. if (FQueueStatus != NULL)
  764. {
  765. TQueueItemProxy * QueueItem = FQueueStatus->FindByQueueItem(Item);
  766. if ((Item->Status == TQueueItem::qsDone) && (Terminal != NULL))
  767. {
  768. FRefreshLocalDirectory = (QueueItem == NULL) ||
  769. (!QueueItem->Info->ModifiedLocal.IsEmpty());
  770. FRefreshRemoteDirectory = (QueueItem == NULL) ||
  771. (!QueueItem->Info->ModifiedRemote.IsEmpty());
  772. }
  773. if (QueueItem != NULL)
  774. {
  775. QueueItem->UserData = (void*)true;
  776. FQueueItemInvalidated = true;
  777. }
  778. }
  779. }
  780. }
  781. //---------------------------------------------------------------------------
  782. bool __fastcall TCustomScpExplorerForm::IsQueueAutoPopup()
  783. {
  784. // during standalone editing, we have no way to see/control queue,
  785. // so we have to always popup prompts automatically
  786. return StandaloneOperation || GUIConfiguration->QueueAutoPopup;
  787. }
  788. //---------------------------------------------------------------------------
  789. void __fastcall TCustomScpExplorerForm::RefreshQueueItems()
  790. {
  791. if (FQueueStatus != NULL)
  792. {
  793. bool QueueAutoPopup = IsQueueAutoPopup();
  794. bool NeedRefresh = FQueueController->NeedRefresh();
  795. bool Refresh = FQueueItemInvalidated || NeedRefresh;
  796. FQueueItemInvalidated = false;
  797. int Limit = Refresh ? FQueueStatus->Count : FQueueStatus->DoneAndActiveCount;
  798. bool Updated = false;
  799. TQueueItemProxy * QueueItem;
  800. bool WasUserAction;
  801. for (int Index = 0; Index < Limit; Index++)
  802. {
  803. bool Update = false;
  804. QueueItem = FQueueStatus->Items[Index];
  805. WasUserAction = TQueueItem::IsUserActionStatus(QueueItem->Status);
  806. if (!NonVisualDataModule->Busy && QueueAutoPopup && WasUserAction &&
  807. (FPendingQueueActionItem == NULL))
  808. {
  809. FPendingQueueActionItem = QueueItem;
  810. FUserActionTimer->Enabled = true;
  811. }
  812. if ((bool)QueueItem->UserData)
  813. {
  814. QueueItem->UserData = (void*)false;
  815. QueueItem->Update();
  816. Updated = true;
  817. Update = true;
  818. }
  819. else if (FQueueController->QueueItemNeedsFrequentRefresh(QueueItem) || NeedRefresh)
  820. {
  821. Update = true;
  822. }
  823. if (Update)
  824. {
  825. FQueueController->RefreshQueueItem(QueueItem);
  826. }
  827. }
  828. if (Updated)
  829. {
  830. NonVisualDataModule->UpdateNonVisibleActions();
  831. SetQueueProgress();
  832. UpdateQueueFileList();
  833. }
  834. }
  835. }
  836. //---------------------------------------------------------------------------
  837. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressState(TBPFLAG Flags)
  838. {
  839. if (FTaskbarList != NULL)
  840. {
  841. // Could now use Application->MainFormHandle, now that we implement Application->OnGetMainFormHandle
  842. FTaskbarList->SetProgressState(GetMainForm()->Handle, Flags);
  843. }
  844. }
  845. //---------------------------------------------------------------------------
  846. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(int Progress)
  847. {
  848. if (Progress >= 0)
  849. {
  850. if (FTaskbarList != NULL)
  851. {
  852. FTaskbarList->SetProgressValue(GetMainForm()->Handle, Progress, 100);
  853. }
  854. }
  855. else
  856. {
  857. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  858. }
  859. }
  860. //---------------------------------------------------------------------------
  861. void __fastcall TCustomScpExplorerForm::SetTaskbarListProgressValue(TFileOperationProgressType * ProgressData)
  862. {
  863. int OverallProgress;
  864. // FProgressForm is null when this is called from SetQueueProgress
  865. if ((FProgressForm != NULL) && (FProgressForm->SynchronizeProgress != NULL))
  866. {
  867. OverallProgress = FProgressForm->SynchronizeProgress->Progress(ProgressData);
  868. }
  869. else if (!ProgressData->IsIndeterminate())
  870. {
  871. OverallProgress = ProgressData->OverallProgress();
  872. }
  873. else
  874. {
  875. OverallProgress = -1;
  876. }
  877. SetTaskbarListProgressValue(OverallProgress);
  878. }
  879. //---------------------------------------------------------------------------
  880. void __fastcall TCustomScpExplorerForm::SetQueueProgress()
  881. {
  882. TTerminalManager::Instance()->QueueStatusUpdated();
  883. if ((FTaskbarList != NULL) && (FProgressForm == NULL))
  884. {
  885. // Do not animate task bar button, when items are queued, but processing is disabled
  886. if ((FQueueStatus != NULL) && (FQueueStatus->ActivePrimaryCount > 0))
  887. {
  888. if (FQueueStatus->IsOnlyOneActiveAndNoPending())
  889. {
  890. TFileOperationProgressType * ProgressData = NULL;
  891. if (FQueueStatus->Items[FQueueStatus->DoneCount] != NULL)
  892. {
  893. ProgressData = FQueueStatus->Items[FQueueStatus->DoneCount]->ProgressData;
  894. }
  895. if ((ProgressData != NULL) &&
  896. ProgressData->InProgress)
  897. {
  898. SetTaskbarListProgressValue(ProgressData);
  899. }
  900. else
  901. {
  902. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  903. }
  904. }
  905. else
  906. {
  907. SetTaskbarListProgressState(TBPF_INDETERMINATE);
  908. }
  909. }
  910. else
  911. {
  912. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  913. }
  914. }
  915. UpdateQueueLabel();
  916. }
  917. //---------------------------------------------------------------------------
  918. void __fastcall TCustomScpExplorerForm::UpdateQueueLabel()
  919. {
  920. UnicodeString Caption = LoadStr(QUEUE_CAPTION);
  921. if (FQueueStatus != NULL)
  922. {
  923. int ActiveAndPendingPrimaryCount = FQueueStatus->ActiveAndPendingPrimaryCount;
  924. if (ActiveAndPendingPrimaryCount > 0)
  925. {
  926. Caption = FORMAT("%s (%d)", (Caption, ActiveAndPendingPrimaryCount));
  927. }
  928. }
  929. QueueLabel->Caption = Caption;
  930. }
  931. //---------------------------------------------------------------------------
  932. void TCustomScpExplorerForm::CheckStoreTransition()
  933. {
  934. if (WinConfiguration->StoreTransition == stInit)
  935. {
  936. if (IsUWP())
  937. {
  938. WinConfiguration->StoreTransition = stStoreFresh;
  939. AppLog(L"Fresh UWP/store installation");
  940. }
  941. else
  942. {
  943. WinConfiguration->StoreTransition = stStandard;
  944. AppLog(L"Fresh standard installation");
  945. }
  946. }
  947. else if ((WinConfiguration->StoreTransition == stStandard) && IsUWP())
  948. {
  949. WinConfiguration->StoreTransition = stStoreMigrated;
  950. WinConfiguration->FirstRun = WinConfiguration->FirstRun + L"=>" + StandardDatestamp();
  951. AppLog(L"Standard installation migrated to store installation");
  952. }
  953. if (WinConfiguration->StoreTransition == stStoreMigrated)
  954. {
  955. TTBXToolbar * Toolbar = new TTBXToolbar(MessageDock);
  956. Toolbar->Parent = MessageDock;
  957. Toolbar->FullSize = true;
  958. Toolbar->Color = Application->HintColor;
  959. TTBXLabelItem * LabelItem;
  960. LabelItem = new TTBXLabelItem(Toolbar);
  961. // Convert to explicit RGB "black" color, to make sure it is contrasting even in Dark theme
  962. // (TTBXOfficeXPTheme.GetStandardColor would convert clWindow to "white" in dark theme)
  963. LabelItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  964. LabelItem->Margin = ScaleByTextHeight(MessageDock, 2); // Is this automatically rescaled?
  965. LabelItem->Caption = LoadStr(STORE_MIGRATION_THANKS);
  966. Toolbar->Items->Add(LabelItem);
  967. TTBXCustomItem * LinkItem = new TTBXItem(Toolbar);
  968. LinkItem->FontSettings->Color = LinkColor;
  969. LinkItem->Caption = LoadStr(STORE_MIGRATION_LEARN);
  970. LinkItem->OnClick = StoreTransitionLinkClick;
  971. Toolbar->Items->Add(LinkItem);
  972. AddMenuSeparator(Toolbar->Items);
  973. TTBXCustomItem * CloseItem = new TTBXItem(Toolbar);
  974. CloseItem->FontSettings->Color = static_cast<TColor>(GetSysColor(clWindow));
  975. CloseItem->Caption = LoadStr(MESSAGE_DISMISS);
  976. CloseItem->OnClick = StoreTransitionCloseClick;
  977. Toolbar->Items->Add(CloseItem);
  978. GiveTBItemPriority(CloseItem);
  979. }
  980. }
  981. //---------------------------------------------------------------------------
  982. void __fastcall TCustomScpExplorerForm::StoreTransitionLinkClick(TObject *)
  983. {
  984. ShowHelp(HELP_STORE_TRANSITION);
  985. }
  986. //---------------------------------------------------------------------------
  987. void __fastcall TCustomScpExplorerForm::StoreTransitionCloseClick(TObject * Sender)
  988. {
  989. TTBCustomItem * Item = DebugNotNull(dynamic_cast<TTBCustomItem *>(Sender));
  990. TTBXToolbar * Toolbar = DebugNotNull(dynamic_cast<TTBXToolbar *>(DebugNotNull(DebugNotNull(Item->Parent)->ParentComponent)));
  991. delete Toolbar;
  992. WinConfiguration->StoreTransition = stStoreAcknowledged;
  993. UpdateControls();
  994. }
  995. //---------------------------------------------------------------------------
  996. void __fastcall TCustomScpExplorerForm::UpdateTransferList()
  997. {
  998. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  999. static_cast<TComponent*>(GetComponent(fcTransferList)));
  1000. TTBXDropDownItem * TransferDropDown = dynamic_cast<TTBXDropDownItem*>(
  1001. static_cast<TComponent*>(GetComponent(fcTransferDropDown)));
  1002. TransferList->Strings->BeginUpdate();
  1003. try
  1004. {
  1005. TransferList->Strings->Assign(GUIConfiguration->CopyParamList->NameList);
  1006. TransferList->Strings->Insert(0, StripHotkey(LoadStr(COPY_PARAM_DEFAULT)));
  1007. TransferList->ItemIndex = GUIConfiguration->CopyParamIndex + 1;
  1008. if (FTransferDropDownHint.IsEmpty())
  1009. {
  1010. FTransferDropDownHint = TransferDropDown->Hint;
  1011. }
  1012. // this way we get name for "default" settings (COPY_PARAM_DEFAULT)
  1013. UnicodeString Name = TransferList->Strings->Strings[TransferList->ItemIndex];
  1014. TransferDropDown->Text = StripHotkey(Name);
  1015. TransferDropDown->Hint = FORMAT(L"%s|%s:\n%s",
  1016. (FTransferDropDownHint, StripHotkey(Name),
  1017. GUIConfiguration->CurrentCopyParam.GetInfoStr(L"; ",
  1018. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General))));
  1019. // update the label, otherwise when it is updated only on the first draw
  1020. // of the list, it is drawn "bold" for some reason
  1021. FTransferListHoverIndex = TransferList->ItemIndex;
  1022. UpdateTransferLabel();
  1023. }
  1024. __finally
  1025. {
  1026. TransferList->Strings->EndUpdate();
  1027. }
  1028. }
  1029. //---------------------------------------------------------------------------
  1030. void __fastcall TCustomScpExplorerForm::UpdateCustomCommandsToolbar()
  1031. {
  1032. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar *>(GetComponent(fcCustomCommandsBand));
  1033. DebugAssert(Toolbar != NULL);
  1034. NonVisualDataModule->UpdateCustomCommandsToolbar(Toolbar);
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. void __fastcall TCustomScpExplorerForm::UpdateActions()
  1038. {
  1039. TForm::UpdateActions();
  1040. if (ComponentVisible[fcCustomCommandsBand])
  1041. {
  1042. UpdateCustomCommandsToolbar();
  1043. }
  1044. }
  1045. //---------------------------------------------------------------------------
  1046. void __fastcall TCustomScpExplorerForm::UpdateSessionsPageControlHeight()
  1047. {
  1048. SessionsPageControl->Height = SessionsPageControl->GetTabsHeight();
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. void __fastcall TCustomScpExplorerForm::UpdateRowSelect(TCustomDirView * DirView)
  1052. {
  1053. if (DirView->RowSelect != WinConfiguration->FullRowSelect)
  1054. {
  1055. DirView->RowSelect = WinConfiguration->FullRowSelect;
  1056. // Without this, the panel turns gray and unused part of header turns black
  1057. DirView->Perform(CM_COLORCHANGED, 0, 0);
  1058. }
  1059. }
  1060. //---------------------------------------------------------------------------
  1061. void __fastcall TCustomScpExplorerForm::ConfigurationChanged()
  1062. {
  1063. Color = GetBtnFaceColor();
  1064. DebugAssert(Configuration && RemoteDirView);
  1065. RemoteDirView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1066. RemoteDirView->DimmHiddenFiles = WinConfiguration->DimmHiddenFiles;
  1067. RemoteDirView->ShowHiddenFiles = WinConfiguration->ShowHiddenFiles;
  1068. RemoteDirView->FormatSizeBytes = WinConfiguration->FormatSizeBytes;
  1069. RemoteDirView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1070. RemoteDirView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1071. RemoteDirView->AlwaysSortDirectoriesByName = WinConfiguration->AlwaysSortDirectoriesByName;
  1072. UpdateRowSelect(RemoteDirView);
  1073. RemoteDriveView->DDAllowMove = !WinConfiguration->DDDisableMove;
  1074. RemoteDriveView->DimmHiddenDirs = WinConfiguration->DimmHiddenFiles;
  1075. RemoteDriveView->ShowHiddenDirs = WinConfiguration->ShowHiddenFiles;
  1076. RemoteDriveView->ShowInaccesibleDirectories = WinConfiguration->ShowInaccesibleDirectories;
  1077. RemoteDriveView->NaturalOrderNumericalSorting = WinConfiguration->NaturalOrderNumericalSorting;
  1078. UpdateSessionsPageControlHeight();
  1079. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1080. UpdateToolbarDisplayMode();
  1081. UpdateTransferList();
  1082. if (Terminal != NULL)
  1083. {
  1084. TransferPresetAutoSelect();
  1085. }
  1086. UpdateQueueView();
  1087. UpdateControls();
  1088. // this can be called even before constuctor finishes.
  1089. if (FEditorManager != NULL)
  1090. {
  1091. FEditorManager->ProcessFiles(FileConfigurationChanged, NULL);
  1092. }
  1093. // this can be called even before constuctor finishes.
  1094. if (FLocalEditors != NULL)
  1095. {
  1096. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  1097. {
  1098. ReconfigureEditorForm(static_cast<TForm *>(FLocalEditors->Items[Index]));
  1099. }
  1100. }
  1101. if (ComponentVisible[fcCustomCommandsBand])
  1102. {
  1103. UpdateCustomCommandsToolbar();
  1104. }
  1105. // show only when keeping queue items forever,
  1106. // otherwise, it's enough to have it in the context menu
  1107. QueueDeleteAllDoneQueueToolbarItem->Visible =
  1108. WinConfiguration->QueueKeepDoneItems && (WinConfiguration->QueueKeepDoneItemsFor < 0);
  1109. if (FFileColorsCurrent != WinConfiguration->FileColors)
  1110. {
  1111. TFileColorData::LoadList(WinConfiguration->FileColors, FFileColors);
  1112. FFileColorsCurrent = WinConfiguration->FileColors;
  1113. FileColorsChanged();
  1114. }
  1115. if ((GetNewTabTab()->CaptionTruncation != GetNewTabTabCaptionTruncation()) &&
  1116. (FSessionColors != NULL))
  1117. {
  1118. SessionListChanged();
  1119. }
  1120. }
  1121. //---------------------------------------------------------------------------
  1122. void __fastcall TCustomScpExplorerForm::DoFileColorsChanged(TCustomDirView * DirView)
  1123. {
  1124. DirView->OnGetItemColor = FFileColors.empty() ? TDirViewGetItemColorEvent(NULL) : TDirViewGetItemColorEvent(&DirViewGetItemColor);
  1125. DirView->Invalidate();
  1126. }
  1127. //---------------------------------------------------------------------------
  1128. void __fastcall TCustomScpExplorerForm::FileColorsChanged()
  1129. {
  1130. DoFileColorsChanged(RemoteDirView);
  1131. }
  1132. //---------------------------------------------------------------------------
  1133. void __fastcall TCustomScpExplorerForm::FileConfigurationChanged(
  1134. const UnicodeString FileName, TEditedFileData * /*Data*/, TObject * Token,
  1135. void * /*Arg*/)
  1136. {
  1137. if (Token != NULL)
  1138. {
  1139. TForm * Editor = dynamic_cast<TForm*>(Token);
  1140. DebugAssert(Editor != NULL);
  1141. ReconfigureEditorForm(Editor);
  1142. }
  1143. }
  1144. //---------------------------------------------------------------------------
  1145. void __fastcall TCustomScpExplorerForm::EnableDDTransferConfirmation(TObject * /*Sender*/)
  1146. {
  1147. WinConfiguration->DDTransferConfirmation = asOn;
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TCustomScpExplorerForm::CopyParamDialogAfter(
  1151. TTransferDirection /*Direction*/, bool /*Temp*/, const UnicodeString & /*TargetDirectory*/)
  1152. {
  1153. // noop
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. bool TCustomScpExplorerForm::GetDoNotShowCopyDialogDefault(bool DragDrop)
  1157. {
  1158. return DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto);
  1159. }
  1160. //---------------------------------------------------------------------------
  1161. void TCustomScpExplorerForm::HandleDoNotShowCopyDialogAgain(bool DragDrop, bool DoNotShowAgain)
  1162. {
  1163. if (DoNotShowAgain)
  1164. {
  1165. if (DragDrop)
  1166. {
  1167. if (WinConfiguration->DDTransferConfirmation == asAuto)
  1168. {
  1169. PopupTrayBalloon(
  1170. NULL, LoadStr(DD_TRANSFER_CONFIRM_OFF2), qtInformation, NULL, 0, EnableDDTransferConfirmation, NULL);
  1171. }
  1172. WinConfiguration->DDTransferConfirmation = asOff;
  1173. }
  1174. else
  1175. {
  1176. WinConfiguration->ConfirmTransferring = false;
  1177. }
  1178. }
  1179. else
  1180. {
  1181. // User explicitly unchecked "do not show again",
  1182. // so show him the dialog the next time
  1183. if (DragDrop && (WinConfiguration->DDTransferConfirmation == asAuto))
  1184. {
  1185. WinConfiguration->DDTransferConfirmation = asOn;
  1186. }
  1187. }
  1188. }
  1189. //---------------------------------------------------------------------------
  1190. bool __fastcall TCustomScpExplorerForm::CopyParamDialog(
  1191. TTransferDirection Direction, TTransferType Type, bool Temp,
  1192. TStrings * FileList, UnicodeString & TargetDirectory, TGUICopyParamType & CopyParam,
  1193. bool Confirm, bool DragDrop, int Options)
  1194. {
  1195. bool Result = true;
  1196. DebugAssert(HasActiveTerminal());
  1197. // these parameters are known in advance
  1198. int Params =
  1199. FLAGMASK(Type == ttMove, cpDelete);
  1200. bool ToTemp = (Temp && (Direction == tdToLocal));
  1201. if (Result && Confirm && WinConfiguration->ConfirmTransferring)
  1202. {
  1203. bool DisableNewerOnly =
  1204. (!Terminal->IsCapable[fcNewerOnlyUpload] && (Direction == tdToRemote)) ||
  1205. ToTemp;
  1206. Options |=
  1207. FLAGMASK(ToTemp, coTemp) |
  1208. FLAGMASK(!Terminal->IsCapable[fcBackgroundTransfers], coDisableQueue) |
  1209. coDoNotShowAgain;
  1210. TUsableCopyParamAttrs UsableCopyParamAttrs = Terminal->UsableCopyParamAttrs(Params);
  1211. int CopyParamAttrs = (Direction == tdToRemote ?
  1212. UsableCopyParamAttrs.Upload : UsableCopyParamAttrs.Download) |
  1213. FLAGMASK(DisableNewerOnly, cpaNoNewerOnly);
  1214. int OutputOptions = FLAGMASK(GetDoNotShowCopyDialogDefault(DragDrop), cooDoNotShowAgain);
  1215. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  1216. FlashOnBackground(); // Particularly when called from ClipboardFakeCreated
  1217. Result = DoCopyDialog(Direction == tdToRemote, Type == ttMove,
  1218. FileList, TargetDirectory, &CopyParam, Options, CopyParamAttrs, SessionData.get(), &OutputOptions, -1);
  1219. if (Result)
  1220. {
  1221. HandleDoNotShowCopyDialogAgain(DragDrop, FLAGSET(OutputOptions, cooDoNotShowAgain));
  1222. CopyParamDialogAfter(Direction, Temp, TargetDirectory);
  1223. }
  1224. }
  1225. if (Result && CopyParam.Queue && !ToTemp && Terminal->IsCapable[fcBackgroundTransfers])
  1226. {
  1227. Configuration->Usage->Inc(L"TransfersOnBackground");
  1228. // these parameter are known only after transfer dialog
  1229. Params |=
  1230. (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  1231. AddQueueItem(Queue, Direction, FileList, TargetDirectory, CopyParam, Params);
  1232. Result = false;
  1233. ClearTransferSourceSelection(Direction);
  1234. }
  1235. return Result;
  1236. }
  1237. //---------------------------------------------------------------------------
  1238. void TCustomScpExplorerForm::ClearOperationSelection(TOperationSide Side)
  1239. {
  1240. if (FOnFileOperationFinished != NULL)
  1241. {
  1242. FOnFileOperationFinished(Side, UnicodeString(), true);
  1243. }
  1244. else
  1245. {
  1246. if (HasDirView[Side])
  1247. {
  1248. DirView(Side)->SelectAll(smNone);
  1249. }
  1250. }
  1251. }
  1252. //---------------------------------------------------------------------------
  1253. void __fastcall TCustomScpExplorerForm::ClearTransferSourceSelection(TTransferDirection Direction)
  1254. {
  1255. TOperationSide Side = ((Direction == tdToRemote) ? osLocal : osRemote);
  1256. ClearOperationSelection(Side);
  1257. }
  1258. //---------------------------------------------------------------------------
  1259. void __fastcall TCustomScpExplorerForm::AddQueueItem(
  1260. TTerminalQueue * Queue, TTransferDirection Direction, TStrings * FileList,
  1261. const UnicodeString TargetDirectory, TGUICopyParamType & CopyParam,
  1262. int Params)
  1263. {
  1264. DebugAssert(Queue != NULL);
  1265. bool SingleFile = false;
  1266. if (FileList->Count == 1)
  1267. {
  1268. if (Direction == tdToRemote)
  1269. {
  1270. UnicodeString FileName = FileList->Strings[0];
  1271. SingleFile = FileExists(ApiPath(FileName));
  1272. }
  1273. else
  1274. {
  1275. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[0]);
  1276. SingleFile = !File->IsDirectory;
  1277. }
  1278. }
  1279. TQueueItem * QueueItem;
  1280. if (Direction == tdToRemote)
  1281. {
  1282. CopyParam.IncludeFileMask.SetRoots(FileList, TargetDirectory);
  1283. QueueItem = new TUploadQueueItem(Terminal, FileList, TargetDirectory,
  1284. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1285. }
  1286. else
  1287. {
  1288. CopyParam.IncludeFileMask.SetRoots(TargetDirectory, FileList);
  1289. QueueItem = new TDownloadQueueItem(Terminal, FileList, TargetDirectory,
  1290. &CopyParam, Params, SingleFile, CopyParam.QueueParallel);
  1291. }
  1292. AddQueueItem(Queue, QueueItem, Terminal);
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. void __fastcall TCustomScpExplorerForm::AddQueueItem(TTerminalQueue * Queue, TQueueItem * QueueItem, TManagedTerminal * Terminal)
  1296. {
  1297. if (Queue->IsEmpty)
  1298. {
  1299. Terminal->QueueOperationStart = Now();
  1300. }
  1301. Queue->AddItem(QueueItem);
  1302. }
  1303. //---------------------------------------------------------------------------
  1304. void __fastcall TCustomScpExplorerForm::RestoreFormParams()
  1305. {
  1306. }
  1307. //---------------------------------------------------------------------------
  1308. void __fastcall TCustomScpExplorerForm::InitControls()
  1309. {
  1310. DebugAssert(FDocks != NULL);
  1311. for (int Index = 0; Index < ComponentCount; Index++)
  1312. {
  1313. TTBDock * Dock = dynamic_cast<TTBDock *>(Components[Index]);
  1314. if ((Dock != NULL) && (Dock->Tag == 0))
  1315. {
  1316. FDocks->Add(Dock);
  1317. }
  1318. }
  1319. CollectItemsWithTextDisplayMode(this);
  1320. }
  1321. //---------------------------------------------------------------------------
  1322. void __fastcall TCustomScpExplorerForm::RestoreParams()
  1323. {
  1324. ConfigurationChanged();
  1325. QueuePanel->Height =
  1326. LoadDimension(WinConfiguration->QueueView.Height, WinConfiguration->QueueView.HeightPixelsPerInch, this);
  1327. LoadListViewStr(QueueView3, WinConfiguration->QueueView.Layout);
  1328. QueueDock->Visible = WinConfiguration->QueueView.ToolBar;
  1329. QueueLabel->Visible = WinConfiguration->QueueView.Label;
  1330. QueueFileList->Visible = WinConfiguration->QueueView.FileList;
  1331. QueueFileList->Height =
  1332. LoadDimension(WinConfiguration->QueueView.FileListHeight, WinConfiguration->QueueView.FileListHeightPixelsPerInch, this);
  1333. if (QueueFileList->Visible)
  1334. {
  1335. AdjustQueueLayout();
  1336. }
  1337. UpdateCustomCommandsToolbar();
  1338. }
  1339. //---------------------------------------------------------------------------
  1340. void __fastcall TCustomScpExplorerForm::StoreParams()
  1341. {
  1342. int APixelsPerInch = GetControlPixelsPerInch(this);
  1343. WinConfiguration->QueueView.Height = QueuePanel->Height;
  1344. WinConfiguration->QueueView.HeightPixelsPerInch = APixelsPerInch;
  1345. WinConfiguration->QueueView.Layout = GetListViewStr(QueueView3);
  1346. WinConfiguration->QueueView.ToolBar = QueueDock->Visible;
  1347. WinConfiguration->QueueView.Label = QueueLabel->Visible;
  1348. WinConfiguration->QueueView.FileList = QueueFileList->Visible;
  1349. WinConfiguration->QueueView.FileListHeight = QueueFileList->Height;
  1350. WinConfiguration->QueueView.FileListHeightPixelsPerInch = APixelsPerInch;
  1351. }
  1352. //---------------------------------------------------------------------------
  1353. void __fastcall TCustomScpExplorerForm::CreateParams(TCreateParams & Params)
  1354. {
  1355. if (!FFormRestored)
  1356. {
  1357. FFormRestored = true;
  1358. RestoreFormParams();
  1359. }
  1360. TForm::CreateParams(Params);
  1361. }
  1362. //---------------------------------------------------------------------------
  1363. void __fastcall TCustomScpExplorerForm::SetDockAllowDrag(bool value)
  1364. {
  1365. DebugAssert(FDocks != NULL);
  1366. for (int Index = 0; Index < FDocks->Count; Index++)
  1367. {
  1368. static_cast<TTBDock*>(FDocks->Items[Index])->AllowDrag = value;
  1369. }
  1370. }
  1371. //---------------------------------------------------------------------------
  1372. void __fastcall TCustomScpExplorerForm::LoadToolbarsLayoutStr(UnicodeString LayoutStr, UnicodeString ButtonsStr)
  1373. {
  1374. SetDockAllowDrag(true);
  1375. while (!ButtonsStr.IsEmpty())
  1376. {
  1377. UnicodeString S = CutToChar(ButtonsStr, L';', true);
  1378. UnicodeString Name = CutToChar(S, L'=', true);
  1379. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1380. {
  1381. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1382. if ((Toolbar != NULL) && SameText(Name, GetToolbarKey(Toolbar->Name)))
  1383. {
  1384. while (!S.IsEmpty())
  1385. {
  1386. UnicodeString S2 = CutToChar(S, L',', true);
  1387. UnicodeString Name = CutToChar(S2, L':', true);
  1388. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1389. {
  1390. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1391. if (SameText(GetToolbarItemName(Item), Name))
  1392. {
  1393. // forward compatibility
  1394. UnicodeString S3 = CutToChar(S2, L':', true);
  1395. bool Visible = StrToIntDef(S3, 0);
  1396. Item->Visible = Visible;
  1397. }
  1398. }
  1399. }
  1400. }
  1401. }
  1402. }
  1403. ::LoadToolbarsLayoutStr(this, LayoutStr);
  1404. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1405. }
  1406. //---------------------------------------------------------------------------
  1407. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsLayoutStr()
  1408. {
  1409. UnicodeString Result;
  1410. SetDockAllowDrag(true);
  1411. Result = ::GetToolbarsLayoutStr(this);
  1412. SetDockAllowDrag(!WinConfiguration->LockToolbars);
  1413. return Result;
  1414. }
  1415. //---------------------------------------------------------------------------
  1416. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarItemName(TTBCustomItem * Item)
  1417. {
  1418. UnicodeString Result;
  1419. if (Item->Action != NULL)
  1420. {
  1421. Result = Item->Action->Name;
  1422. Result = RemoveSuffix(Result, L"Action", true);
  1423. }
  1424. else
  1425. {
  1426. Result = Item->Name;
  1427. Result = RemoveSuffix(Result, L"SubmenuItem", true);
  1428. Result = RemoveSuffix(Result, L"Item", true);
  1429. }
  1430. return Result;
  1431. }
  1432. //---------------------------------------------------------------------------
  1433. UnicodeString __fastcall TCustomScpExplorerForm::GetToolbarsButtonsStr()
  1434. {
  1435. UnicodeString Result;
  1436. for (int ToolbarIndex = 0; ToolbarIndex < ComponentCount; ToolbarIndex++)
  1437. {
  1438. UnicodeString ToolbarStr;
  1439. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(Components[ToolbarIndex]);
  1440. if ((Toolbar != NULL) && (Toolbar != QueueToolbar))
  1441. {
  1442. for (int ItemIndex = 0; ItemIndex < Toolbar->Items->Count; ItemIndex++)
  1443. {
  1444. TTBCustomItem * Item = Toolbar->Items->Items[ItemIndex];
  1445. // Currently all buttons are visible by default, so we can safely remember all hidden buttons.
  1446. // Once we introduce any buttons that are hidden by default, we would have to remember their initial state
  1447. // and save the changes here only.
  1448. if (NonVisualDataModule->IsCustomizableToolbarItem(Item) && !Item->Visible)
  1449. {
  1450. UnicodeString Name = GetToolbarItemName(Item);
  1451. DebugAssert(Name.Pos(L"TBX") == 0);
  1452. AddToList(ToolbarStr, FORMAT(L"%s:0", (Name)), L",");
  1453. }
  1454. }
  1455. }
  1456. if (!ToolbarStr.IsEmpty())
  1457. {
  1458. AddToList(Result, FORMAT(L"%s=%s", (GetToolbarKey(Toolbar->Name), ToolbarStr)), L";");
  1459. }
  1460. }
  1461. return Result;
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. void __fastcall TCustomScpExplorerForm::CreateProgressForm(TSynchronizeProgress * SynchronizeProgress)
  1465. {
  1466. DebugAssert(FProgressForm == NULL);
  1467. bool AllowSkip = HasActiveTerminal() ? Terminal->IsCapable[fcSkipTransfer] : false;
  1468. bool AllowMoveToQueue = (FTransferResumeList != NULL) || (FDeletedFiles != NULL);
  1469. FProgressForm = new TProgressForm(Application, AllowMoveToQueue, AllowSkip, SynchronizeProgress);
  1470. FProgressForm->DeleteLocalToRecycleBin =
  1471. (WinConfiguration->DeleteToRecycleBin != FAlternativeDelete);
  1472. FProgressForm->DeleteRemoteToRecycleBin =
  1473. HasActiveTerminal() &&
  1474. (Terminal->SessionData->DeleteToRecycleBin != FAlternativeDelete) &&
  1475. !Terminal->SessionData->RecycleBinPath.IsEmpty();
  1476. // As progress window has delayed show now, we need to lock ourselves, (at least) until then
  1477. LockWindow();
  1478. // Actually, do not know what hides the progress once the operation finishes
  1479. // (it is possibly the SetQueueProgress - and we should not rely on that)
  1480. SetTaskbarListProgressState(TBPF_NORMAL);
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. void __fastcall TCustomScpExplorerForm::DestroyProgressForm()
  1484. {
  1485. UnlockWindow();
  1486. SAFE_DESTROY(FProgressForm);
  1487. SetQueueProgress();
  1488. }
  1489. //---------------------------------------------------------------------------
  1490. void __fastcall TCustomScpExplorerForm::FileOperationProgress(
  1491. TFileOperationProgressType & ProgressData)
  1492. {
  1493. // Download to temporary local directory
  1494. if (FPendingTempSpaceWarn && ProgressData.InProgress && ProgressData.TotalSizeSet)
  1495. {
  1496. bool Continue = true;
  1497. FPendingTempSpaceWarn = false;
  1498. DoWarnLackOfTempSpace(ProgressData.Directory, ProgressData.TotalSize, Continue);
  1499. if (!Continue)
  1500. {
  1501. Abort();
  1502. }
  1503. }
  1504. // operation is being executed and we still didn't show up progress form
  1505. if (ProgressData.InProgress && !FProgressForm)
  1506. {
  1507. CreateProgressForm(NULL);
  1508. DebugAssert(FProgressForm->OnceDoneOperation == odoIdle);
  1509. FProgressForm->OnceDoneOperation = ProgressData.InitialOnceDoneOperation;
  1510. }
  1511. // operation is finished (or terminated), so we hide progress form
  1512. else if (!ProgressData.InProgress && (FProgressForm != NULL) && (FProgressForm->SynchronizeProgress == NULL))
  1513. {
  1514. DestroyProgressForm();
  1515. if (ProgressData.Operation == foCalculateSize)
  1516. {
  1517. // When calculating size before transfer, the abort caused by
  1518. // cancel flag set due to "MoveToQueue" below,
  1519. // is not propagated back to us in ExecuteFileOperation,
  1520. // as it is silently swallowed.
  1521. // So we explicitly (re)throw it here.
  1522. if (FMoveToQueue)
  1523. {
  1524. Abort();
  1525. }
  1526. }
  1527. else
  1528. {
  1529. if ((ProgressData.Cancel == csContinue) &&
  1530. !FAutoOperation)
  1531. {
  1532. OperationComplete(ProgressData.StartTime);
  1533. }
  1534. }
  1535. }
  1536. if (FProgressForm &&
  1537. // Can happen only during synchronization, when ending one of the operations
  1538. ProgressData.InProgress)
  1539. {
  1540. FProgressForm->SetProgressData(ProgressData);
  1541. DebugAssert(ProgressData.InProgress);
  1542. SetTaskbarListProgressValue(&ProgressData);
  1543. if (FProgressForm->Cancel > csContinue)
  1544. {
  1545. ProgressData.SetCancelAtLeast(FProgressForm->Cancel);
  1546. if (FProgressForm->Cancel == csCancelFile)
  1547. {
  1548. FProgressForm->ClearCancel();
  1549. }
  1550. // cancel cancels even the move
  1551. FMoveToQueue = false;
  1552. }
  1553. else if (FProgressForm->MoveToQueue)
  1554. {
  1555. FMoveToQueue = true;
  1556. ProgressData.SetCancelAtLeast(csCancel);
  1557. }
  1558. if ((FTransferResumeList != NULL) &&
  1559. ProgressData.InProgress &&
  1560. ProgressData.IsTransfer() &&
  1561. !ProgressData.FullFileName.IsEmpty())
  1562. {
  1563. if ((FTransferResumeList->Count == 0) ||
  1564. (FTransferResumeList->Strings[FTransferResumeList->Count - 1] != ProgressData.FullFileName))
  1565. {
  1566. // note that we do not recognize directories from files here
  1567. FTransferResumeList->Add(ProgressData.FullFileName);
  1568. }
  1569. }
  1570. }
  1571. }
  1572. //---------------------------------------------------------------------------
  1573. void __fastcall TCustomScpExplorerForm::OperationComplete(
  1574. const TDateTime & StartTime)
  1575. {
  1576. if (GUIConfiguration->BeepOnFinish &&
  1577. (Now() - StartTime > GUIConfiguration->BeepOnFinishAfter))
  1578. {
  1579. UnicodeString BeepSound = GUIConfiguration->BeepSound;
  1580. DWORD Sound;
  1581. if (!ExtractFileExt(BeepSound).IsEmpty())
  1582. {
  1583. Sound = SND_FILENAME;
  1584. }
  1585. else
  1586. {
  1587. Sound = SND_ALIAS;
  1588. }
  1589. PlaySound(BeepSound.c_str(), NULL, Sound | SND_ASYNC);
  1590. }
  1591. }
  1592. //---------------------------------------------------------------------------
  1593. void __fastcall TCustomScpExplorerForm::OperationProgress(
  1594. TFileOperationProgressType & ProgressData)
  1595. {
  1596. // For example, when calling TFileOperationProgressType::Suspend in TTerminal::QueryReopen,
  1597. // we cannot recurse back to TTerminal::Idle as that may detect another error, calling "suspend" again.
  1598. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1599. FileOperationProgress(ProgressData);
  1600. }
  1601. //---------------------------------------------------------------------------
  1602. UnicodeString __fastcall TCustomScpExplorerForm::GetProgressTitle()
  1603. {
  1604. UnicodeString Result;
  1605. if (FProgressForm != NULL)
  1606. {
  1607. Result = FProgressForm->ProgressStr();
  1608. }
  1609. return Result;
  1610. }
  1611. //---------------------------------------------------------------------------
  1612. bool __fastcall TCustomScpExplorerForm::PanelOperation(TOperationSide /*Side*/,
  1613. bool DragDrop)
  1614. {
  1615. return (!DragDrop && (DropSourceControl == NULL)) ||
  1616. (DropSourceControl == DirView(osOther));
  1617. }
  1618. //---------------------------------------------------------------------------
  1619. TListItem * TCustomScpExplorerForm::VisualiseOperationFinished(TOperationSide Side, const UnicodeString & FileName, bool Unselect)
  1620. {
  1621. TCustomDirView * ADirView = DirView(Side);
  1622. UnicodeString FileNameOnly = ExtractFileName(FileName, !IsSideLocalBrowser(Side));
  1623. TListItem * Item = ADirView->FindFileItem(FileNameOnly);
  1624. // this can happen when local drive is unplugged in the middle of the operation
  1625. if (Item != NULL)
  1626. {
  1627. if (Unselect)
  1628. {
  1629. Item->Selected = false;
  1630. }
  1631. ADirView->MakeProgressVisible(Item);
  1632. }
  1633. return Item;
  1634. }
  1635. //---------------------------------------------------------------------------
  1636. void __fastcall TCustomScpExplorerForm::DoOperationFinished(
  1637. TFileOperation Operation, TOperationSide Side,
  1638. bool /*Temp*/, const UnicodeString & FileName, bool Success,
  1639. TOnceDoneOperation & OnceDoneOperation)
  1640. {
  1641. if (!FAutoOperation)
  1642. {
  1643. // no selection on "/upload", form serves only as event handler
  1644. // (it is not displayed)
  1645. if (PanelOperation(Side, FDragDropOperation) && Visible &&
  1646. ((Operation == FPrimaryOperation) ||
  1647. ((Operation != foCalculateSize) && (Operation != foGetProperties) && (Operation != foCalculateChecksum))))
  1648. {
  1649. TOperationSide DViewSide;
  1650. if ((FProgressSide != osCurrent) &&
  1651. IsLocalBrowserMode() && (Side == osLocal)) // Only to limit the impact
  1652. {
  1653. // assume the operation is over the focused panel
  1654. DViewSide = FProgressSide;
  1655. }
  1656. else
  1657. {
  1658. DViewSide = Side;
  1659. }
  1660. if (FOnFileOperationFinished != NULL)
  1661. {
  1662. FOnFileOperationFinished(DViewSide, FileName, Success);
  1663. }
  1664. else
  1665. {
  1666. VisualiseOperationFinished(DViewSide, FileName, Success);
  1667. }
  1668. }
  1669. if (TFileOperationProgressType::IsTransferOperation(Operation))
  1670. {
  1671. if (DebugAlwaysTrue(!IsLocalBrowserMode()))
  1672. {
  1673. if (Side == osLocal)
  1674. {
  1675. Configuration->Usage->Inc(L"UploadedFiles");
  1676. }
  1677. else
  1678. {
  1679. Configuration->Usage->Inc(L"DownloadedFiles");
  1680. }
  1681. }
  1682. }
  1683. }
  1684. if (Success && (FSynchronizeController != NULL))
  1685. {
  1686. DebugAssert(!IsSideLocalBrowser(osRemote));
  1687. if (Operation == foCopy)
  1688. {
  1689. DebugAssert(Side == osLocal);
  1690. FSynchronizeController->LogOperation(soUpload, FileName);
  1691. }
  1692. else if (Operation == foDelete)
  1693. {
  1694. DebugAssert(Side == osRemote);
  1695. FSynchronizeController->LogOperation(soDelete, FileName);
  1696. }
  1697. }
  1698. if (FProgressForm)
  1699. {
  1700. OnceDoneOperation = FProgressForm->OnceDoneOperation;
  1701. }
  1702. }
  1703. //---------------------------------------------------------------------------
  1704. void __fastcall TCustomScpExplorerForm::OperationFinished(
  1705. TFileOperation Operation, TOperationSide Side,
  1706. bool Temp, const UnicodeString & FileName, Boolean Success,
  1707. TOnceDoneOperation & OnceDoneOperation)
  1708. {
  1709. TAutoNestingCounter Counter(FDoNotIdleCurrentTerminal);
  1710. DoOperationFinished(Operation, Side, Temp, FileName, Success,
  1711. OnceDoneOperation);
  1712. }
  1713. //---------------------------------------------------------------------------
  1714. bool TCustomScpExplorerForm::IsLocalBrowserMode()
  1715. {
  1716. return false;
  1717. }
  1718. //---------------------------------------------------------------------------
  1719. bool TCustomScpExplorerForm::SupportsLocalBrowser()
  1720. {
  1721. return false;
  1722. }
  1723. //---------------------------------------------------------------------------
  1724. bool TCustomScpExplorerForm::IsSideLocalBrowser(TOperationSide)
  1725. {
  1726. return false;
  1727. }
  1728. //---------------------------------------------------------------------------
  1729. TCustomDirView * TCustomScpExplorerForm::GetCurrentLocalBrowser()
  1730. {
  1731. return NULL;
  1732. }
  1733. //---------------------------------------------------------------------------
  1734. TCustomDirView * __fastcall TCustomScpExplorerForm::DirView(TOperationSide Side)
  1735. {
  1736. DebugAssert(GetSide(Side) == osRemote);
  1737. DebugUsedParam(Side);
  1738. return RemoteDirView;
  1739. }
  1740. //---------------------------------------------------------------------------
  1741. TCustomDriveView * __fastcall TCustomScpExplorerForm::DriveView(TOperationSide Side)
  1742. {
  1743. DebugAssert(GetSide(Side) == osRemote);
  1744. DebugUsedParam(Side);
  1745. return RemoteDriveView;
  1746. }
  1747. //---------------------------------------------------------------------------
  1748. bool __fastcall TCustomScpExplorerForm::DirViewEnabled(TOperationSide Side)
  1749. {
  1750. DebugAssert(GetSide(Side) == osRemote);
  1751. DebugUsedParam(Side);
  1752. return HasActiveTerminal();
  1753. }
  1754. //---------------------------------------------------------------------------
  1755. bool __fastcall TCustomScpExplorerForm::GetEnableFocusedOperation(
  1756. TOperationSide Side, int FilesOnly)
  1757. {
  1758. return DirView(Side)->AnyFileSelected(true, (FilesOnly != 0), true);
  1759. }
  1760. //---------------------------------------------------------------------------
  1761. bool __fastcall TCustomScpExplorerForm::GetEnableSelectedOperation(
  1762. TOperationSide Side, int FilesOnly)
  1763. {
  1764. return DirView(Side)->AnyFileSelected(false, (FilesOnly != 0), true);
  1765. }
  1766. //---------------------------------------------------------------------------
  1767. struct THistoryItemData
  1768. {
  1769. short int Side;
  1770. short int Index;
  1771. };
  1772. //---------------------------------------------------------------------------
  1773. void __fastcall TCustomScpExplorerForm::HistoryGo(TOperationSide Side, int Index)
  1774. {
  1775. DirView(Side)->HistoryGo(Index);
  1776. }
  1777. //---------------------------------------------------------------------------
  1778. void __fastcall TCustomScpExplorerForm::HistoryItemClick(System::TObject* Sender)
  1779. {
  1780. TTBCustomItem * Item = dynamic_cast<TTBCustomItem *>(Sender);
  1781. THistoryItemData Data = *reinterpret_cast<THistoryItemData*>(&(Item->Tag));
  1782. HistoryGo((TOperationSide)Data.Side, Data.Index);
  1783. }
  1784. //---------------------------------------------------------------------------
  1785. void __fastcall TCustomScpExplorerForm::UpdateHistoryMenu(TOperationSide Side,
  1786. bool Back)
  1787. {
  1788. if (FHistoryMenu[Side == osLocal][Back] != NULL)
  1789. {
  1790. TCustomDirView * DView = DirView(Side);
  1791. TTBXPopupMenu * Menu = FHistoryMenu[Side == osLocal][Back];
  1792. int ICount = Back ? DView->BackCount : DView->ForwardCount;
  1793. if (ICount > 10)
  1794. {
  1795. ICount = 10;
  1796. }
  1797. Menu->Items->Clear();
  1798. THistoryItemData Data;
  1799. Data.Side = Side;
  1800. for (short int i = 1; i <= ICount; i++)
  1801. {
  1802. TTBCustomItem * Item = new TTBXItem(Menu);
  1803. Data.Index = static_cast<short int>(i * (Back ? -1 : 1));
  1804. Item->Caption = MinimizeName(DView->HistoryPath[Data.Index], 50, !IsSideLocalBrowser(Side));
  1805. Item->Hint = DView->HistoryPath[Data.Index];
  1806. DebugAssert(sizeof(int) == sizeof(THistoryItemData));
  1807. Item->Tag = *reinterpret_cast<int*>(&Data);
  1808. Item->OnClick = HistoryItemClick;
  1809. Menu->Items->Add(Item);
  1810. }
  1811. }
  1812. }
  1813. //---------------------------------------------------------------------------
  1814. TTBXPopupMenu * __fastcall TCustomScpExplorerForm::HistoryMenu(
  1815. TOperationSide Side, bool Back)
  1816. {
  1817. if (FHistoryMenu[Side == osLocal][Back] == NULL)
  1818. {
  1819. // workaround
  1820. // In Pascal the size of TTBXPopupMenu is 132, in C++ 136,
  1821. // operator new allocates memory in Pascal code, but calls inline
  1822. // constructor in C++, leading in problems, the function does
  1823. // both in Pascal code
  1824. FHistoryMenu[Side == osLocal][Back] = CreateTBXPopupMenu(this);
  1825. UpdateHistoryMenu(Side, Back);
  1826. }
  1827. return FHistoryMenu[Side == osLocal][Back];
  1828. }
  1829. //---------------------------------------------------------------------------
  1830. void __fastcall TCustomScpExplorerForm::DirViewHistoryChange(
  1831. TCustomDirView *Sender)
  1832. {
  1833. TOperationSide Side = (Sender == DirView(osOther) ? osOther : osLocal);
  1834. UpdateHistoryMenu(Side, true);
  1835. UpdateHistoryMenu(Side, false);
  1836. }
  1837. //---------------------------------------------------------------------------
  1838. bool __fastcall TCustomScpExplorerForm::CustomCommandRemoteAllowed()
  1839. {
  1840. // remote custom commands can be executed only if the server supports shell commands
  1841. // or have secondary shell
  1842. return HasActiveTerminal() && (Terminal->IsCapable[fcSecondaryShell] || Terminal->IsCapable[fcShellAnyCommand]);
  1843. }
  1844. //---------------------------------------------------------------------------
  1845. int __fastcall TCustomScpExplorerForm::CustomCommandState(
  1846. const TCustomCommandType & Command, bool OnFocused, TCustomCommandListType ListType)
  1847. {
  1848. // -1 = hidden, 0 = disabled, 1 = enabled
  1849. int Result;
  1850. TFileCustomCommand RemoteCustomCommand;
  1851. TLocalCustomCommand LocalCustomCommand;
  1852. TFileCustomCommand * NonInteractiveCustomCommand =
  1853. FLAGCLEAR(Command.Params, ccLocal) ? &RemoteCustomCommand : &LocalCustomCommand;
  1854. TInteractiveCustomCommand InteractiveCustomCommand(NonInteractiveCustomCommand);
  1855. UnicodeString Cmd = InteractiveCustomCommand.Complete(Command.Command, false);
  1856. if (FLAGCLEAR(Command.Params, ccLocal))
  1857. {
  1858. int AllowedState = CustomCommandRemoteAllowed() ? 1 : 0;
  1859. // custom command that does not operate with files can be executed anytime ...
  1860. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1861. {
  1862. // ... but do not show such command in remote file menu
  1863. if ((ListType == ccltAll) || (ListType == ccltNonFile))
  1864. {
  1865. Result = AllowedState;
  1866. }
  1867. else
  1868. {
  1869. Result = -1;
  1870. }
  1871. }
  1872. else
  1873. {
  1874. if ((ListType == ccltAll) || ((ListType == ccltFile) && !IsSideLocalBrowser(FCurrentSide)))
  1875. {
  1876. Result = (DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true)) ? AllowedState : 0;
  1877. }
  1878. else
  1879. {
  1880. Result = -1;
  1881. }
  1882. }
  1883. }
  1884. else
  1885. {
  1886. // custom command that does not operate with files can be executed anytime
  1887. if (!NonInteractiveCustomCommand->IsFileCommand(Cmd))
  1888. {
  1889. Result = ((ListType == ccltAll) || (ListType == ccltNonFile)) ? 1 : -1;
  1890. }
  1891. else if (LocalCustomCommand.HasLocalFileName(Cmd))
  1892. {
  1893. if ((ListType == ccltAll) || (ListType == ccltFile))
  1894. {
  1895. // special case is "diff"-style command that can be executed over any side,
  1896. // if we have both sides
  1897. Result =
  1898. // Cannot have focus on both panels, so we have to call AnyFileSelected
  1899. // directly (instead of EnableSelectedOperation) to pass
  1900. // false to FocusedFileOnlyWhenFocused when panel is inactive.
  1901. ((HasDirView[osLocal] && !IsSideLocalBrowser(osRemote) &&
  1902. DirView(osLocal)->AnyFileSelected(false, false, (FCurrentSide == osLocal))) &&
  1903. DirView(osRemote)->AnyFileSelected(false, false, (FCurrentSide == osRemote))) ? 1 : 0;
  1904. }
  1905. else if (ListType == ccltBoth)
  1906. {
  1907. DebugAssert(!IsLocalBrowserMode());
  1908. Result = 1;
  1909. }
  1910. else
  1911. {
  1912. Result = -1;
  1913. }
  1914. }
  1915. else
  1916. {
  1917. if ((ListType == ccltAll) ||
  1918. ((ListType == ccltFile) && (!IsSideLocalBrowser(FCurrentSide) || FLAGCLEAR(Command.Params, ccRemoteFiles))))
  1919. {
  1920. Result = DirView(FCurrentSide)->AnyFileSelected(OnFocused, false, true) ? 1 : 0;
  1921. }
  1922. else
  1923. {
  1924. Result = -1;
  1925. }
  1926. }
  1927. if ((Result > 0) &&
  1928. LocalCustomCommand.IsSessionCommand(Cmd) &&
  1929. !HasActiveTerminal())
  1930. {
  1931. Result = 0;
  1932. }
  1933. }
  1934. return Result;
  1935. }
  1936. //---------------------------------------------------------------------------
  1937. void __fastcall TCustomScpExplorerForm::RemoteCustomCommand(
  1938. TStrings * FileList, const TCustomCommandType & ACommand,
  1939. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  1940. {
  1941. if (EnsureCommandSessionFallback(fcShellAnyCommand))
  1942. {
  1943. TRemoteCustomCommand RemoteCustomCommand(Data, Terminal->CurrentDirectory);
  1944. TWinInteractiveCustomCommand InteractiveCustomCommand(
  1945. &RemoteCustomCommand, ACommand.Name, ACommand.HomePage);
  1946. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  1947. Configuration->Usage->Inc(L"RemoteCustomCommandRuns2");
  1948. bool Capture =
  1949. FLAGSET(ACommand.Params, ccShowResults) ||
  1950. FLAGSET(ACommand.Params, ccCopyResults) ||
  1951. FLAGSET(ACommand.Params, ccShowResultsInMsgBox);
  1952. TCaptureOutputEvent OutputEvent = NULL;
  1953. DebugAssert(FCapturedLog == NULL);
  1954. if (Capture)
  1955. {
  1956. FCapturedLog = new TStringList();
  1957. OutputEvent = TerminalCaptureLog;
  1958. }
  1959. try
  1960. {
  1961. if (!RemoteCustomCommand.IsFileCommand(Command))
  1962. {
  1963. Terminal->AnyCommand(RemoteCustomCommand.Complete(Command, true),
  1964. OutputEvent);
  1965. }
  1966. else
  1967. {
  1968. Terminal->CustomCommandOnFiles(Command, ACommand.Params, FileList, OutputEvent);
  1969. }
  1970. if ((FCapturedLog != NULL) && (FCapturedLog->Count > 0))
  1971. {
  1972. if (FLAGSET(ACommand.Params, ccCopyResults))
  1973. {
  1974. CopyToClipboard(FCapturedLog);
  1975. }
  1976. if (FLAGSET(ACommand.Params, ccShowResults))
  1977. {
  1978. DoConsoleDialog(Terminal, L"", FCapturedLog);
  1979. }
  1980. else if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox))
  1981. {
  1982. MessageDialog(FCapturedLog->Text, qtInformation, qaOK);
  1983. }
  1984. }
  1985. }
  1986. __finally
  1987. {
  1988. SAFE_DESTROY(FCapturedLog);
  1989. }
  1990. }
  1991. }
  1992. //---------------------------------------------------------------------------
  1993. void __fastcall TCustomScpExplorerForm::LocalCustomCommandPure(
  1994. TStrings * FileList, const TCustomCommandType & ACommand, const UnicodeString & Command, TStrings * ALocalFileList,
  1995. const TCustomCommandData & Data, bool LocalFileCommand, bool FileListCommand, UnicodeString * POutput)
  1996. {
  1997. DebugAssert(!IsLocalBrowserMode());
  1998. TStrings * LocalFileList = NULL;
  1999. TStrings * RemoteFileList = NULL;
  2000. TStrings * RemoteFileListFull = NULL;
  2001. try
  2002. {
  2003. if (LocalFileCommand)
  2004. {
  2005. if (ALocalFileList == NULL)
  2006. {
  2007. DebugAssert(HasDirView[osLocal]);
  2008. // Cannot have focus on both panels, so we have to call AnyFileSelected
  2009. // directly (instead of EnableSelectedOperation) to pass
  2010. // false to FocusedFileOnlyWhenFocused
  2011. DebugAssert(DirView(osLocal)->AnyFileSelected(false, false, false));
  2012. LocalFileList = DirView(osLocal)->CreateFileList(false, true, NULL);
  2013. }
  2014. else
  2015. {
  2016. LocalFileList = ALocalFileList;
  2017. }
  2018. if (FileListCommand)
  2019. {
  2020. if (LocalFileList->Count != 1)
  2021. {
  2022. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH1));
  2023. }
  2024. }
  2025. else
  2026. {
  2027. if ((LocalFileList->Count != 1) &&
  2028. (FileList->Count != 1) &&
  2029. (LocalFileList->Count != FileList->Count))
  2030. {
  2031. throw Exception(LoadStr(CUSTOM_COMMAND_SELECTED_UNMATCH));
  2032. }
  2033. }
  2034. }
  2035. UnicodeString RootTempDir;
  2036. UnicodeString TempDir;
  2037. bool RemoteFiles = FLAGSET(ACommand.Params, ccRemoteFiles);
  2038. if (!RemoteFiles)
  2039. {
  2040. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, true, true);
  2041. }
  2042. try
  2043. {
  2044. TDateTimes RemoteFileTimes;
  2045. if (RemoteFiles)
  2046. {
  2047. RemoteFileList = FileList;
  2048. }
  2049. else
  2050. {
  2051. RemoteFileList = new TStringList();
  2052. TMakeLocalFileListParams MakeFileListParam;
  2053. MakeFileListParam.FileList = RemoteFileList;
  2054. MakeFileListParam.FileTimes = &RemoteFileTimes;
  2055. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2056. MakeFileListParam.Recursive =
  2057. FLAGSET(ACommand.Params, ccRecursive) && !FileListCommand;
  2058. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2059. if (!MakeFileListParam.Recursive)
  2060. {
  2061. RemoteFileTimes.clear();
  2062. RemoteFileListFull = new TStringList();
  2063. MakeFileListParam.FileList = RemoteFileListFull;
  2064. MakeFileListParam.Recursive = true;
  2065. MakeFileListParam.IncludeDirs = false;
  2066. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  2067. }
  2068. else
  2069. {
  2070. RemoteFileListFull = RemoteFileList;
  2071. }
  2072. }
  2073. bool NonBlocking = FileListCommand && RemoteFiles && !POutput;
  2074. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2075. if (!NonBlocking)
  2076. {
  2077. int Count;
  2078. if (FileListCommand)
  2079. {
  2080. Count = 1;
  2081. }
  2082. else if (LocalFileCommand)
  2083. {
  2084. Count = std::max(LocalFileList->Count, RemoteFileList->Count);
  2085. }
  2086. else
  2087. {
  2088. Count = RemoteFileList->Count;
  2089. }
  2090. Progress.Start(foCustomCommand, osRemote, Count);
  2091. DebugAssert(FProgressForm != NULL);
  2092. FProgressForm->ReadOnly = true;
  2093. }
  2094. try
  2095. {
  2096. if (FileListCommand)
  2097. {
  2098. UnicodeString LocalFile;
  2099. // MakeFileList does not delimit filenames
  2100. UnicodeString FileList = MakeFileList(RemoteFileList);
  2101. if (LocalFileCommand)
  2102. {
  2103. DebugAssert(LocalFileList->Count == 1);
  2104. LocalFile = LocalFileList->Strings[0];
  2105. }
  2106. TLocalCustomCommand CustomCommand(Data,
  2107. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), L"", LocalFile, FileList);
  2108. UnicodeString ShellCommand = CustomCommand.Complete(Command, true);
  2109. if (NonBlocking)
  2110. {
  2111. DebugAssert(!POutput);
  2112. ExecuteShellChecked(ShellCommand);
  2113. }
  2114. else
  2115. {
  2116. ExecuteProcessCheckedAndWait(ShellCommand, HelpKeyword, POutput);
  2117. }
  2118. }
  2119. else if (LocalFileCommand)
  2120. {
  2121. if (LocalFileList->Count == 1)
  2122. {
  2123. UnicodeString LocalFile = LocalFileList->Strings[0];
  2124. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2125. {
  2126. UnicodeString FileName = RemoteFileList->Strings[Index];
  2127. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2128. Progress.SetFile(FileNameForProgress);
  2129. TLocalCustomCommand CustomCommand(Data,
  2130. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(), FileName, LocalFile, L"");
  2131. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2132. TOnceDoneOperation OnceDoneOperation;
  2133. // Do not unselect anything, as it won't work with two panels anyway
  2134. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2135. }
  2136. }
  2137. else if (RemoteFileList->Count == 1)
  2138. {
  2139. UnicodeString FileName = RemoteFileList->Strings[0];
  2140. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2141. {
  2142. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2143. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2144. Progress.SetFile(LocalFileNameOnly);
  2145. TLocalCustomCommand CustomCommand(
  2146. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2147. FileName, LocalFileName, L"");
  2148. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2149. TOnceDoneOperation OnceDoneOperation;
  2150. // Do not unselect anything, as it won't work with two panels anyway
  2151. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2152. }
  2153. }
  2154. else
  2155. {
  2156. if (LocalFileList->Count != RemoteFileList->Count)
  2157. {
  2158. throw Exception(LoadStr(CUSTOM_COMMAND_PAIRS_DOWNLOAD_FAILED));
  2159. }
  2160. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2161. {
  2162. UnicodeString FileName = RemoteFileList->Strings[Index];
  2163. UnicodeString LocalFileName = LocalFileList->Strings[Index];
  2164. UnicodeString LocalFileNameOnly = ExtractFileName(LocalFileName);
  2165. Progress.SetFile(LocalFileNameOnly); // sic
  2166. TLocalCustomCommand CustomCommand(
  2167. Data, Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2168. FileName, LocalFileName, L"");
  2169. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2170. TOnceDoneOperation OnceDoneOperation;
  2171. // Do not unselect anything, as it won't work with two panels anyway
  2172. Progress.Finish(UnicodeString(), true, OnceDoneOperation);
  2173. }
  2174. }
  2175. }
  2176. else
  2177. {
  2178. for (int Index = 0; Index < RemoteFileList->Count; Index++)
  2179. {
  2180. UnicodeString FileName = RemoteFileList->Strings[Index];
  2181. UnicodeString FileNameForProgress = RemoteFiles ? FileName : ExtractFileName(FileName);
  2182. Progress.SetFile(FileNameForProgress);
  2183. TLocalCustomCommand CustomCommand(Data,
  2184. Terminal->CurrentDirectory, DefaultDownloadTargetDirectory(),
  2185. FileName, L"", L"");
  2186. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2187. TOnceDoneOperation OnceDoneOperation;
  2188. Progress.Finish(FileNameForProgress, true, OnceDoneOperation);
  2189. }
  2190. }
  2191. }
  2192. __finally
  2193. {
  2194. if (!NonBlocking)
  2195. {
  2196. Progress.Stop();
  2197. }
  2198. }
  2199. DebugAssert(!FAutoOperation);
  2200. if (!RemoteFiles)
  2201. {
  2202. TempDir = IncludeTrailingBackslash(TempDir);
  2203. for (int Index = 0; Index < RemoteFileListFull->Count; Index++)
  2204. {
  2205. UnicodeString FileName = RemoteFileListFull->Strings[Index];
  2206. if (DebugAlwaysTrue(SameText(TempDir, FileName.SubString(1, TempDir.Length()))) &&
  2207. // Skip directories, process only nested files.
  2208. // The check is redundant as FileAge fails for directories anyway.
  2209. !DirectoryExists(FileName))
  2210. {
  2211. UnicodeString RemoteDir =
  2212. UnixExtractFileDir(
  2213. UnixIncludeTrailingBackslash(Terminal->CurrentDirectory) +
  2214. ToUnixPath(FileName.SubString(TempDir.Length() + 1, FileName.Length() - TempDir.Length())));
  2215. TDateTime NewTime;
  2216. if (FileAge(FileName, NewTime) &&
  2217. (NewTime != RemoteFileTimes[Index]))
  2218. {
  2219. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2220. TemporaryFileCopyParam(CopyParam);
  2221. CopyParam.FileMask = L"";
  2222. FAutoOperation = true;
  2223. std::unique_ptr<TStrings> TemporaryFilesList(new TStringList());
  2224. TemporaryFilesList->Add(FileName);
  2225. Terminal->CopyToRemote(TemporaryFilesList.get(), RemoteDir, &CopyParam, cpTemporary, NULL);
  2226. }
  2227. }
  2228. }
  2229. }
  2230. }
  2231. __finally
  2232. {
  2233. FAutoOperation = false;
  2234. if (!RootTempDir.IsEmpty() && DebugAlwaysTrue(!RemoteFiles))
  2235. {
  2236. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  2237. }
  2238. }
  2239. }
  2240. __finally
  2241. {
  2242. if (RemoteFileList != FileList)
  2243. {
  2244. delete RemoteFileList;
  2245. }
  2246. if (LocalFileList != ALocalFileList)
  2247. {
  2248. delete LocalFileList;
  2249. }
  2250. if (RemoteFileListFull != RemoteFileList)
  2251. {
  2252. delete RemoteFileListFull;
  2253. }
  2254. }
  2255. }
  2256. //---------------------------------------------------------------------------
  2257. void __fastcall TCustomScpExplorerForm::LocalCustomCommandWithLocalFiles(
  2258. const TCustomCommandType & ACommand, const UnicodeString & Command, const TCustomCommandData & Data,
  2259. bool FileListCommand, UnicodeString * POutput)
  2260. {
  2261. std::unique_ptr<TStrings> SelectedFileList(DirView(osCurrent)->CreateFileList(false, true, NULL));
  2262. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  2263. for (int Index = 0; Index < SelectedFileList->Count; Index++)
  2264. {
  2265. UnicodeString FileName = SelectedFileList->Strings[Index];
  2266. if (DirectoryExists(FileName))
  2267. {
  2268. if (FLAGSET(ACommand.Params, ccApplyToDirectories))
  2269. {
  2270. LocalFileList->Add(FileName);
  2271. }
  2272. if (FLAGSET(ACommand.Params, ccRecursive))
  2273. {
  2274. TMakeLocalFileListParams MakeFileListParam;
  2275. MakeFileListParam.FileList = LocalFileList.get();
  2276. MakeFileListParam.FileTimes = NULL;
  2277. MakeFileListParam.IncludeDirs = FLAGSET(ACommand.Params, ccApplyToDirectories);
  2278. MakeFileListParam.Recursive = true;
  2279. ProcessLocalDirectory(FileName, Terminal->MakeLocalFileList, &MakeFileListParam);
  2280. }
  2281. }
  2282. else
  2283. {
  2284. LocalFileList->Add(FileName);
  2285. }
  2286. }
  2287. UnicodeString RemotePath;
  2288. if (Terminal != NULL)
  2289. {
  2290. RemotePath = Terminal->CurrentDirectory;
  2291. }
  2292. if (FileListCommand)
  2293. {
  2294. UnicodeString FileList = MakeFileList(LocalFileList.get());
  2295. TLocalCustomCommand CustomCommand(
  2296. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2297. L"", L"", FileList);
  2298. ExecuteProcessChecked(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2299. }
  2300. else
  2301. {
  2302. TFileOperationProgressType Progress(&OperationProgress, &OperationFinished);
  2303. Progress.Start(foCustomCommand, osLocal, LocalFileList->Count);
  2304. DebugAssert(FProgressForm != NULL);
  2305. FProgressForm->ReadOnly = true;
  2306. try
  2307. {
  2308. for (int Index = 0; Index < LocalFileList->Count; Index++)
  2309. {
  2310. UnicodeString FileName = LocalFileList->Strings[Index];
  2311. Progress.SetFile(FileName);
  2312. TLocalCustomCommand CustomCommand(
  2313. Data, RemotePath, DefaultDownloadTargetDirectory(),
  2314. FileName, L"", L"");
  2315. ExecuteProcessCheckedAndWait(CustomCommand.Complete(Command, true), HelpKeyword, POutput);
  2316. TOnceDoneOperation OnceDoneOperation;
  2317. Progress.Finish(FileName, true, OnceDoneOperation);
  2318. }
  2319. }
  2320. __finally
  2321. {
  2322. Progress.Stop();
  2323. }
  2324. }
  2325. }
  2326. //---------------------------------------------------------------------------
  2327. void __fastcall TCustomScpExplorerForm::LocalCustomCommand(TStrings * FileList,
  2328. const TCustomCommandType & ACommand, TStrings * ALocalFileList,
  2329. const TCustomCommandData & Data, const UnicodeString & CommandCommand)
  2330. {
  2331. UnicodeString RemotePath = (Terminal != NULL) ? Terminal->CurrentDirectory : UnicodeString();
  2332. TLocalCustomCommand LocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory());
  2333. TWinInteractiveCustomCommand InteractiveCustomCommand(
  2334. &LocalCustomCommand, ACommand.Name, ACommand.HomePage);
  2335. UnicodeString Command = InteractiveCustomCommand.Complete(CommandCommand, false);
  2336. bool FileListCommand = LocalCustomCommand.IsFileListCommand(Command);
  2337. bool LocalFileCommand = LocalCustomCommand.HasLocalFileName(Command);
  2338. Configuration->Usage->Inc(L"LocalCustomCommandRuns2");
  2339. std::unique_ptr<UnicodeString> POutput;
  2340. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) ||
  2341. FLAGSET(ACommand.Params, ccCopyResults))
  2342. {
  2343. POutput.reset(new UnicodeString());
  2344. }
  2345. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  2346. if (!LocalCustomCommand.IsFileCommand(Command))
  2347. {
  2348. ExecuteProcessChecked(LocalCustomCommand.Complete(Command, true), HelpKeyword, POutput.get());
  2349. }
  2350. // remote files?
  2351. else if (!IsSideLocalBrowser(FCurrentSide) || LocalFileCommand)
  2352. {
  2353. LocalCustomCommandPure(FileList, ACommand, Command, ALocalFileList, Data, LocalFileCommand, FileListCommand, POutput.get());
  2354. }
  2355. // local files
  2356. else
  2357. {
  2358. LocalCustomCommandWithLocalFiles(ACommand, Command, Data, FileListCommand, POutput.get());
  2359. }
  2360. if (POutput.get() != NULL)
  2361. {
  2362. // If the output is single-line, we do not want the trailing CRLF, as the CopyToClipboard(TStrings *) does
  2363. int P = POutput->Pos(sLineBreak);
  2364. if (P == POutput->Length() - static_cast<int>(strlen(sLineBreak)) + 1)
  2365. {
  2366. POutput->SetLength(P - 1);
  2367. }
  2368. // Copy even empty output to clipboard
  2369. if (FLAGSET(ACommand.Params, ccCopyResults))
  2370. {
  2371. CopyToClipboard(*POutput);
  2372. }
  2373. // But do not show an empty message box.
  2374. // This way the ShowResultsInMsgBox can be used to suppress a console window of commands with no output
  2375. if (FLAGSET(ACommand.Params, ccShowResultsInMsgBox) &&
  2376. !POutput->IsEmpty())
  2377. {
  2378. TClipboardHandler ClipboardHandler;
  2379. ClipboardHandler.Text = *POutput;
  2380. TMessageParams Params;
  2381. TQueryButtonAlias Aliases[1];
  2382. Aliases[0].Button = qaRetry;
  2383. Aliases[0].Alias = LoadStr(EDIT_COPY);
  2384. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  2385. Params.Aliases = Aliases;
  2386. Params.AliasesCount = LENOF(Aliases);
  2387. MessageDialog(*POutput, qtInformation, qaOK | qaRetry, HelpKeyword, &Params);
  2388. }
  2389. }
  2390. }
  2391. //---------------------------------------------------------------------------
  2392. void __fastcall TCustomScpExplorerForm::CustomCommand(TStrings * FileList,
  2393. const TCustomCommandType & ACommand, TStrings * ALocalFileList)
  2394. {
  2395. TCustomCommandData Data;
  2396. UnicodeString Site;
  2397. UnicodeString RemotePath;
  2398. if (HasActiveTerminal())
  2399. {
  2400. std::unique_ptr<TSessionData> SessionData(SessionDataForCode());
  2401. Data = TCustomCommandData(SessionData.get());
  2402. Site = Terminal->SessionData->SessionKey;
  2403. RemotePath = Terminal->CurrentDirectory;
  2404. }
  2405. UnicodeString HelpKeyword = ACommand.HomePage;
  2406. std::unique_ptr<TStrings> CustomCommandOptions(CloneStrings(WinConfiguration->CustomCommandOptions));
  2407. if (ACommand.AnyOptionWithFlag(TCustomCommandType::ofRun))
  2408. {
  2409. std::unique_ptr<TCustomCommand> CustomCommandForOptions;
  2410. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2411. {
  2412. CustomCommandForOptions.reset(new TRemoteCustomCommand(Data, RemotePath));
  2413. }
  2414. else
  2415. {
  2416. CustomCommandForOptions.reset(new TLocalCustomCommand(Data, RemotePath, DefaultDownloadTargetDirectory()));
  2417. }
  2418. if (!DoCustomCommandOptionsDialog(
  2419. &ACommand, CustomCommandOptions.get(), NULL, TCustomCommandType::ofRun, CustomCommandForOptions.get(), Site, NULL))
  2420. {
  2421. Abort();
  2422. }
  2423. }
  2424. UnicodeString CommandCommand = ACommand.GetCommandWithExpandedOptions(CustomCommandOptions.get(), Site);
  2425. if (FLAGCLEAR(ACommand.Params, ccLocal))
  2426. {
  2427. RemoteCustomCommand(FileList, ACommand, Data, CommandCommand);
  2428. }
  2429. else
  2430. {
  2431. LocalCustomCommand(FileList, ACommand, ALocalFileList, Data, CommandCommand);
  2432. }
  2433. }
  2434. //---------------------------------------------------------------------------
  2435. void __fastcall TCustomScpExplorerForm::BothCustomCommand(
  2436. const TCustomCommandType & Command)
  2437. {
  2438. DebugAssert(FCustomCommandLocalFileList != NULL);
  2439. DebugAssert(FCustomCommandRemoteFileList != NULL);
  2440. DebugAssert(FCustomCommandLocalFileList->Count == FCustomCommandRemoteFileList->Count);
  2441. TStrings * LocalFileList = new TStringList();
  2442. TStrings * RemoteFileList = new TStringList();
  2443. try
  2444. {
  2445. for (int Index = 0; Index < FCustomCommandLocalFileList->Count; Index++)
  2446. {
  2447. LocalFileList->Clear();
  2448. LocalFileList->AddObject(
  2449. FCustomCommandLocalFileList->Strings[Index],
  2450. FCustomCommandLocalFileList->Objects[Index]);
  2451. RemoteFileList->Clear();
  2452. RemoteFileList->AddObject(
  2453. FCustomCommandRemoteFileList->Strings[Index],
  2454. FCustomCommandRemoteFileList->Objects[Index]);
  2455. CustomCommand(RemoteFileList, Command, LocalFileList);
  2456. }
  2457. }
  2458. __finally
  2459. {
  2460. delete LocalFileList;
  2461. delete RemoteFileList;
  2462. }
  2463. }
  2464. //---------------------------------------------------------------------------
  2465. void __fastcall TCustomScpExplorerForm::CustomCommandMenu(
  2466. TAction * Action, TStrings * LocalFileList, TStrings * RemoteFileList)
  2467. {
  2468. delete FCustomCommandLocalFileList;
  2469. delete FCustomCommandRemoteFileList;
  2470. // takeover ownership,
  2471. // the lists must survive the MenuPopup as OnClick occurs only after it exits
  2472. FCustomCommandLocalFileList = LocalFileList;
  2473. FCustomCommandRemoteFileList = RemoteFileList;
  2474. TButton * Button = dynamic_cast<TButton *>(Action->ActionComponent);
  2475. if (Button != NULL)
  2476. {
  2477. FCustomCommandMenu->Items->Clear();
  2478. NonVisualDataModule->CreateCustomCommandsMenu(FCustomCommandMenu->Items, false, false, ccltBoth, NULL);
  2479. MenuPopup(FCustomCommandMenu, Button);
  2480. }
  2481. else
  2482. {
  2483. NonVisualDataModule->CreateCustomCommandsMenu(Action, false, ccltBoth);
  2484. }
  2485. }
  2486. //---------------------------------------------------------------------------
  2487. void __fastcall TCustomScpExplorerForm::TerminalCaptureLog(
  2488. const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  2489. {
  2490. DebugAssert(FCapturedLog != NULL);
  2491. if ((OutputType == cotOutput) || (OutputType == cotError))
  2492. {
  2493. FCapturedLog->Add(AddedLine);
  2494. }
  2495. }
  2496. //---------------------------------------------------------------------------
  2497. bool __fastcall TCustomScpExplorerForm::IsFileControl(TObject * Control,
  2498. TOperationSide Side)
  2499. {
  2500. return
  2501. (Side == osOther) &&
  2502. ((Control == DirView(osOther)) || (Control == DriveView(osOther)));
  2503. }
  2504. //---------------------------------------------------------------------------
  2505. void __fastcall TCustomScpExplorerForm::DirViewContextPopupDefaultItem(
  2506. TOperationSide Side, TTBXCustomItem * Item,
  2507. TResolvedDoubleClickAction DoubleClickAction1, TResolvedDoubleClickAction DoubleClickAction2)
  2508. {
  2509. TCustomDirView * DView = DirView(Side);
  2510. bool IsDefault = false;
  2511. if (DView->ItemFocused != NULL)
  2512. {
  2513. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  2514. TResolvedDoubleClickAction DefaultAction =
  2515. WinConfiguration->ResolveDoubleClickAction(DView->ItemIsDirectory(DView->ItemFocused), ATerminal);
  2516. IsDefault = (DefaultAction == DoubleClickAction1) || (DefaultAction == DoubleClickAction2);
  2517. }
  2518. TTBItemOptions O = Item->Options;
  2519. if (IsDefault)
  2520. {
  2521. Item->Options = O << tboDefault;
  2522. }
  2523. else
  2524. {
  2525. Item->Options = O >> tboDefault;
  2526. }
  2527. }
  2528. //---------------------------------------------------------------------------
  2529. void __fastcall TCustomScpExplorerForm::DirViewContextPopup(
  2530. TOperationSide Side, Byte PopupComponent, const TPoint &MousePos)
  2531. {
  2532. TCustomDirView * DView = DirView(Side);
  2533. TListItem * Item = DView->ItemFocused;
  2534. if ((DView->GetItemAt(MousePos.x, MousePos.y) == Item) &&
  2535. EnableFocusedOperation[Side])
  2536. {
  2537. TPoint ClientPoint;
  2538. ClientPoint = ((MousePos.x < 0) && (MousePos.y < 0)) ?
  2539. TPoint(0, 0) : MousePos;
  2540. FLastContextPopupScreenPoint = DView->ClientToScreen(ClientPoint);
  2541. reinterpret_cast<TPopupMenu*>(GetComponent(PopupComponent))->Popup(
  2542. FLastContextPopupScreenPoint.x, FLastContextPopupScreenPoint.y);
  2543. }
  2544. }
  2545. //---------------------------------------------------------------------------
  2546. void __fastcall TCustomScpExplorerForm::RemoteDirViewContextPopup(
  2547. TObject * /*Sender*/, const TPoint &MousePos, bool &Handled)
  2548. {
  2549. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteOpenMenuItem, rdcaChangeDir, rdcaOpen);
  2550. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteEditMenuItem, rdcaEdit, rdcaNone);
  2551. DirViewContextPopupDefaultItem(osRemote, NonVisualDataModule->RemoteCopyMenuItem, rdcaCopy, rdcaNone);
  2552. DirViewContextPopup(osRemote, fcRemotePopup, MousePos);
  2553. Handled = true;
  2554. }
  2555. //---------------------------------------------------------------------------
  2556. void __fastcall TCustomScpExplorerForm::ReloadLocalDirectory(const UnicodeString Directory)
  2557. {
  2558. }
  2559. //---------------------------------------------------------------------------
  2560. void __fastcall TCustomScpExplorerForm::BatchStart(void *& /*Storage*/)
  2561. {
  2562. DebugAssert(FErrorList == NULL);
  2563. if (WinConfiguration->ContinueOnError)
  2564. {
  2565. FErrorList = new TStringList();
  2566. Configuration->Usage->Inc(L"ContinuationsOnError");
  2567. }
  2568. NonVisualDataModule->StartBusy();
  2569. }
  2570. //---------------------------------------------------------------------------
  2571. void __fastcall TCustomScpExplorerForm::BatchEnd(void * /*Storage*/)
  2572. {
  2573. NonVisualDataModule->EndBusy();
  2574. if (FErrorList)
  2575. {
  2576. HandleErrorList(FErrorList);
  2577. }
  2578. }
  2579. //---------------------------------------------------------------------------
  2580. void __fastcall TCustomScpExplorerForm::UpdateCopyParamCounters(
  2581. const TCopyParamType & CopyParam)
  2582. {
  2583. if (!CopyParam.IncludeFileMask.Masks.IsEmpty())
  2584. {
  2585. Configuration->Usage->Inc(L"FileMaskUses");
  2586. }
  2587. if (IsEffectiveFileNameMask(CopyParam.FileMask))
  2588. {
  2589. Configuration->Usage->Inc(L"OperationMaskUses");
  2590. }
  2591. }
  2592. //---------------------------------------------------------------------------
  2593. bool __fastcall TCustomScpExplorerForm::ExecuteCopyMoveFileOperation(
  2594. TFileOperation Operation, TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * AParam)
  2595. {
  2596. DebugAssert(!IsLocalBrowserMode());
  2597. TTransferDirection Direction = (Side == osLocal ? tdToRemote : tdToLocal);
  2598. TTransferType Type = (Operation == foCopy ? ttCopy : ttMove);
  2599. TTransferOperationParam DefaultParam;
  2600. TTransferOperationParam & Param = (AParam != NULL) ? *static_cast<TTransferOperationParam *>(AParam) : DefaultParam;
  2601. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  2602. switch (Param.Queue)
  2603. {
  2604. case asOn:
  2605. CopyParam.Queue = true;
  2606. break;
  2607. case asOff:
  2608. CopyParam.Queue = false;
  2609. break;
  2610. case asAuto:
  2611. default:
  2612. // keep default
  2613. break;
  2614. }
  2615. bool Result =
  2616. CopyParamDialog(Direction, Type, Param.Temp, FileList, Param.TargetDirectory, CopyParam, !NoConfirmation, Param.DragDrop, Param.Options);
  2617. if (Result)
  2618. {
  2619. DebugAssert(Terminal);
  2620. bool SelectionRestored = false;
  2621. TCustomDirView * DView = NULL;
  2622. if (HasDirView[Side])
  2623. {
  2624. DView = DirView(Side);
  2625. DView->SaveSelection();
  2626. DView->SaveSelectedNames();
  2627. }
  2628. UpdateCopyParamCounters(CopyParam);
  2629. std::unique_ptr<TStringList> TransferResumeList(new TStringList());
  2630. DebugAssert(FTransferResumeList == NULL);
  2631. FTransferResumeList = Terminal->IsCapable[fcMoveToQueue] ? TransferResumeList.get() : NULL;
  2632. FMoveToQueue = false;
  2633. int Params = FLAGMASK(Operation == foMove, cpDelete);
  2634. try
  2635. {
  2636. TStrings * PermanentFileList;
  2637. std::unique_ptr<TStrings> PermanentFileListOwner;
  2638. try
  2639. {
  2640. if (Side == osLocal)
  2641. {
  2642. PermanentFileList = FileList;
  2643. Params |= FLAGMASK(Param.Temp, cpTemporary);
  2644. CopyParam.IncludeFileMask.SetRoots(FileList, Param.TargetDirectory);
  2645. Terminal->CopyToRemote(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2646. if (Operation == foMove)
  2647. {
  2648. ReloadLocalDirectory();
  2649. if (DView != NULL)
  2650. {
  2651. DView->RestoreSelection();
  2652. }
  2653. SelectionRestored = true;
  2654. }
  2655. }
  2656. else
  2657. {
  2658. // Clone the file list as it may refer to current directory files,
  2659. // which get destroyed, when the source directory is reloaded after foMove operation.
  2660. // We should actually clone the file list for whole ExecuteFileOperation to protect against reloads.
  2661. // But for a hotfix, we are not going to do such a big change.
  2662. PermanentFileListOwner.reset(TRemoteFileList::CloneStrings(FileList));
  2663. PermanentFileList = PermanentFileListOwner.get();
  2664. try
  2665. {
  2666. CopyParam.IncludeFileMask.SetRoots(Param.TargetDirectory, FileList);
  2667. Terminal->CopyToLocal(FileList, Param.TargetDirectory, &CopyParam, Params, NULL);
  2668. }
  2669. __finally
  2670. {
  2671. if (Operation == foMove)
  2672. {
  2673. if (DView != NULL)
  2674. {
  2675. DView->RestoreSelection();
  2676. }
  2677. SelectionRestored = true;
  2678. }
  2679. ReloadLocalDirectory(Param.TargetDirectory);
  2680. }
  2681. }
  2682. // When the transfer batch is aborted between individual file transfers, the Abort is not called.
  2683. if (FMoveToQueue)
  2684. {
  2685. Abort();
  2686. }
  2687. }
  2688. catch (EAbort &)
  2689. {
  2690. if (FMoveToQueue)
  2691. {
  2692. Params |= (CopyParam.QueueNoConfirmation ? cpNoConfirmation : 0);
  2693. DebugAssert(CopyParam.TransferSkipList == NULL);
  2694. DebugAssert(CopyParam.TransferResumeFile.IsEmpty());
  2695. if (TransferResumeList->Count > 0)
  2696. {
  2697. CopyParam.TransferResumeFile = TransferResumeList->Strings[TransferResumeList->Count - 1];
  2698. TransferResumeList->Delete(TransferResumeList->Count - 1);
  2699. }
  2700. CopyParam.TransferSkipList = TransferResumeList.release();
  2701. // not really needed, just to keep it consistent with TransferResumeList
  2702. FTransferResumeList = NULL;
  2703. FMoveToQueue = false;
  2704. Configuration->Usage->Inc("MovesToBackground");
  2705. AddQueueItem(Queue, Direction, PermanentFileList, Param.TargetDirectory, CopyParam, Params);
  2706. ClearTransferSourceSelection(Direction);
  2707. }
  2708. throw;
  2709. }
  2710. }
  2711. __finally
  2712. {
  2713. if (!SelectionRestored && (DView != NULL))
  2714. {
  2715. DView->DiscardSavedSelection();
  2716. }
  2717. FTransferResumeList = NULL;
  2718. }
  2719. }
  2720. return Result;
  2721. }
  2722. //---------------------------------------------------------------------------
  2723. bool __fastcall TCustomScpExplorerForm::ExecuteDeleteFileOperation(
  2724. TOperationSide Side, TStrings * FileList, void * Param)
  2725. {
  2726. DebugAssert(FileList->Count);
  2727. // We deliberately do not toggle alternative flag (Param), but use OR,
  2728. // because the Param is set only when command is invoked using Shift-Del/F8 keyboard
  2729. // shortcut of CurrentDeleteAlternativeAction
  2730. bool Alternative =
  2731. bool(Param) || UseAlternativeFunction();
  2732. bool Recycle;
  2733. if (IsSideLocalBrowser(Side))
  2734. {
  2735. Recycle = (WinConfiguration->DeleteToRecycleBin != Alternative);
  2736. }
  2737. else
  2738. {
  2739. Recycle =
  2740. (Terminal->SessionData->DeleteToRecycleBin != Alternative) &&
  2741. !Terminal->SessionData->RecycleBinPath.IsEmpty() &&
  2742. !Terminal->IsRecycledFile(FileList->Strings[0]);
  2743. }
  2744. bool Result = !(Recycle ? WinConfiguration->ConfirmRecycling : WinConfiguration->ConfirmDeleting);
  2745. if (!Result)
  2746. {
  2747. UnicodeString Query;
  2748. if (FileList->Count == 1)
  2749. {
  2750. if (IsSideLocalBrowser(Side))
  2751. {
  2752. Query = ExtractFileName(FileList->Strings[0]);
  2753. }
  2754. else
  2755. {
  2756. Query = UnixExtractFileName(FileList->Strings[0]);
  2757. }
  2758. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILE : CONFIRM_DELETE_FILE), (Query));
  2759. }
  2760. else
  2761. {
  2762. Query = FMTLOAD((Recycle ? CONFIRM_RECYCLE_FILES : CONFIRM_DELETE_FILES), (FileList->Count));
  2763. }
  2764. TMessageParams Params(mpNeverAskAgainCheck);
  2765. Params.ImageName = L"Delete file";
  2766. unsigned int Answer =
  2767. MessageDialog(MainInstructions(Query), qtConfirmation, qaOK | qaCancel, HELP_DELETE_FILE, &Params);
  2768. if (Answer == qaNeverAskAgain)
  2769. {
  2770. Result = true;
  2771. if (Recycle)
  2772. {
  2773. WinConfiguration->ConfirmRecycling = false;
  2774. }
  2775. else
  2776. {
  2777. WinConfiguration->ConfirmDeleting = false;
  2778. }
  2779. }
  2780. else
  2781. {
  2782. Result = (Answer == qaOK);
  2783. }
  2784. }
  2785. if (Result)
  2786. {
  2787. DeleteFiles(Side, FileList, FLAGMASK(Alternative, dfAlternative));
  2788. }
  2789. return Result;
  2790. }
  2791. //---------------------------------------------------------------------------
  2792. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2793. TOperationSide Side, TStrings * FileList, bool NoConfirmation, void * Param)
  2794. {
  2795. TAutoBatch AutoBatch(this);
  2796. bool Result;
  2797. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2798. {
  2799. Result = ExecuteCopyMoveFileOperation(Operation, Side, FileList, NoConfirmation, Param);
  2800. }
  2801. else if (Operation == foRename)
  2802. {
  2803. DebugAssert(DirView(Side)->ItemFocused);
  2804. DirView(Side)->ItemFocused->EditCaption();
  2805. Result = true;
  2806. }
  2807. else if (Operation == foDelete)
  2808. {
  2809. Result = ExecuteDeleteFileOperation(Side, FileList, Param);
  2810. }
  2811. else if (Operation == foSetProperties)
  2812. {
  2813. DirView(osRemote)->SaveSelectedNames();
  2814. Result = SetProperties(Side, FileList);
  2815. }
  2816. else if (Operation == foCustomCommand)
  2817. {
  2818. DebugAssert(Param);
  2819. DebugAssert(Side == osRemote); // Side carries no meaning for foCustomCommand
  2820. DirView(osRemote)->SaveSelectedNames();
  2821. const TCustomCommandType * Command = static_cast<const TCustomCommandType*>(Param);
  2822. CustomCommand(FileList, *Command, NULL);
  2823. Result = true;
  2824. }
  2825. else if ((Operation == foRemoteMove) || (Operation == foRemoteCopy))
  2826. {
  2827. DebugAssert(!IsSideLocalBrowser(Side));
  2828. Result = RemoteTransferFiles(FileList, NoConfirmation,
  2829. (Operation == foRemoteMove), reinterpret_cast<TManagedTerminal *>(Param));
  2830. }
  2831. else if (Operation == foLock)
  2832. {
  2833. DebugAssert(!IsSideLocalBrowser(Side));
  2834. LockFiles(FileList, true);
  2835. Result = true;
  2836. }
  2837. else if (Operation == foUnlock)
  2838. {
  2839. DebugAssert(!IsSideLocalBrowser(Side));
  2840. LockFiles(FileList, false);
  2841. Result = true;
  2842. }
  2843. else
  2844. {
  2845. DebugFail();
  2846. }
  2847. return Result;
  2848. }
  2849. //---------------------------------------------------------------------------
  2850. TOperationSide __fastcall TCustomScpExplorerForm::GetSide(TOperationSide Side)
  2851. {
  2852. if (Side == osCurrent)
  2853. {
  2854. Side = FCurrentSide;
  2855. }
  2856. return Side;
  2857. }
  2858. //---------------------------------------------------------------------------
  2859. TOperationSide TCustomScpExplorerForm::GetOtherSide(TOperationSide Side)
  2860. {
  2861. TOperationSide Result;
  2862. switch (GetSide(Side))
  2863. {
  2864. case osLocal:
  2865. Result = osOther;
  2866. break;
  2867. case osOther:
  2868. Result = osLocal;
  2869. break;
  2870. default:
  2871. DebugFail();
  2872. Abort();
  2873. }
  2874. return Result;
  2875. }
  2876. //---------------------------------------------------------------------------
  2877. bool __fastcall TCustomScpExplorerForm::ExecuteFileOperation(TFileOperation Operation,
  2878. TOperationSide Side, bool OnFocused, bool NoConfirmation, void * Param)
  2879. {
  2880. Side = GetSide(Side);
  2881. bool FullPath = IsSideLocalBrowser(Side);
  2882. TCustomDirView * ADirView = DirView(Side);
  2883. std::unique_ptr<TStringList> FileList(new TStringList());
  2884. ADirView->CreateFileList(OnFocused, FullPath, FileList.get());
  2885. bool ReloadProperties =
  2886. !IsSideLocalBrowser(Side) && (Operation == foSetProperties) &&
  2887. DebugAlwaysTrue(HasActiveTerminal()) && Terminal->IsCapable[fcLoadingAdditionalProperties];
  2888. bool Result = ExecuteFileOperation(Operation, Side, FileList.get(), NoConfirmation, Param);
  2889. if (Result && ReloadProperties)
  2890. {
  2891. std::unique_ptr<TStringList> FileList2(new TStringList());
  2892. FileList->CaseSensitive = true;
  2893. FileList->Sort();
  2894. for (int Index = 0; Index < ADirView->Items->Count; Index++)
  2895. {
  2896. TListItem * Item = ADirView->Items->Item[Index];
  2897. UnicodeString FileName = ADirView->ItemFileName(Item);
  2898. int Index2;
  2899. if (FileList->Find(FileName, Index2))
  2900. {
  2901. FileList2->AddObject(FileName, ADirView->ItemData(Item));
  2902. }
  2903. }
  2904. LoadFilesProperties(FileList2.get());
  2905. }
  2906. return Result;
  2907. }
  2908. //---------------------------------------------------------------------------
  2909. void __fastcall TCustomScpExplorerForm::ExecuteFileOperationCommand(
  2910. TFileOperation Operation, TOperationSide Side, bool OnFocused,
  2911. bool NoConfirmation, void * Param)
  2912. {
  2913. if (ExecuteFileOperation(Operation, Side, OnFocused, NoConfirmation, Param))
  2914. {
  2915. if (TFileOperationProgressType::IsTransferOperation(Operation))
  2916. {
  2917. DebugAssert(!IsLocalBrowserMode());
  2918. if (GetSide(Side) == osLocal)
  2919. {
  2920. Configuration->Usage->Inc(L"UploadsCommand");
  2921. }
  2922. else
  2923. {
  2924. Configuration->Usage->Inc(L"DownloadsCommand");
  2925. }
  2926. }
  2927. }
  2928. }
  2929. //---------------------------------------------------------------------------
  2930. void __fastcall TCustomScpExplorerForm::ExecuteCopyOperationCommand(
  2931. TOperationSide Side, bool OnFocused, unsigned int Flags)
  2932. {
  2933. TTransferOperationParam Param;
  2934. if ((WinConfiguration->Interface != ifCommander) ||
  2935. WinConfiguration->ScpCommander.ExplorerKeyboardShortcuts)
  2936. {
  2937. Flags &= ~cocShortCutHint;
  2938. }
  2939. TCustomDirView * DView = DirView(Side);
  2940. Param.Options =
  2941. FLAGMASK(FLAGSET(Flags, cocShortCutHint), coShortCutHint) |
  2942. FLAGMASK(SelectedAllFilesInDirView(DView), coAllFiles);
  2943. if (FLAGSET(Flags, cocQueue))
  2944. {
  2945. Param.Queue = asOn;
  2946. }
  2947. else if (FLAGSET(Flags, cocNonQueue))
  2948. {
  2949. Param.Queue = asOff;
  2950. }
  2951. ExecuteFileOperationCommand(foCopy, Side, OnFocused, false, &Param);
  2952. }
  2953. //---------------------------------------------------------------------------
  2954. void __fastcall TCustomScpExplorerForm::HandleErrorList(TStringList *& ErrorList)
  2955. {
  2956. int Count = ErrorList->Count;
  2957. try
  2958. {
  2959. if (ErrorList->Count)
  2960. {
  2961. UnicodeString Message = MainInstructions(FMTLOAD(ERROR_LIST_COUNT, (ErrorList->Count)));
  2962. if (MessageDialog(Message, qtError,
  2963. qaOK | qaCancel, HELP_NONE) == qaOK)
  2964. {
  2965. unsigned int Answer;
  2966. int Index = 0;
  2967. do
  2968. {
  2969. DebugAssert(Index >= 0 && Index < Count);
  2970. TQueryButtonAlias Aliases[2];
  2971. Aliases[0].Button = qaYes;
  2972. Aliases[0].Alias = LoadStr(PREV_BUTTON);
  2973. Aliases[1].Button = qaNo;
  2974. Aliases[1].Alias = LoadStr(NEXT_BUTTON);
  2975. TMessageParams Params;
  2976. Params.Aliases = Aliases;
  2977. Params.AliasesCount = LENOF(Aliases);
  2978. int No = Index + 1;
  2979. UnicodeString Message = ErrorList->Strings[Index];
  2980. UnicodeString AMainInstructions;
  2981. UnicodeString Details;
  2982. if (ExtractMainInstructions(Message, AMainInstructions))
  2983. {
  2984. Details = Message;
  2985. Message = AMainInstructions;
  2986. }
  2987. Message = MainInstructions(FMTLOAD(ERROR_LIST_NUMBER, (No, Count, Message))) + Details;
  2988. Answer = MoreMessageDialog(
  2989. Message,
  2990. dynamic_cast<TStrings *>(ErrorList->Objects[Index]), qtError,
  2991. (Index ? qaYes : 0) | (Index < Count - 1 ? qaNo : 0) |
  2992. qaOK, HELP_NONE, &Params);
  2993. if (Answer == qaNo)
  2994. {
  2995. Index++;
  2996. }
  2997. if (Answer == qaYes)
  2998. {
  2999. Index--;
  3000. }
  3001. }
  3002. while (Answer != qaOK);
  3003. }
  3004. }
  3005. }
  3006. __finally
  3007. {
  3008. TStrings * List = ErrorList;
  3009. ErrorList = NULL;
  3010. for (int i = 0; i < Count; i++)
  3011. {
  3012. delete List->Objects[i];
  3013. }
  3014. delete List;
  3015. }
  3016. }
  3017. //---------------------------------------------------------------------------
  3018. void __fastcall TCustomScpExplorerForm::ExecuteRemoteFile(
  3019. const UnicodeString & FullFileName, TRemoteFile * File, TExecuteFileBy ExecuteFileBy)
  3020. {
  3021. // needed for checking filemasks, as there's no directory object
  3022. // associated with the file object
  3023. File->FullFileName = FullFileName;
  3024. TFileMasks::TParams MaskParams;
  3025. MaskParams.Size = File->Size;
  3026. MaskParams.Modification = File->Modification;
  3027. ExecuteFile(osRemote, ExecuteFileBy, NULL, FullFileName, File, MaskParams);
  3028. }
  3029. //---------------------------------------------------------------------------
  3030. void __fastcall TCustomScpExplorerForm::EditNew(TOperationSide Side)
  3031. {
  3032. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3033. Side = GetSide(Side);
  3034. TCustomDirView * DView = DirView(Side);
  3035. TListItem * FocusedItem = DView->ItemFocused;
  3036. UnicodeString Name;
  3037. if ((FocusedItem != NULL) && !DView->ItemIsDirectory(FocusedItem))
  3038. {
  3039. Name = DView->ItemFileName(FocusedItem);
  3040. }
  3041. else
  3042. {
  3043. Name = LoadStr(NEW_FILE);
  3044. }
  3045. UnicodeString Names = Name;
  3046. std::unique_ptr<TStrings> History(CloneStrings(CustomWinConfiguration->History[L"EditFile"]));
  3047. if (InputDialog(LoadStr(EDIT_FILE_CAPTION), LoadStr(EDIT_FILE_PROMPT), Names,
  3048. HELP_EDIT_NEW, History.get(), true, NULL, true, 400))
  3049. {
  3050. while (!Names.IsEmpty())
  3051. {
  3052. Name = CutToChar(Names, FileMasksDelimiters[1], false);
  3053. CustomWinConfiguration->History[L"EditFile"] = History.get();
  3054. UnicodeString TargetFileName;
  3055. UnicodeString LocalFileName;
  3056. UnicodeString RootTempDir;
  3057. UnicodeString TempDir;
  3058. UnicodeString RemoteDirectory;
  3059. bool ExistingFile = false;
  3060. if (!IsSideLocalBrowser(Side))
  3061. {
  3062. Name = AbsolutePath(Terminal->CurrentDirectory, Name);
  3063. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(Name));
  3064. if ((File.get() != NULL) &&
  3065. !File->IsDirectory)
  3066. {
  3067. ExecuteRemoteFile(Name, File.get(), efDefaultEditor);
  3068. ExistingFile = true;
  3069. }
  3070. File.reset(NULL);
  3071. if (!ExistingFile)
  3072. {
  3073. RemoteDirectory = UnixExtractFilePath(Name);
  3074. TemporaryDirectoryForRemoteFiles(
  3075. RemoteDirectory, GUIConfiguration->CurrentCopyParam, false, TempDir, RootTempDir);
  3076. TargetFileName = UnixExtractFileName(Name);
  3077. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3078. LocalFileName = TempDir +
  3079. // We probably do not want to trim the VMS version here
  3080. Terminal->ChangeFileName(&CopyParam, TargetFileName, osRemote, false);
  3081. }
  3082. }
  3083. else
  3084. {
  3085. if (ExtractFilePath(Name).IsEmpty())
  3086. {
  3087. LocalFileName = IncludeTrailingBackslash(DView->PathName) + Name;
  3088. }
  3089. else
  3090. {
  3091. LocalFileName = ExpandFileName(Name);
  3092. }
  3093. TargetFileName = ExtractFileName(Name);
  3094. }
  3095. if (!ExistingFile)
  3096. {
  3097. bool NewFile = !FileExists(ApiPath(LocalFileName));
  3098. if (NewFile)
  3099. {
  3100. int File = FileCreate(ApiPath(LocalFileName));
  3101. if (File < 0)
  3102. {
  3103. if (!RootTempDir.IsEmpty())
  3104. {
  3105. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3106. }
  3107. throw Exception(FMTLOAD(CREATE_FILE_ERROR, (LocalFileName)));
  3108. }
  3109. else
  3110. {
  3111. FileClose(File);
  3112. }
  3113. }
  3114. TExecuteFileBy ExecuteFileBy = efDefaultEditor;
  3115. const TEditorData * ExternalEditor = NULL;
  3116. TFileMasks::TParams MaskParams; // size not known
  3117. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, TargetFileName,
  3118. false, MaskParams);
  3119. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, TargetFileName,
  3120. ExternalEditor, RootTempDir, RemoteDirectory, NewFile, TDateTime());
  3121. }
  3122. }
  3123. }
  3124. }
  3125. //---------------------------------------------------------------------------
  3126. bool __fastcall TCustomScpExplorerForm::RemoteExecuteForceText(
  3127. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor)
  3128. {
  3129. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3130. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3131. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3132. return
  3133. ((ExecuteFileBy == efInternalEditor)) ||
  3134. ((ExecuteFileBy == efExternalEditor) && ExternalEditor->ExternalEditorText);
  3135. }
  3136. //---------------------------------------------------------------------------
  3137. void __fastcall TCustomScpExplorerForm::CustomExecuteFile(TOperationSide Side,
  3138. TExecuteFileBy ExecuteFileBy, UnicodeString FileName, UnicodeString OriginalFileName,
  3139. const TEditorData * ExternalEditor, UnicodeString LocalRootDirectory,
  3140. UnicodeString RemoteDirectory, bool NewFile, const TDateTime & SourceTimestamp)
  3141. {
  3142. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3143. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3144. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3145. DebugAssert(ExecuteFileBy != efDefaultEditor);
  3146. Side = GetSide(Side);
  3147. std::unique_ptr<TEditedFileData> Data(new TEditedFileData);
  3148. if (!IsSideLocalBrowser(Side))
  3149. {
  3150. Data->Terminal = Terminal;
  3151. Data->SessionData = CloneCurrentSessionData();
  3152. Data->ForceText = RemoteExecuteForceText(ExecuteFileBy, ExternalEditor);
  3153. Data->RemoteDirectory = RemoteDirectory;
  3154. Data->SessionName = Terminal->SessionData->SessionName;
  3155. Data->LocalRootDirectory = LocalRootDirectory;
  3156. Data->OriginalFileName = OriginalFileName;
  3157. Data->Command = L""; // will be changed later for external editor
  3158. // Empty SourceTimestamp indicates that checking was disabled when the file was opened
  3159. if (WinConfiguration->EditorCheckNotModified)
  3160. {
  3161. Data->SourceTimestamp = SourceTimestamp;
  3162. }
  3163. }
  3164. if (ExecuteFileBy == efInternalEditor)
  3165. {
  3166. if (!IsSideLocalBrowser(Side))
  3167. {
  3168. UnicodeString RemotePath = UnixCombinePaths(RemoteDirectory, OriginalFileName);
  3169. UnicodeString Caption = RemotePath + TitleSeparator + Terminal->SessionData->SessionName;
  3170. TForm * Editor;
  3171. try
  3172. {
  3173. Editor =
  3174. ShowEditorForm(
  3175. FileName, this,
  3176. FEditorManager->FileChanged, FEditorManager->FileReload, FEditorManager->FileClosed,
  3177. SaveAllInternalEditors, AnyInternalEditorModified,
  3178. Caption, StandaloneOperation, SessionColor, Terminal->SessionData->InternalEditorEncoding, NewFile);
  3179. }
  3180. catch(...)
  3181. {
  3182. if (!LocalRootDirectory.IsEmpty())
  3183. {
  3184. RecursiveDeleteFile(ExcludeTrailingBackslash(LocalRootDirectory));
  3185. }
  3186. throw;
  3187. }
  3188. FEditorManager->AddFileInternal(FileName, Data.release(), Editor);
  3189. AppLogFmt(L"Opened internal editor with \"%s\"", (FileName));
  3190. }
  3191. else
  3192. {
  3193. DebugAssert(!StandaloneOperation);
  3194. TForm * Editor =
  3195. ShowEditorForm(FileName, this, NULL, NULL, LocalEditorClosed,
  3196. SaveAllInternalEditors, AnyInternalEditorModified,
  3197. L"", false, SessionColor, -1, NewFile);
  3198. FLocalEditors->Add(Editor);
  3199. }
  3200. }
  3201. else
  3202. {
  3203. HANDLE Process;
  3204. if (ExecuteFileBy == efExternalEditor)
  3205. {
  3206. UnicodeString Program, Params, Dir;
  3207. Data->Command = ExternalEditor->ExternalEditor;
  3208. ReformatFileNameCommand(Data->Command);
  3209. SplitCommand(Data->Command, Program, Params, Dir);
  3210. Params = ExpandFileNameCommand(Params, FileName);
  3211. Program = ExpandEnvironmentVariables(Program);
  3212. if (!ExecuteShell(Program, Params, Process))
  3213. {
  3214. throw EOSExtException(FMTLOAD(EDITOR_ERROR, (Program)));
  3215. }
  3216. }
  3217. else
  3218. {
  3219. DebugAssert(!IsSideLocalBrowser(Side));
  3220. if (!ExecuteShell(FileName, L"", Process))
  3221. {
  3222. throw EOSExtException(FMTLOAD(EXECUTE_FILE_ERROR, (FileName)));
  3223. }
  3224. }
  3225. if (IsSideLocalBrowser(Side) ||
  3226. ((ExecuteFileBy == efShell) &&
  3227. !WinConfiguration->Editor.SDIShellEditor) ||
  3228. ((ExecuteFileBy == efExternalEditor) &&
  3229. !ExternalEditor->SDIExternalEditor))
  3230. {
  3231. // no need for handle
  3232. if (Process != NULL)
  3233. {
  3234. DebugCheck(CloseHandle(Process));
  3235. }
  3236. Process = INVALID_HANDLE_VALUE;
  3237. }
  3238. else
  3239. {
  3240. if (Process == NULL)
  3241. {
  3242. throw ExtException(LoadStr(OPEN_FILE_NO_PROCESS2), L"", HELP_OPEN_FILE_NO_PROCESS);
  3243. }
  3244. }
  3245. if (!IsSideLocalBrowser(Side))
  3246. {
  3247. FEditorManager->AddFileExternal(FileName, Data.release(), Process);
  3248. AppLogFmt(L"Opened external editor with remote file \"%s\".", (FileName));
  3249. }
  3250. }
  3251. }
  3252. //---------------------------------------------------------------------------
  3253. void __fastcall TCustomScpExplorerForm::SaveInternalEditor(
  3254. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3255. void * /*Arg*/)
  3256. {
  3257. if (Token != NULL)
  3258. {
  3259. EditorFormFileSave(static_cast<TForm *>(Token));
  3260. }
  3261. }
  3262. //---------------------------------------------------------------------------
  3263. void __fastcall TCustomScpExplorerForm::SaveAllInternalEditors(TObject * /*Sender*/)
  3264. {
  3265. for (int Index = 0; Index < FLocalEditors->Count; Index++)
  3266. {
  3267. EditorFormFileSave(static_cast<TForm *>(FLocalEditors->Items[Index]));
  3268. }
  3269. FEditorManager->ProcessFiles(SaveInternalEditor, NULL);
  3270. }
  3271. //---------------------------------------------------------------------------
  3272. void __fastcall TCustomScpExplorerForm::InternalEditorModified(
  3273. const UnicodeString /*FileName*/, TEditedFileData * /*Data*/, TObject * Token,
  3274. void * Arg)
  3275. {
  3276. if ((Token != NULL) &&
  3277. IsEditorFormModified(static_cast<TForm *>(Token)))
  3278. {
  3279. *static_cast<bool *>(Arg) = true;
  3280. }
  3281. }
  3282. //---------------------------------------------------------------------------
  3283. void __fastcall TCustomScpExplorerForm::AnyInternalEditorModified(
  3284. TObject * /*Sender*/, bool & Modified)
  3285. {
  3286. for (int Index = 0; !Modified && (Index < FLocalEditors->Count); Index++)
  3287. {
  3288. if (IsEditorFormModified(static_cast<TForm *>(FLocalEditors->Items[Index])))
  3289. {
  3290. Modified = true;
  3291. }
  3292. }
  3293. if (!Modified)
  3294. {
  3295. FEditorManager->ProcessFiles(InternalEditorModified, &Modified);
  3296. }
  3297. }
  3298. //---------------------------------------------------------------------------
  3299. void __fastcall TCustomScpExplorerForm::LocalEditorClosed(TObject * Sender, bool /*Forced*/)
  3300. {
  3301. DebugCheck(FLocalEditors->Extract(Sender) >= 0);
  3302. }
  3303. //---------------------------------------------------------------------------
  3304. void __fastcall TCustomScpExplorerForm::TemporaryDirectoryForRemoteFiles(
  3305. const UnicodeString & RemoteDirectory, const TCopyParamType & CopyParam, bool Simple,
  3306. UnicodeString & Result, UnicodeString & RootDirectory)
  3307. {
  3308. if (!WinConfiguration->TemporaryDirectoryDeterministic || Simple)
  3309. {
  3310. RootDirectory = IncludeTrailingBackslash(WinConfiguration->TemporaryDir());
  3311. Result = RootDirectory;
  3312. }
  3313. else
  3314. {
  3315. RootDirectory = L"";
  3316. Result = WinConfiguration->ExpandedTemporaryDirectory();
  3317. Result = IncludeTrailingBackslash(Result);
  3318. }
  3319. if (WinConfiguration->TemporaryDirectoryAppendSession && !Simple)
  3320. {
  3321. Result = IncludeTrailingBackslash(Result + MakeValidFileName(Terminal->SessionData->SessionName));
  3322. }
  3323. if (WinConfiguration->TemporaryDirectoryAppendPath && !Simple)
  3324. {
  3325. UnicodeString ARemoteDirectory = RemoteDirectory;
  3326. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory[1] == L'/'))
  3327. {
  3328. ARemoteDirectory.Delete(1, 1);
  3329. }
  3330. Result = IncludeTrailingBackslash(Result + CopyParam.ValidLocalPath(FromUnixPath(ARemoteDirectory)));
  3331. }
  3332. if (!ForceDirectories(ApiPath(Result)))
  3333. {
  3334. throw EOSExtException(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  3335. }
  3336. }
  3337. //---------------------------------------------------------------------------
  3338. void __fastcall TCustomScpExplorerForm::TemporarilyDownloadFiles(
  3339. TStrings * FileList, bool ForceText, UnicodeString & RootTempDir, UnicodeString & TempDir,
  3340. bool GetTargetNames, bool AutoOperation, bool SimpleTempDir)
  3341. {
  3342. DebugAssert(!IsLocalBrowserMode());
  3343. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3344. if (ForceText)
  3345. {
  3346. CopyParam.TransferMode = tmAscii;
  3347. }
  3348. TemporaryFileCopyParam(CopyParam);
  3349. if (TempDir.IsEmpty())
  3350. {
  3351. TemporaryDirectoryForRemoteFiles(Terminal->CurrentDirectory, CopyParam, SimpleTempDir, TempDir, RootTempDir);
  3352. }
  3353. DebugAssert(!FAutoOperation);
  3354. FAutoOperation = AutoOperation;
  3355. Terminal->ExceptionOnFail = true;
  3356. try
  3357. {
  3358. try
  3359. {
  3360. // turn off confirmations, as for MDI editors we may possibly download
  3361. // the same file over
  3362. Terminal->CopyToLocal(
  3363. FileList, TempDir, &CopyParam, cpNoConfirmation | cpTemporary, NULL);
  3364. if (GetTargetNames)
  3365. {
  3366. for (int i = 0; i < FileList->Count; i++)
  3367. {
  3368. FileList->Strings[i] =
  3369. Terminal->ChangeFileName(&CopyParam, UnixExtractFileName(FileList->Strings[i]), osRemote, false);
  3370. }
  3371. }
  3372. }
  3373. catch(...)
  3374. {
  3375. if (!RootTempDir.IsEmpty())
  3376. {
  3377. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  3378. }
  3379. throw;
  3380. }
  3381. }
  3382. __finally
  3383. {
  3384. FAutoOperation = false;
  3385. Terminal->ExceptionOnFail = false;
  3386. }
  3387. }
  3388. //---------------------------------------------------------------------------
  3389. void __fastcall TCustomScpExplorerForm::EditorAutoConfig()
  3390. {
  3391. // Do not waste time checking for default editor list the next time,
  3392. // or testing if default editor is not notepad.
  3393. bool TryNextTime = false;
  3394. UnicodeString UsageState;
  3395. if (!WinConfiguration->EditorList->IsDefaultList())
  3396. {
  3397. UsageState = "H";
  3398. }
  3399. else
  3400. {
  3401. UnicodeString Executable;
  3402. UnicodeString ExecutableDescription;
  3403. if (DetectSystemExternalEditor(false, Executable, ExecutableDescription, UsageState, TryNextTime))
  3404. {
  3405. UnicodeString Message =
  3406. FMTLOAD(EDITOR_AUTO_CONFIG2, (ExecutableDescription, ExecutableDescription));
  3407. unsigned int Answer =
  3408. MessageDialog(Message, qtConfirmation, qaOK | qaCancel, HELP_EDITOR_AUTO_CONFIG);
  3409. if (Answer != qaOK)
  3410. {
  3411. UsageState = "R";
  3412. }
  3413. else
  3414. {
  3415. UsageState = "A";
  3416. TEditorData EditorData;
  3417. EditorData.Editor = edExternal;
  3418. EditorData.ExternalEditor = FormatCommand(Executable, L"");
  3419. EditorData.ExternalEditorOptionsAutodetect();
  3420. TEditorList EditorList;
  3421. EditorList = *WinConfiguration->EditorList;
  3422. EditorList.Insert(0, new TEditorPreferences(EditorData));
  3423. WinConfiguration->EditorList = &EditorList;
  3424. }
  3425. }
  3426. }
  3427. WinConfiguration->OfferedEditorAutoConfig = !TryNextTime;
  3428. WinConfiguration->Usage->Set(L"EditorAutoConfig", UsageState);
  3429. }
  3430. //---------------------------------------------------------------------------
  3431. void __fastcall TCustomScpExplorerForm::ExecuteFileNormalize(
  3432. TExecuteFileBy & ExecuteFileBy, const TEditorData *& ExternalEditor,
  3433. const UnicodeString & FileName, bool Local, const TFileMasks::TParams & MaskParams)
  3434. {
  3435. if (ExecuteFileBy == efDefaultEditor)
  3436. {
  3437. if (!WinConfiguration->OfferedEditorAutoConfig)
  3438. {
  3439. EditorAutoConfig();
  3440. }
  3441. const TEditorPreferences * Editor =
  3442. WinConfiguration->DefaultEditorForFile(FileName, Local, MaskParams);
  3443. if ((Editor == NULL) || (Editor->Data->Editor == edInternal))
  3444. {
  3445. ExecuteFileBy = efInternalEditor;
  3446. ExternalEditor = NULL;
  3447. }
  3448. else if (Editor->Data->Editor == edOpen)
  3449. {
  3450. ExecuteFileBy = efShell;
  3451. ExternalEditor = NULL;
  3452. }
  3453. else
  3454. {
  3455. ExecuteFileBy = efExternalEditor;
  3456. ExternalEditor = Editor->Data;
  3457. }
  3458. }
  3459. }
  3460. //---------------------------------------------------------------------------
  3461. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3462. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3463. UnicodeString FullFileName, TObject * Object, const TFileMasks::TParams & MaskParams)
  3464. {
  3465. UnicodeString OriginalFileName;
  3466. UnicodeString LocalRootDirectory;
  3467. UnicodeString RemoteDirectory;
  3468. ExecuteFileNormalize(ExecuteFileBy, ExternalEditor, FullFileName,
  3469. IsSideLocalBrowser(Side), MaskParams);
  3470. UnicodeString Counter;
  3471. UnicodeString LocalFileName;
  3472. bool Handled = false;
  3473. if (!IsSideLocalBrowser(Side))
  3474. {
  3475. // We need to trim VMS version here, so that we use name without version
  3476. // when uploading back to create a new version of the file
  3477. OriginalFileName = Terminal->GetBaseFileName(UnixExtractFileName(FullFileName));
  3478. RemoteDirectory = UnixExtractFilePath(FullFileName);
  3479. TObject * Token = NULL;
  3480. UnicodeString LocalDirectory;
  3481. if (!FEditorManager->CanAddFile(RemoteDirectory, OriginalFileName,
  3482. Terminal->SessionData->SessionName, Token, LocalRootDirectory,
  3483. LocalDirectory))
  3484. {
  3485. if (Token != NULL)
  3486. {
  3487. TForm * Form = dynamic_cast<TForm *>(Token);
  3488. if (Form->WindowState == wsMinimized)
  3489. {
  3490. ShowWindow(Form->Handle, SW_RESTORE);
  3491. }
  3492. else
  3493. {
  3494. Form->SetFocus();
  3495. }
  3496. Handled = true;
  3497. }
  3498. else
  3499. {
  3500. throw Exception(FMTLOAD(ALREADY_EDITED_EXTERNALLY_OR_UPLOADED, (OriginalFileName)));
  3501. }
  3502. }
  3503. if (!Handled)
  3504. {
  3505. TStringList * FileList1 = new TStringList();
  3506. try
  3507. {
  3508. FileList1->AddObject(FullFileName, Object);
  3509. TemporarilyDownloadFiles(FileList1,
  3510. RemoteExecuteForceText(ExecuteFileBy, ExternalEditor),
  3511. LocalRootDirectory, LocalDirectory, true, true, false);
  3512. LocalFileName = LocalDirectory + FileList1->Strings[0];
  3513. }
  3514. __finally
  3515. {
  3516. delete FileList1;
  3517. }
  3518. switch (ExecuteFileBy)
  3519. {
  3520. case efShell:
  3521. Counter = "RemoteFilesExecuted";
  3522. break;
  3523. case efInternalEditor:
  3524. Counter = "RemoteFilesOpenedInInternalEditor";
  3525. break;
  3526. case efExternalEditor:
  3527. Counter = "RemoteFilesOpenedInExternalEditor";
  3528. break;
  3529. default:
  3530. DebugFail();
  3531. }
  3532. }
  3533. }
  3534. else
  3535. {
  3536. LocalFileName = FullFileName;
  3537. OriginalFileName = ExtractFileName(FullFileName);
  3538. switch (ExecuteFileBy)
  3539. {
  3540. case efShell:
  3541. Counter = "LocalFilesExecuted";
  3542. break;
  3543. case efInternalEditor:
  3544. Counter = "LocalFilesOpenedInInternalEditor";
  3545. break;
  3546. case efExternalEditor:
  3547. Counter = "LocalFilesOpenedInExternalEditor";
  3548. break;
  3549. default:
  3550. DebugFail();
  3551. }
  3552. }
  3553. if (!Handled)
  3554. {
  3555. Configuration->Usage->Inc(Counter);
  3556. CustomExecuteFile(Side, ExecuteFileBy, LocalFileName, OriginalFileName,
  3557. ExternalEditor, LocalRootDirectory, RemoteDirectory, false, MaskParams.Modification);
  3558. }
  3559. }
  3560. //---------------------------------------------------------------------------
  3561. void __fastcall TCustomScpExplorerForm::ExecuteFile(TOperationSide Side,
  3562. TExecuteFileBy ExecuteFileBy, const TEditorData * ExternalEditor,
  3563. bool AllSelected, bool OnFocused)
  3564. {
  3565. DebugAssert(!WinConfiguration->DisableOpenEdit);
  3566. DebugAssert((ExecuteFileBy == efExternalEditor) ==
  3567. ((ExternalEditor != NULL) && (ExternalEditor->Editor == edExternal)));
  3568. Side = GetSide(Side);
  3569. TCustomDirView * DView = DirView(Side);
  3570. TStrings * FileList =
  3571. AllSelected ?
  3572. DView->CreateFileList(OnFocused, IsSideLocalBrowser(Side)) :
  3573. DView->CreateFocusedFileList(IsSideLocalBrowser(Side));
  3574. try
  3575. {
  3576. DebugAssert(AllSelected || (FileList->Count == 1));
  3577. for (int i = 0; i < FileList->Count; i++)
  3578. {
  3579. UnicodeString ListFileName = FileList->Strings[i];
  3580. UnicodeString FileNameOnly =
  3581. !IsSideLocalBrowser(Side) ? UnixExtractFileName(ListFileName) : ExtractFileName(ListFileName);
  3582. TListItem * Item = DView->FindFileItem(FileNameOnly);
  3583. if (!DView->ItemIsDirectory(Item))
  3584. {
  3585. UnicodeString FullFileName;
  3586. if (!IsSideLocalBrowser(Side))
  3587. {
  3588. FullFileName = DirView(Side)->Path + ListFileName;
  3589. }
  3590. else
  3591. {
  3592. FullFileName = ListFileName;
  3593. }
  3594. TObject * Object = FileList->Objects[i];
  3595. TFileMasks::TParams MaskParams;
  3596. MaskParams.Size = DView->ItemFileSize(Item);
  3597. TDateTimePrecision Precision;
  3598. MaskParams.Modification = DView->ItemFileTime(Item, Precision);
  3599. std::unique_ptr<TRemoteFile> File;
  3600. if (!IsSideLocalBrowser(Side))
  3601. {
  3602. File.reset(Terminal->TryReadFile(FullFileName));
  3603. if (File.get() != NULL)
  3604. {
  3605. File->FullFileName = FullFileName;
  3606. Object = File.get();
  3607. MaskParams.Size = File->Size;
  3608. MaskParams.Modification = File->Modification;
  3609. }
  3610. }
  3611. ExecuteFile(Side, ExecuteFileBy, ExternalEditor, FullFileName, Object, MaskParams);
  3612. }
  3613. }
  3614. }
  3615. __finally
  3616. {
  3617. delete FileList;
  3618. }
  3619. }
  3620. //---------------------------------------------------------------------------
  3621. void __fastcall TCustomScpExplorerForm::TemporaryFileCopyParam(TCopyParamType & CopyParam)
  3622. {
  3623. CopyParam.FileNameCase = ncNoChange;
  3624. CopyParam.PreserveRights = false;
  3625. CopyParam.PreserveReadOnly = false;
  3626. CopyParam.ReplaceInvalidChars = true;
  3627. CopyParam.IncludeFileMask = TFileMasks();
  3628. CopyParam.NewerOnly = false;
  3629. CopyParam.FileMask = L"";
  3630. }
  3631. //---------------------------------------------------------------------------
  3632. bool TCustomScpExplorerForm::EditorCheckNotModified(const TEditedFileData * Data)
  3633. {
  3634. return WinConfiguration->EditorCheckNotModified && (Data->SourceTimestamp != TDateTime());
  3635. }
  3636. //---------------------------------------------------------------------------
  3637. class TEditorUploadQueueItem : public TUploadQueueItem
  3638. {
  3639. public:
  3640. __fastcall TEditorUploadQueueItem(
  3641. TTerminal * Terminal, TStrings * FilesToCopy, const UnicodeString & TargetDir,
  3642. const TCopyParamType * CopyParam, int Params) :
  3643. TUploadQueueItem(Terminal, FilesToCopy, TargetDir, CopyParam, Params, true, false)
  3644. {
  3645. }
  3646. protected:
  3647. virtual void __fastcall DoTransferExecute(TTerminal * Terminal, TParallelOperation * ParallelOperation)
  3648. {
  3649. TUploadQueueItem::DoTransferExecute(Terminal, ParallelOperation);
  3650. TTerminalManager::Instance()->ScpExplorer->EditedFileUploaded(Terminal, CompleteEvent);
  3651. }
  3652. };
  3653. //---------------------------------------------------------------------------
  3654. void TCustomScpExplorerForm::EditedFileUploaded(TTerminal * ATerminal, HANDLE UploadCompleteEvent)
  3655. {
  3656. if (WinConfiguration->EditorCheckNotModified) // optimization
  3657. {
  3658. UnicodeString RemoteFilePath;
  3659. {
  3660. TGuard Guard(FEditorManager->Section);
  3661. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3662. if (DebugAlwaysTrue(Data != NULL) &&
  3663. EditorCheckNotModified(Data))
  3664. {
  3665. RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3666. }
  3667. }
  3668. if (!RemoteFilePath.IsEmpty())
  3669. {
  3670. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(RemoteFilePath));
  3671. if (File.get() != NULL)
  3672. {
  3673. TGuard Guard(FEditorManager->Section);
  3674. TEditedFileData * Data = FEditorManager->FindByUploadCompleteEvent(UploadCompleteEvent);
  3675. if (DebugAlwaysTrue(Data != NULL))
  3676. {
  3677. Data->SourceTimestamp = File->Modification;
  3678. AppLogFmt(L"Uploaded edited remote file timestamp: %s", (StandardTimestamp(Data->SourceTimestamp)));
  3679. }
  3680. }
  3681. }
  3682. }
  3683. }
  3684. //---------------------------------------------------------------------------
  3685. void __fastcall TCustomScpExplorerForm::ExecutedFileChanged(
  3686. const UnicodeString & FileName, TEditedFileData * Data, HANDLE UploadCompleteEvent, bool & Retry)
  3687. {
  3688. TTerminalManager * Manager = TTerminalManager::Instance();
  3689. if ((Manager->ActiveTerminal == Data->Terminal) &&
  3690. Manager->ScheduleTerminalReconnnect(Data->Terminal))
  3691. {
  3692. AppLog(L"Scheduled session reconnect, will retry the upload later");
  3693. Retry = true;
  3694. }
  3695. else if (!IsActiveTerminal(Data->Terminal))
  3696. {
  3697. if (!NonVisualDataModule->Busy)
  3698. {
  3699. UnicodeString FileNameOnly = ExtractFileName(FileName);
  3700. UnicodeString EditInactiveSessionReopenAcceptedCounter = L"EditInactiveSessionReopenAccepted";
  3701. UnicodeString EditInactiveSessionReopenRejectedCounter = L"EditInactiveSessionReopenRejected";
  3702. if (Data->Terminal == NULL)
  3703. {
  3704. TManagedTerminal * SameSiteTerminal = Manager->FindActiveTerminalForSite(Data->SessionData);
  3705. if (SameSiteTerminal != NULL)
  3706. {
  3707. UnicodeString Message =
  3708. FMTLOAD(EDIT_SESSION_REATTACH,
  3709. (FileNameOnly, Data->SessionName, FileNameOnly));
  3710. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3711. {
  3712. Data->Terminal = SameSiteTerminal;
  3713. Data->SessionName = SameSiteTerminal->SessionData->SessionName;
  3714. // We might also overwrite session data
  3715. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3716. }
  3717. else
  3718. {
  3719. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3720. Abort();
  3721. }
  3722. }
  3723. }
  3724. // Foreground session should reconnect itself (except for those disconnected explicitly by the user)
  3725. else if (DebugAlwaysTrue(Terminal->Disconnected || (Terminal != Data->Terminal)))
  3726. {
  3727. UnicodeString Message =
  3728. MainInstructions(
  3729. FMTLOAD(EDIT_SESSION_RECONNECT, (Data->SessionName, FileNameOnly)));
  3730. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) == qaOK)
  3731. {
  3732. if (Terminal->Disconnected)
  3733. {
  3734. Manager->ActiveSession = Terminal;
  3735. ReconnectSession();
  3736. // Was it reconnected? (if not, Data->Terminal should be nulled now)
  3737. if (!IsActiveTerminal(Data->Terminal) || (Terminal != Data->Terminal))
  3738. {
  3739. Abort();
  3740. }
  3741. }
  3742. else
  3743. {
  3744. Manager->SetActiveTerminalWithAutoReconnect(Data->Terminal);
  3745. }
  3746. Configuration->Usage->Inc(EditInactiveSessionReopenAcceptedCounter);
  3747. }
  3748. else
  3749. {
  3750. Configuration->Usage->Inc(EditInactiveSessionReopenRejectedCounter);
  3751. Abort();
  3752. }
  3753. }
  3754. }
  3755. if (!IsActiveTerminal(Data->Terminal))
  3756. {
  3757. Configuration->Usage->Inc(L"EditInactiveSession");
  3758. // Prevent this when not idle (!NonVisualDataModule->Busy)?
  3759. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED2,
  3760. (ExtractFileName(FileName), Data->SessionName)));
  3761. }
  3762. }
  3763. if (!Retry && EditorCheckNotModified(Data))
  3764. {
  3765. if (NonVisualDataModule->Busy)
  3766. {
  3767. Retry = true;
  3768. }
  3769. else
  3770. {
  3771. UnicodeString RemoteFilePath = UnixCombinePaths(Data->RemoteDirectory, Data->OriginalFileName);
  3772. std::unique_ptr<TRemoteFile> File(Terminal->TryReadFile(RemoteFilePath));
  3773. if (File.get() != NULL)
  3774. {
  3775. AppLogFmt(L"Edited remote file timestamp: %s, Original timestamp: %s", (StandardTimestamp(File->Modification), StandardTimestamp(Data->SourceTimestamp)));
  3776. if (File->Modification != Data->SourceTimestamp)
  3777. {
  3778. UnicodeString Message = MainInstructions(LoadStr(EDIT_CHANGED_EXTERNALLY));
  3779. if (MessageDialog(Message, qtConfirmation, qaOK | qaCancel) != qaOK)
  3780. {
  3781. Abort();
  3782. }
  3783. }
  3784. }
  3785. }
  3786. }
  3787. if (!Retry)
  3788. {
  3789. TStrings * FileList = new TStringList();
  3790. try
  3791. {
  3792. FileList->Add(FileName);
  3793. // Consider using the same settings (preset) as when the file was downloaded.
  3794. // More over this does not reflect the actual session that will do the upload.
  3795. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  3796. TemporaryFileCopyParam(CopyParam);
  3797. if (Data->ForceText)
  3798. {
  3799. CopyParam.TransferMode = tmAscii;
  3800. }
  3801. // so i do not need to worry if masking algorithm works in all cases
  3802. // ("" means "copy file name", no masking is actually done)
  3803. if (ExtractFileName(FileName) == Data->OriginalFileName)
  3804. {
  3805. CopyParam.FileMask = L"";
  3806. }
  3807. else
  3808. {
  3809. CopyParam.FileMask = DelimitFileNameMask(Data->OriginalFileName);
  3810. }
  3811. int Params = cpNoConfirmation | cpTemporary;
  3812. if (Data->Terminal->IsCapable[fcBackgroundTransfers])
  3813. {
  3814. TTerminalQueue * AQueue = Manager->FindQueueForTerminal(Data->Terminal);
  3815. TQueueItem * QueueItem =
  3816. new TEditorUploadQueueItem(Data->Terminal, FileList, Data->RemoteDirectory, &CopyParam, Params);
  3817. QueueItem->CompleteEvent = UploadCompleteEvent;
  3818. AddQueueItem(AQueue, QueueItem, Data->Terminal);
  3819. }
  3820. else
  3821. {
  3822. if (NonVisualDataModule->Busy)
  3823. {
  3824. Retry = true;
  3825. }
  3826. else
  3827. {
  3828. Data->Terminal->CopyToRemote(FileList, Data->RemoteDirectory, &CopyParam, Params, NULL);
  3829. SetEvent(UploadCompleteEvent);
  3830. }
  3831. }
  3832. }
  3833. __finally
  3834. {
  3835. delete FileList;
  3836. }
  3837. }
  3838. }
  3839. //---------------------------------------------------------------------------
  3840. void __fastcall TCustomScpExplorerForm::ExecutedFileReload(
  3841. const UnicodeString & FileName, TEditedFileData * Data)
  3842. {
  3843. // Sanity check, we should not be busy otherwise user would not be able to click Reload button.
  3844. DebugAssert(!NonVisualDataModule->Busy);
  3845. if (!IsActiveTerminal(Data->Terminal))
  3846. {
  3847. throw Exception(FMTLOAD(EDIT_SESSION_CLOSED_RELOAD,
  3848. (ExtractFileName(FileName), Data->SessionName)));
  3849. }
  3850. TManagedTerminal * PrevSession = TTerminalManager::Instance()->ActiveSession;
  3851. TTerminalManager::Instance()->ActiveSession = Data->Terminal;
  3852. NonVisualDataModule->StartBusy();
  3853. try
  3854. {
  3855. std::unique_ptr<TRemoteFile> File;
  3856. UnicodeString RemoteFileName =
  3857. UnixIncludeTrailingBackslash(Data->RemoteDirectory) + Data->OriginalFileName;
  3858. Terminal->ExceptionOnFail = true;
  3859. try
  3860. {
  3861. File.reset(Terminal->ReadFile(RemoteFileName));
  3862. if (!File->HaveFullFileName)
  3863. {
  3864. File->FullFileName = RemoteFileName;
  3865. }
  3866. }
  3867. __finally
  3868. {
  3869. Terminal->ExceptionOnFail = false;
  3870. }
  3871. std::unique_ptr<TStrings> FileList(new TStringList());
  3872. FileList->AddObject(RemoteFileName, File.get());
  3873. UnicodeString RootTempDir = Data->LocalRootDirectory;
  3874. UnicodeString TempDir = ExtractFilePath(FileName);
  3875. TemporarilyDownloadFiles(FileList.get(), Data->ForceText, RootTempDir, TempDir, true, true, false);
  3876. if (EditorCheckNotModified(Data))
  3877. {
  3878. Data->SourceTimestamp = File->Modification;
  3879. }
  3880. // sanity check, the target file name should be still the same
  3881. DebugAssert(ExtractFileName(FileName) == FileList->Strings[0]);
  3882. }
  3883. __finally
  3884. {
  3885. NonVisualDataModule->EndBusy();
  3886. // it actually may not exist anymore...
  3887. TTerminalManager::Instance()->ActiveSession = PrevSession;
  3888. }
  3889. }
  3890. //---------------------------------------------------------------------------
  3891. void __fastcall TCustomScpExplorerForm::ExecutedFileEarlyClosed(
  3892. const TEditedFileData * Data, bool & KeepOpen)
  3893. {
  3894. // Command is set for external editors only (not for "shell" open).
  3895. if (!Data->Command.IsEmpty())
  3896. {
  3897. bool AnyFound = false;
  3898. bool AnyMDI = false;
  3899. bool AnyNonMDI = false;
  3900. bool AnyDetect = false;
  3901. TEditorList * EditorList = new TEditorList();
  3902. try
  3903. {
  3904. *EditorList = *WinConfiguration->EditorList;
  3905. for (int i = 0; i < EditorList->Count; i++)
  3906. {
  3907. const TEditorPreferences * Editor = EditorList->Editors[i];
  3908. if ((Editor->Data->Editor == edExternal) &&
  3909. (Editor->Data->ExternalEditor == Data->Command))
  3910. {
  3911. AnyFound = true;
  3912. if (Editor->Data->SDIExternalEditor)
  3913. {
  3914. AnyNonMDI = true;
  3915. if (Editor->Data->DetectMDIExternalEditor)
  3916. {
  3917. AnyDetect = true;
  3918. }
  3919. }
  3920. else
  3921. {
  3922. AnyMDI = true;
  3923. }
  3924. }
  3925. }
  3926. bool EnableMDI = false;
  3927. bool DisableDetect = false;
  3928. if (AnyMDI)
  3929. {
  3930. KeepOpen = true;
  3931. if (AnyNonMDI)
  3932. {
  3933. // there is at least one instance of the editor with MDI support enabled,
  3934. // and one with disabled, enable it for all instances
  3935. EnableMDI = true;
  3936. }
  3937. }
  3938. else if (AnyFound && !AnyDetect)
  3939. {
  3940. // at least once instance found but all have MDI autodetection disabled
  3941. // => close the file (default action)
  3942. }
  3943. else
  3944. {
  3945. // no instance of the editor has MDI support enabled
  3946. TMessageParams Params;
  3947. if (AnyFound)
  3948. {
  3949. // there is at least one instance of the editor
  3950. Params.Params |= mpNeverAskAgainCheck;
  3951. }
  3952. unsigned int Answer = MessageDialog(FMTLOAD(EDITOR_EARLY_CLOSED2, (Data->OriginalFileName)), qtWarning,
  3953. qaYes | qaNo, HELP_EDITOR_EARLY_CLOSED, &Params);
  3954. switch (Answer)
  3955. {
  3956. case qaNeverAskAgain:
  3957. DisableDetect = true;
  3958. break;
  3959. case qaNo:
  3960. EnableMDI = true;
  3961. KeepOpen = true;
  3962. break;
  3963. }
  3964. }
  3965. if (AnyFound && (EnableMDI || DisableDetect))
  3966. {
  3967. bool Changed = false;
  3968. for (int i = 0; i < EditorList->Count; i++)
  3969. {
  3970. const TEditorPreferences * Editor = EditorList->Editors[i];
  3971. if ((Editor->Data->Editor == edExternal) &&
  3972. (Editor->Data->ExternalEditor == Data->Command) &&
  3973. ((EnableMDI && Editor->Data->SDIExternalEditor) ||
  3974. (DisableDetect && Editor->Data->DetectMDIExternalEditor)))
  3975. {
  3976. Changed = true;
  3977. TEditorPreferences * UpdatedEditor = new TEditorPreferences(*Editor);
  3978. if (EnableMDI)
  3979. {
  3980. UpdatedEditor->GetData()->SDIExternalEditor = false;
  3981. }
  3982. if (DisableDetect)
  3983. {
  3984. UpdatedEditor->GetData()->DetectMDIExternalEditor = false;
  3985. }
  3986. EditorList->Change(i, UpdatedEditor);
  3987. }
  3988. }
  3989. if (Changed)
  3990. {
  3991. WinConfiguration->EditorList = EditorList;
  3992. }
  3993. }
  3994. }
  3995. __finally
  3996. {
  3997. delete EditorList;
  3998. }
  3999. }
  4000. else
  4001. {
  4002. // "open" case
  4003. MessageDialog(FMTLOAD(APP_EARLY_CLOSED, (Data->OriginalFileName)), qtWarning,
  4004. qaOK, HELP_APP_EARLY_CLOSED);
  4005. }
  4006. }
  4007. //---------------------------------------------------------------------------
  4008. void __fastcall TCustomScpExplorerForm::ExecutedFileUploadComplete(TObject * Sender)
  4009. {
  4010. EditorFormFileUploadComplete(DebugNotNull(dynamic_cast<TForm *>(Sender)));
  4011. }
  4012. //---------------------------------------------------------------------------
  4013. void __fastcall TCustomScpExplorerForm::RemoteDirViewEnter(TObject * /*Sender*/)
  4014. {
  4015. SideEnter(osRemote);
  4016. }
  4017. //---------------------------------------------------------------------------
  4018. void __fastcall TCustomScpExplorerForm::RemoteDriveViewEnter(TObject * /*Sender*/)
  4019. {
  4020. MakeNextInTabOrder(RemoteDirPanel, RemoteDrivePanel);
  4021. SideEnter(osRemote);
  4022. }
  4023. //---------------------------------------------------------------------------
  4024. void __fastcall TCustomScpExplorerForm::SideEnter(TOperationSide Side)
  4025. {
  4026. FCurrentSide = Side;
  4027. if (Visible)
  4028. {
  4029. UpdateControls();
  4030. }
  4031. }
  4032. //---------------------------------------------------------------------------
  4033. void __fastcall TCustomScpExplorerForm::FileDeleted(TOperationSide Side, const UnicodeString & FileName, bool Success)
  4034. {
  4035. VisualiseOperationFinished(Side, FileName, Success);
  4036. if (DebugAlwaysTrue(FDeletedFiles != NULL) && Success)
  4037. {
  4038. FDeletedFiles->Add(FileName);
  4039. }
  4040. }
  4041. //---------------------------------------------------------------------------
  4042. void __fastcall TCustomScpExplorerForm::DeleteFiles(TOperationSide Side,
  4043. TStrings * FileList, bool Alternative)
  4044. {
  4045. TCustomDirView * DView = DirView(Side);
  4046. DView->SaveSelection();
  4047. DView->SaveSelectedNames();
  4048. DebugAssert(!FAlternativeDelete);
  4049. FAlternativeDelete = Alternative;
  4050. try
  4051. {
  4052. if (!IsSideLocalBrowser(Side))
  4053. {
  4054. DebugAssert(Terminal != NULL);
  4055. // Clone the file list as it may refer to current directory files, which get destroyed, when the directory is reloaded after the operation
  4056. std::unique_ptr<TStrings> PermanentFileList(TRemoteFileList::CloneStrings(FileList));
  4057. std::unique_ptr<TStringList> DeletedFiles(new TStringList());
  4058. DeletedFiles->CaseSensitive = DebugAlwaysTrue(!IsSideLocalBrowser(Side));
  4059. int Params = FLAGMASK(Alternative, dfAlternative);
  4060. try
  4061. {
  4062. DebugAssert(FDeletedFiles == NULL);
  4063. TValueRestorer<TStrings *> DeletedFilesRestorer(FDeletedFiles, DeletedFiles.get());
  4064. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  4065. FOnFileOperationFinished = FileDeleted;
  4066. FMoveToQueue = false;
  4067. Terminal->DeleteFiles(FileList, Params);
  4068. // Probably not needed for deleting, just for consistency with transfer code
  4069. if (FMoveToQueue)
  4070. {
  4071. Abort();
  4072. }
  4073. }
  4074. catch (EAbort &)
  4075. {
  4076. if (FMoveToQueue)
  4077. {
  4078. DeletedFiles->Sorted = true;
  4079. for (int Index = 0; Index < PermanentFileList->Count; Index++)
  4080. {
  4081. if (DeletedFiles->IndexOf(PermanentFileList->Strings[Index]) >= 0)
  4082. {
  4083. // We should always be deleting the first item => what can be used to optimize this code, if needed
  4084. DebugAssert(Index == 0);
  4085. PermanentFileList->Delete(Index);
  4086. Index--;
  4087. }
  4088. }
  4089. Configuration->Usage->Inc("MovesToBackgroundDelete");
  4090. TQueueItem * QueueItem = new TDeleteQueueItem(Terminal, PermanentFileList.get(), Params);
  4091. AddQueueItem(Queue, QueueItem, Terminal);
  4092. ClearOperationSelection(osRemote);
  4093. }
  4094. }
  4095. }
  4096. else
  4097. {
  4098. if (IsLocalBrowserMode())
  4099. {
  4100. Configuration->Usage->Inc(L"LocalLocalDeletes");
  4101. }
  4102. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, FCurrentSide);
  4103. try
  4104. {
  4105. TTerminalManager::Instance()->LocalTerminal->DeleteLocalFiles(FileList, FLAGMASK(Alternative, dfAlternative));
  4106. }
  4107. __finally
  4108. {
  4109. ReloadLocalDirectory();
  4110. }
  4111. }
  4112. FAlternativeDelete = false;
  4113. }
  4114. catch(...)
  4115. {
  4116. FAlternativeDelete = false;
  4117. DView->DiscardSavedSelection();
  4118. throw;
  4119. }
  4120. DView->RestoreSelection();
  4121. }
  4122. //---------------------------------------------------------------------------
  4123. void __fastcall TCustomScpExplorerForm::LockFiles(TStrings * FileList, bool Lock)
  4124. {
  4125. DebugAssert(Terminal);
  4126. DebugAssert(!IsLocalBrowserMode());
  4127. RemoteDirView->SaveSelection();
  4128. RemoteDirView->SaveSelectedNames();
  4129. try
  4130. {
  4131. if (Lock)
  4132. {
  4133. Terminal->LockFiles(FileList);
  4134. }
  4135. else
  4136. {
  4137. Terminal->UnlockFiles(FileList);
  4138. }
  4139. }
  4140. catch(...)
  4141. {
  4142. RemoteDirView->DiscardSavedSelection();
  4143. throw;
  4144. }
  4145. RemoteDirView->RestoreSelection();
  4146. }
  4147. //---------------------------------------------------------------------------
  4148. bool TCustomScpExplorerForm::DoDirectoryExists(void * Session, const UnicodeString & Directory)
  4149. {
  4150. bool Result = false;
  4151. TTerminal * ATerminal = (Session == NULL) ? Terminal : reinterpret_cast<TTerminal *>(Session);
  4152. if (IsActiveTerminal(ATerminal))
  4153. {
  4154. std::unique_ptr<TRemoteFile> File(ATerminal->TryReadFile(Directory));
  4155. Result = File && File->IsDirectory;
  4156. }
  4157. return Result;
  4158. }
  4159. //---------------------------------------------------------------------------
  4160. bool TCustomScpExplorerForm::NeedSecondarySessionForRemoteCopy(TStrings * FileList)
  4161. {
  4162. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4163. return
  4164. !Terminal->IsCapable[fcRemoteCopy] ||
  4165. (CopyDirsOnSecondarySession && TRemoteFileList::AnyDirectory(FileList));
  4166. }
  4167. //---------------------------------------------------------------------------
  4168. bool __fastcall TCustomScpExplorerForm::RemoteTransferDialog(TManagedTerminal *& Session,
  4169. TStrings * FileList, UnicodeString & Target, UnicodeString & FileMask, bool & DirectCopy,
  4170. bool NoConfirmation, bool Move)
  4171. {
  4172. DebugAssert(Terminal != NULL);
  4173. DebugAssert(Terminal == TTerminalManager::Instance()->ActiveTerminal);
  4174. DebugAssert(!IsLocalBrowserMode());
  4175. if (Session == NULL)
  4176. {
  4177. Session = Terminal;
  4178. }
  4179. bool TargetConfirmed = false;
  4180. if (Session == Terminal)
  4181. {
  4182. if (RemoteDriveView->DropTarget != NULL)
  4183. {
  4184. Target = RemoteDriveView->NodePathName(RemoteDriveView->DropTarget);
  4185. TargetConfirmed = true;
  4186. }
  4187. else if (RemoteDirView->DropTarget != NULL)
  4188. {
  4189. DebugAssert(RemoteDirView->ItemIsDirectory(RemoteDirView->DropTarget));
  4190. Target = RemoteDirView->ItemFullFileName(RemoteDirView->DropTarget);
  4191. TargetConfirmed = true;
  4192. }
  4193. else
  4194. {
  4195. Target = RemoteDirView->Path;
  4196. }
  4197. }
  4198. else
  4199. {
  4200. Target = GetSessionPath(Session, osRemote);
  4201. }
  4202. Target = UnixIncludeTrailingBackslash(Target);
  4203. if (FileList->Count == 1)
  4204. {
  4205. FileMask = DelimitFileNameMask(UnixExtractFileName(FileList->Strings[0]));
  4206. }
  4207. else
  4208. {
  4209. FileMask = AnyMask;
  4210. }
  4211. DirectCopy = Terminal->IsCapable[fcRemoteCopy] || Terminal->IsCapable[fcSecondaryShell];
  4212. bool Result = true;
  4213. if (!NoConfirmation)
  4214. {
  4215. bool Multi = (FileList->Count > 1);
  4216. if (Move)
  4217. {
  4218. Result = DoRemoteMoveDialog(Multi, Target, FileMask, DoDirectoryExists);
  4219. }
  4220. else
  4221. {
  4222. std::unique_ptr<TStrings> Sessions(new TStringList);
  4223. std::unique_ptr<TStrings> Directories(new TStringList);
  4224. TStrings * SessionList = TTerminalManager::Instance()->SessionList;
  4225. for (int Index = 0; Index < SessionList->Count; Index++)
  4226. {
  4227. TManagedTerminal * ASession = DebugNotNull(dynamic_cast<TManagedTerminal *>(SessionList->Objects[Index]));
  4228. if (IsActiveTerminal(ASession) && DebugAlwaysTrue(!ASession->LocalBrowser))
  4229. {
  4230. Sessions->AddObject(SessionList->Strings[Index], ASession);
  4231. Directories->Add(GetSessionPath(ASession, osRemote));
  4232. }
  4233. }
  4234. bool AnyDirectory = false;
  4235. bool CopyDirsOnSecondarySession = Terminal->IsCapable[fcSecondaryShell];
  4236. if (CopyDirsOnSecondarySession && !Terminal->CommandSessionOpened) // optimization
  4237. {
  4238. for (int Index = 0; !AnyDirectory && (Index < FileList->Count); Index++)
  4239. {
  4240. AnyDirectory = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]))->IsDirectory;
  4241. }
  4242. }
  4243. TDirectRemoteCopy AllowDirectCopy;
  4244. if (Terminal->CommandSessionOpened || !NeedSecondarySessionForRemoteCopy(FileList))
  4245. {
  4246. DebugAssert(DirectCopy);
  4247. AllowDirectCopy = drcAllow;
  4248. }
  4249. else if (Terminal->IsCapable[fcSecondaryShell])
  4250. {
  4251. DebugAssert(DirectCopy);
  4252. AllowDirectCopy = Terminal->IsCapable[fcRemoteCopy] ? drcConfirmCommandSessionDirs : drcConfirmCommandSession;
  4253. }
  4254. else
  4255. {
  4256. DebugAssert(!DirectCopy);
  4257. AllowDirectCopy = drcDisallow;
  4258. }
  4259. void * ASession = Session;
  4260. Result = DoRemoteCopyDialog(
  4261. Sessions.get(), Directories.get(), AllowDirectCopy, Multi, ASession, Target, FileMask, DirectCopy, Terminal,
  4262. DoDirectoryExists, TargetConfirmed);
  4263. Session = static_cast<TManagedTerminal *>(ASession);
  4264. }
  4265. }
  4266. return Result;
  4267. }
  4268. //---------------------------------------------------------------------------
  4269. bool __fastcall TCustomScpExplorerForm::RemoteTransferFiles(
  4270. TStrings * FileList, bool NoConfirmation, bool Move, TManagedTerminal * Session)
  4271. {
  4272. DebugAssert(!IsLocalBrowserMode());
  4273. bool DirectCopy;
  4274. UnicodeString Target, FileMask;
  4275. bool Result = RemoteTransferDialog(Session, FileList, Target, FileMask, DirectCopy, NoConfirmation, Move);
  4276. if (Result)
  4277. {
  4278. if (!Move && !DirectCopy)
  4279. {
  4280. Configuration->Usage->Inc("RemoteCopyTemp");
  4281. UnicodeString RootTempDir;
  4282. UnicodeString TempDir;
  4283. TemporarilyDownloadFiles(FileList, false, RootTempDir, TempDir, false, false, true);
  4284. TStrings * TemporaryFilesList = new TStringList();
  4285. try
  4286. {
  4287. TMakeLocalFileListParams MakeFileListParam;
  4288. MakeFileListParam.FileList = TemporaryFilesList;
  4289. MakeFileListParam.FileTimes = NULL;
  4290. MakeFileListParam.IncludeDirs = true;
  4291. MakeFileListParam.Recursive = false;
  4292. ProcessLocalDirectory(TempDir, Terminal->MakeLocalFileList, &MakeFileListParam);
  4293. TTerminalManager::Instance()->ActiveSession = Session;
  4294. if (TemporaryFilesList->Count > 0)
  4295. {
  4296. TGUICopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  4297. CopyParam.FileMask = FileMask;
  4298. DebugAssert(!FAutoOperation);
  4299. FAutoOperation = true;
  4300. Terminal->CopyToRemote(TemporaryFilesList, Target, &CopyParam, cpTemporary, NULL);
  4301. }
  4302. }
  4303. __finally
  4304. {
  4305. delete TemporaryFilesList;
  4306. FAutoOperation = false;
  4307. if (!RootTempDir.IsEmpty())
  4308. {
  4309. RecursiveDeleteFile(ExcludeTrailingBackslash(RootTempDir));
  4310. }
  4311. }
  4312. }
  4313. else
  4314. {
  4315. RemoteDirView->SaveSelection();
  4316. RemoteDirView->SaveSelectedNames();
  4317. try
  4318. {
  4319. if (Move)
  4320. {
  4321. Configuration->Usage->Inc("RemoteMove");
  4322. Terminal->MoveFiles(FileList, Target, FileMask, false);
  4323. }
  4324. else
  4325. {
  4326. Configuration->Usage->Inc("RemoteCopyDirect");
  4327. DebugAssert(DirectCopy);
  4328. DebugAssert(Session == Terminal);
  4329. if (!NeedSecondarySessionForRemoteCopy(FileList) ||
  4330. Terminal->CommandSessionOpened ||
  4331. CommandSessionFallback())
  4332. {
  4333. Terminal->CopyFiles(FileList, Target, FileMask, false);
  4334. }
  4335. }
  4336. }
  4337. catch(...)
  4338. {
  4339. RemoteDirView->DiscardSavedSelection();
  4340. throw;
  4341. }
  4342. RemoteDirView->RestoreSelection();
  4343. }
  4344. }
  4345. return Result;
  4346. }
  4347. //---------------------------------------------------------------------------
  4348. void __fastcall TCustomScpExplorerForm::CreateRemoteDirectory(
  4349. const UnicodeString & Path, TRemoteProperties & Properties)
  4350. {
  4351. DebugAssert(!IsLocalBrowserMode());
  4352. Properties.Valid = Properties.Valid << vpEncrypt;
  4353. Properties.Encrypt = GUIConfiguration->CurrentCopyParam.EncryptNewFiles;
  4354. RemoteDirView->CreateDirectoryEx(Path, &Properties);
  4355. }
  4356. //---------------------------------------------------------------------------
  4357. void __fastcall TCustomScpExplorerForm::CreateDirectory(TOperationSide Side)
  4358. {
  4359. Side = GetSide(Side);
  4360. TRemoteProperties Properties = GUIConfiguration->NewDirectoryProperties;
  4361. TRemoteProperties * AProperties = (!IsSideLocalBrowser(Side) ? &Properties : NULL);
  4362. UnicodeString Name = LoadStr(NEW_FOLDER);
  4363. int AllowedChanges =
  4364. FLAGMASK(!IsSideLocalBrowser(Side) && Terminal->IsCapable[fcModeChanging], cpMode);
  4365. bool SaveSettings = false;
  4366. if (DoCreateDirectoryDialog(Name, AProperties, AllowedChanges, SaveSettings))
  4367. {
  4368. TWindowLock Lock(this);
  4369. if (!IsSideLocalBrowser(Side))
  4370. {
  4371. if (SaveSettings)
  4372. {
  4373. GUIConfiguration->NewDirectoryProperties = Properties;
  4374. }
  4375. CreateRemoteDirectory(Name, Properties);
  4376. }
  4377. else
  4378. {
  4379. DirView(Side)->CreateDirectory(Name);
  4380. }
  4381. }
  4382. }
  4383. //---------------------------------------------------------------------------
  4384. void __fastcall TCustomScpExplorerForm::HomeDirectory(TOperationSide Side)
  4385. {
  4386. TWindowLock Lock(this);
  4387. DirView(Side)->ExecuteHomeDirectory();
  4388. }
  4389. //---------------------------------------------------------------------------
  4390. void __fastcall TCustomScpExplorerForm::OpenDirectory(TOperationSide Side)
  4391. {
  4392. DoOpenDirectoryDialog(odBrowse, Side);
  4393. }
  4394. //---------------------------------------------------------------------------
  4395. bool __fastcall TCustomScpExplorerForm::OpenBookmark(TOperationSide Side, TBookmark * Bookmark)
  4396. {
  4397. TOperationSide BookmarkSide = IsLocalBrowserMode() ? osLocal : Side;
  4398. UnicodeString Path = Bookmark->GetSideDirectory(BookmarkSide);
  4399. bool Result = !Path.IsEmpty();
  4400. if (Result)
  4401. {
  4402. TryOpenDirectory(Side, Path);
  4403. }
  4404. return Result;
  4405. }
  4406. //---------------------------------------------------------------------------
  4407. void __fastcall TCustomScpExplorerForm::CalculateSize(
  4408. TStrings * FileList, __int64 & Size, TCalculateSizeStats & Stats,
  4409. bool & Close)
  4410. {
  4411. // terminal can be already closed (e.g. dropped connection)
  4412. if (Terminal != NULL)
  4413. {
  4414. try
  4415. {
  4416. TCalculateSizeParams Params;
  4417. Params.Stats = &Stats;
  4418. Terminal->CalculateFilesSize(FileList, Size, Params);
  4419. }
  4420. catch(...)
  4421. {
  4422. if (!Terminal->Active)
  4423. {
  4424. Close = true;
  4425. }
  4426. throw;
  4427. }
  4428. }
  4429. }
  4430. //---------------------------------------------------------------------------
  4431. void __fastcall TCustomScpExplorerForm::CalculateChecksum(const UnicodeString & Alg,
  4432. TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  4433. bool & Close)
  4434. {
  4435. if ((Terminal != NULL) && // terminal can be already closed (e.g. dropped connection)
  4436. EnsureCommandSessionFallback(fcCalculatingChecksum))
  4437. {
  4438. Configuration->Usage->Inc(L"ChecksumCalculated");
  4439. try
  4440. {
  4441. Terminal->CalculateFilesChecksum(Alg, FileList, OnCalculatedChecksum);
  4442. }
  4443. catch(...)
  4444. {
  4445. if (!Terminal->Active)
  4446. {
  4447. Close = true;
  4448. }
  4449. throw;
  4450. }
  4451. }
  4452. }
  4453. //---------------------------------------------------------------------------
  4454. void TCustomScpExplorerForm::LoadFilesProperties(TStrings * FileList)
  4455. {
  4456. if (Terminal->LoadFilesProperties(FileList))
  4457. {
  4458. RemoteDirView->Invalidate();
  4459. }
  4460. }
  4461. //---------------------------------------------------------------------------
  4462. bool TCustomScpExplorerForm::CanCalculateChecksum()
  4463. {
  4464. return
  4465. Terminal->IsCapable[fcCalculatingChecksum] ||
  4466. (Terminal->IsCapable[fcSecondaryShell] && !Terminal->IsEncryptingFiles());
  4467. }
  4468. //---------------------------------------------------------------------------
  4469. bool __fastcall TCustomScpExplorerForm::SetProperties(TOperationSide Side, TStrings * FileList)
  4470. {
  4471. bool Result;
  4472. if (!IsSideLocalBrowser(Side))
  4473. {
  4474. TRemoteTokenList * GroupList = NULL;
  4475. TRemoteTokenList * UserList = NULL;
  4476. try
  4477. {
  4478. TRemoteProperties CurrentProperties;
  4479. LoadFilesProperties(FileList);
  4480. bool CapableGroupChanging = Terminal->IsCapable[fcGroupChanging];
  4481. bool CapableOwnerChanging = Terminal->IsCapable[fcOwnerChanging];
  4482. if (CapableGroupChanging || CapableOwnerChanging)
  4483. {
  4484. if (CapableGroupChanging)
  4485. {
  4486. GroupList = Terminal->Groups->Duplicate();
  4487. }
  4488. if (CapableOwnerChanging)
  4489. {
  4490. UserList = Terminal->Users->Duplicate();
  4491. }
  4492. TRemoteDirectory * Files = Terminal->Files;
  4493. int Count = Files->Count;
  4494. if (Count > 100)
  4495. {
  4496. Count = 100;
  4497. }
  4498. for (int Index = 0; Index < Count; Index++)
  4499. {
  4500. TRemoteFile * File = Files->Files[Index];
  4501. if (CapableGroupChanging)
  4502. {
  4503. GroupList->AddUnique(File->Group);
  4504. }
  4505. if (CapableOwnerChanging)
  4506. {
  4507. UserList->AddUnique(File->Owner);
  4508. }
  4509. }
  4510. // if we haven't collected tokens for all files in current directory,
  4511. // make sure we collect them at least for all selected files.
  4512. // (note that so far the files in FileList has to be from current direcotry)
  4513. if (Count < Files->Count)
  4514. {
  4515. for (int Index = 0; Index < FileList->Count; Index++)
  4516. {
  4517. TRemoteFile * File = (TRemoteFile *)(FileList->Objects[Index]);
  4518. if (CapableGroupChanging)
  4519. {
  4520. GroupList->AddUnique(File->Group);
  4521. }
  4522. if (CapableOwnerChanging)
  4523. {
  4524. UserList->AddUnique(File->Owner);
  4525. }
  4526. }
  4527. }
  4528. }
  4529. CurrentProperties = TRemoteProperties::CommonProperties(FileList);
  4530. bool CapableAclChanging = Terminal->IsCapable[fcAclChangingFiles];
  4531. if (CapableAclChanging && TRemoteFileList::AnyDirectory(FileList))
  4532. {
  4533. CapableAclChanging = false;
  4534. CurrentProperties.Valid = CurrentProperties.Valid >> vpRights;
  4535. }
  4536. int Flags = 0;
  4537. if (Terminal->IsCapable[fcModeChanging]) Flags |= cpMode;
  4538. if (CapableAclChanging) Flags |= cpAcl;
  4539. if (CapableOwnerChanging) Flags |= cpOwner;
  4540. if (CapableGroupChanging) Flags |= cpGroup;
  4541. TCalculateChecksumEvent CalculateChecksumEvent = NULL;
  4542. if (CanCalculateChecksum())
  4543. {
  4544. CalculateChecksumEvent = CalculateChecksum;
  4545. }
  4546. std::unique_ptr<TStrings> ChecksumAlgs(new TStringList());
  4547. Terminal->GetSupportedChecksumAlgs(ChecksumAlgs.get());
  4548. TRemoteProperties NewProperties = CurrentProperties;
  4549. Result =
  4550. DoPropertiesDialog(FileList, RemoteDirView->PathName,
  4551. GroupList, UserList, ChecksumAlgs.get(), &NewProperties, Flags,
  4552. Terminal->IsCapable[fcGroupOwnerChangingByID],
  4553. CalculateSize, CalculateChecksumEvent);
  4554. if (Result)
  4555. {
  4556. NewProperties = TRemoteProperties::ChangedProperties(CurrentProperties, NewProperties);
  4557. Terminal->ChangeFilesProperties(FileList, &NewProperties);
  4558. }
  4559. }
  4560. __finally
  4561. {
  4562. delete GroupList;
  4563. delete UserList;
  4564. }
  4565. }
  4566. else
  4567. {
  4568. DirView(Side)->DisplayPropertiesMenu();
  4569. Result = true;
  4570. }
  4571. return Result;
  4572. }
  4573. //---------------------------------------------------------------------------
  4574. void __fastcall TCustomScpExplorerForm::KeyProcessed(Word & Key, TShiftState Shift)
  4575. {
  4576. if (Shift * AllKeyShiftStates() == (TShiftState() << ssAlt))
  4577. {
  4578. FIgnoreNextDialogChar = Key;
  4579. }
  4580. Key = 0;
  4581. }
  4582. //---------------------------------------------------------------------------
  4583. void __fastcall TCustomScpExplorerForm::CheckCustomCommandShortCut(
  4584. TCustomCommandList * List, Word & Key, Classes::TShiftState Shift, TShortCut KeyShortCut)
  4585. {
  4586. const TCustomCommandType * Command = List->Find(KeyShortCut);
  4587. if (Command != NULL)
  4588. {
  4589. KeyProcessed(Key, Shift);
  4590. if (CustomCommandState(*Command, false, ccltAll) > 0)
  4591. {
  4592. TAutoFlag DontCopyCommandToClipboardFlag(DontCopyCommandToClipboard);
  4593. ExecuteFileOperationCommand(foCustomCommand, osRemote,
  4594. false, false, const_cast<TCustomCommandType *>(Command));
  4595. }
  4596. }
  4597. }
  4598. //---------------------------------------------------------------------------
  4599. void __fastcall TCustomScpExplorerForm::KeyDown(Word & Key, Classes::TShiftState Shift)
  4600. {
  4601. if (!NonVisualDataModule->Busy)
  4602. {
  4603. if (QueueView3->Focused() && (QueueView3->OnKeyDown != NULL))
  4604. {
  4605. QueueView3->OnKeyDown(QueueView3, Key, Shift);
  4606. }
  4607. if ((Key != 0) && !DirView(osCurrent)->IsEditing())
  4608. {
  4609. TShortCut KeyShortCut = ShortCut(Key, Shift);
  4610. for (int Index = 0; Index < NonVisualDataModule->ExplorerActions->ActionCount; Index++)
  4611. {
  4612. // Note that handling shortcuts on panel (current control) popup menu has precendence over this.
  4613. // But so far it's not a problem, as it does what we want.
  4614. TAction * Action = (TAction *)NonVisualDataModule->ExplorerActions->Actions[Index];
  4615. if (((Action->ShortCut == KeyShortCut) ||
  4616. (Action->SecondaryShortCuts->IndexOfShortCut(KeyShortCut) >= 0)) &&
  4617. AllowedAction(Action, aaShortCut))
  4618. {
  4619. // Has to be called before the action as the dialog char is already in queue.
  4620. // So when the action consumes message queue, we already need to have the
  4621. // FIgnoreNextDialogChar set
  4622. KeyProcessed(Key, Shift);
  4623. // Reset reference to previous component (when menu/toolbar was clicked).
  4624. // Needed to detect that action was invoked by keyboard shortcut
  4625. // in TNonVisualDataModule::ExplorerActionsExecute
  4626. Action->ActionComponent = NULL;
  4627. Action->Execute();
  4628. return;
  4629. }
  4630. }
  4631. for (int i = 0; i < TTerminalManager::Instance()->Count; i++)
  4632. {
  4633. if (NonVisualDataModule->OpenSessionShortCut(i) == KeyShortCut)
  4634. {
  4635. KeyProcessed(Key, Shift);
  4636. TTerminalManager::Instance()->ActiveSessionIndex = i;
  4637. return;
  4638. }
  4639. }
  4640. if (Key == VK_TAB && Shift.Contains(ssCtrl))
  4641. {
  4642. KeyProcessed(Key, Shift);
  4643. TTerminalManager::Instance()->CycleTerminals(!Shift.Contains(ssShift));
  4644. }
  4645. TShortCut CustomShortCut = NormalizeCustomShortCut(KeyShortCut);
  4646. if (IsCustomShortCut(CustomShortCut))
  4647. {
  4648. CheckCustomCommandShortCut(WinConfiguration->CustomCommandList, Key, Shift, CustomShortCut);
  4649. CheckCustomCommandShortCut(WinConfiguration->ExtensionList, Key, Shift, CustomShortCut);
  4650. if (WinConfiguration->SharedBookmarks != NULL)
  4651. {
  4652. TBookmark * Bookmark = WinConfiguration->SharedBookmarks->FindByShortCut(CustomShortCut);
  4653. if ((Bookmark != NULL) &&
  4654. OpenBookmark(FCurrentSide, Bookmark))
  4655. {
  4656. KeyProcessed(Key, Shift);
  4657. }
  4658. }
  4659. }
  4660. }
  4661. }
  4662. TForm::KeyDown(Key, Shift);
  4663. }
  4664. //---------------------------------------------------------------------------
  4665. void __fastcall TCustomScpExplorerForm::InitStatusBar()
  4666. {
  4667. bool OpenedTerminal = false;
  4668. UnicodeString ProtocolName;
  4669. UnicodeString ProtocolNameHint;
  4670. UnicodeString SecurityProtocolName;
  4671. UnicodeString DurationHint;
  4672. // See the comment in TScpCommanderForm::UpdateControls()
  4673. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4674. if (ActiveTerminal != NULL)
  4675. {
  4676. // Active is not enough here
  4677. if (ActiveTerminal->Status == ssOpened)
  4678. {
  4679. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4680. const TFileSystemInfo & FileSystemInfo = ActiveTerminal->GetFileSystemInfo();
  4681. if (FileSystemInfo.ProtocolName.IsEmpty())
  4682. {
  4683. ProtocolName = SessionInfo.ProtocolName;
  4684. }
  4685. else
  4686. {
  4687. ProtocolName = FileSystemInfo.ProtocolName;
  4688. }
  4689. ProtocolNameHint = LoadStr(STATUS_PROTOCOL_HINT);
  4690. SecurityProtocolName = SessionInfo.SecurityProtocolName;
  4691. DurationHint = LoadStr(STATUS_DURATION_HINT);
  4692. OpenedTerminal = true;
  4693. }
  4694. else if (ActiveTerminal->Status > ssClosed)
  4695. {
  4696. ProtocolName = LoadStr(STATUS_CONNECTING);
  4697. }
  4698. else
  4699. {
  4700. ProtocolName = LoadStr(STATUS_NOT_CONNECTED2);
  4701. }
  4702. }
  4703. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4704. int Offset = SessionStatusBar->Panels->Count - SessionPanelCount;
  4705. TTBXStatusPanel * ProtocolStatusPanel = SessionStatusBar->Panels->Items[Offset + 0];
  4706. ProtocolStatusPanel->ViewPriority = (ActiveTerminal != NULL) ? 100 : 0;
  4707. if (ProtocolStatusPanel->Caption != ProtocolName)
  4708. {
  4709. ProtocolStatusPanel->Caption = ProtocolName;
  4710. std::unique_ptr<TCanvas> Canvas(CreateControlCanvas(SessionStatusBar));
  4711. ProtocolStatusPanel->Size = Canvas->TextWidth(ProtocolName) + ScaleByTextHeight(SessionStatusBar, 32);
  4712. }
  4713. ProtocolStatusPanel->Hint = ProtocolNameHint;
  4714. TTBXStatusPanel * SecurityStatusPanel = SessionStatusBar->Panels->Items[Offset + 1];
  4715. SecurityStatusPanel->ViewPriority = OpenedTerminal ? 98 : 0;
  4716. bool SecurityEnabled = !SecurityProtocolName.IsEmpty();
  4717. SecurityStatusPanel->Enabled = SecurityEnabled;
  4718. UnicodeString SecurityProtocolHint;
  4719. if (SecurityEnabled)
  4720. {
  4721. SecurityProtocolHint = FMTLOAD(STATUS_SECURE, (SecurityProtocolName));
  4722. }
  4723. else
  4724. {
  4725. SecurityProtocolHint = LoadStr(STATUS_INSECURE);
  4726. }
  4727. SecurityStatusPanel->Hint = SecurityProtocolHint;
  4728. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[Offset + 2];
  4729. DurationStatusPanel->ViewPriority = OpenedTerminal ? 99 : 0;
  4730. DurationStatusPanel->Hint = DurationHint;
  4731. UpdateStatusBar();
  4732. }
  4733. //---------------------------------------------------------------------------
  4734. void __fastcall TCustomScpExplorerForm::UpdateStatusBar()
  4735. {
  4736. TTBXStatusBar * SessionStatusBar = (TTBXStatusBar *)GetComponent(fcStatusBar);
  4737. DebugAssert(SessionStatusBar != NULL);
  4738. TTBXStatusPanel * NoteStatusPanel = SessionStatusBar->Panels->Items[0];
  4739. if (!FNote.IsEmpty())
  4740. {
  4741. NoteStatusPanel->Caption = FNote;
  4742. }
  4743. else
  4744. {
  4745. UpdateStatusPanelText(NoteStatusPanel);
  4746. }
  4747. NoteStatusPanel->Hint = FNoteHints;
  4748. UnicodeString LoginTime;
  4749. // See the comment in TScpCommanderForm::UpdateControls()
  4750. TTerminal * ActiveTerminal = TTerminalManager::Instance()->ActiveTerminal;
  4751. // Active is not enough here
  4752. if ((ActiveTerminal != NULL) && (ActiveTerminal->Status == ssOpened))
  4753. {
  4754. const TSessionInfo & SessionInfo = ActiveTerminal->GetSessionInfo();
  4755. LoginTime = FormatDateTimeSpan(Now() - SessionInfo.LoginTime);
  4756. }
  4757. TTBXStatusPanel * DurationStatusPanel = SessionStatusBar->Panels->Items[SessionStatusBar->Panels->Count - 1];
  4758. DurationStatusPanel->Caption = LoginTime;
  4759. }
  4760. //---------------------------------------------------------------------------
  4761. void __fastcall TCustomScpExplorerForm::UpdateStatusPanelText(TTBXStatusPanel * Panel)
  4762. {
  4763. Panel->Caption = L"";
  4764. }
  4765. //---------------------------------------------------------------------------
  4766. void __fastcall TCustomScpExplorerForm::Idle()
  4767. {
  4768. if (FShowing ||
  4769. // Particularly for
  4770. // - Standalone editing
  4771. // - Detecting closed connection and automatically reconnect it while waiting for changes
  4772. // while "keeping remote directory up to date".
  4773. StandaloneOperation)
  4774. {
  4775. FEditorManager->Check();
  4776. // make sure that Idle is called before update queue, as it may invoke QueueEvent
  4777. // that needs to know if queue view is visible (and it may be closed after queue update)
  4778. TTerminalManager::Instance()->Idle(FDoNotIdleCurrentTerminal > 0);
  4779. }
  4780. if (FShowing)
  4781. {
  4782. if (!NonVisualDataModule->Busy &&
  4783. // Menu is opened or drag&drop is going on
  4784. (Mouse->Capture == NULL))
  4785. {
  4786. if (FRefreshRemoteDirectory)
  4787. {
  4788. if ((Terminal != NULL) && (Terminal->Status == ssOpened))
  4789. {
  4790. Terminal->RefreshDirectory();
  4791. }
  4792. FRefreshRemoteDirectory = false;
  4793. }
  4794. if (FRefreshLocalDirectory)
  4795. {
  4796. ReloadLocalDirectory();
  4797. FRefreshLocalDirectory = false;
  4798. }
  4799. if (WinConfiguration->RefreshRemotePanel)
  4800. {
  4801. if ((Terminal != NULL) && (Terminal->Status == ssOpened) &&
  4802. (Now() - Terminal->DirectoryLoaded > WinConfiguration->RefreshRemotePanelInterval))
  4803. {
  4804. RemoteDirView->ReloadDirectory();
  4805. }
  4806. }
  4807. }
  4808. // TB2 shows accels on Alt key down, but hides it only after menu modal loop finishes.
  4809. // But if Alt is used to switch apps or for keyboard shortcut, the menu modal loop does not happen and accelerators stay displayed.
  4810. // It's difficult to fix this in TB2, as there's no "up" equivalent to CM_DIALOGKEY, which shows the accels.
  4811. // And the Alt key can be released even when other window or application is active, so handling the key up in explorer window won't do either.
  4812. TTBCustomToolbar * MenuToolbar = DebugNotNull(dynamic_cast<TTBCustomToolbar *>(GetComponent(fcMenu)));
  4813. MenuToolbar->Idle();
  4814. }
  4815. if (FShowing || StandaloneOperation)
  4816. {
  4817. if (FQueueStatusInvalidated)
  4818. {
  4819. UpdateQueueStatus(false);
  4820. }
  4821. RefreshQueueItems();
  4822. }
  4823. if (FShowing)
  4824. {
  4825. UpdateStatusBar();
  4826. }
  4827. if (FClipboardFakeMonitorsPendingReset && !FDownloadingFromClipboard)
  4828. {
  4829. FClipboardFakeMonitorsPendingReset = false;
  4830. FClipboardFakeMonitors.reset(NULL);
  4831. }
  4832. FIgnoreNextDialogChar = 0;
  4833. }
  4834. //---------------------------------------------------------------------------
  4835. void __fastcall TCustomScpExplorerForm::UserActionTimer(TObject * /*Sender*/)
  4836. {
  4837. try
  4838. {
  4839. FUserActionTimer->Enabled = false;
  4840. if (IsQueueAutoPopup() && (FPendingQueueActionItem != NULL))
  4841. {
  4842. if (TQueueItem::IsUserActionStatus(FPendingQueueActionItem->Status))
  4843. {
  4844. FPendingQueueActionItem->ProcessUserAction();
  4845. }
  4846. }
  4847. }
  4848. __finally
  4849. {
  4850. FPendingQueueActionItem = NULL;
  4851. }
  4852. }
  4853. //---------------------------------------------------------------------------
  4854. void __fastcall TCustomScpExplorerForm::ApplicationMinimize(TObject * /*Sender*/)
  4855. {
  4856. if (WinConfiguration->MinimizeToTray)
  4857. {
  4858. UpdateTrayIcon();
  4859. FTrayIcon->Visible = true;
  4860. if (Visible)
  4861. {
  4862. ShowWindow(Handle, SW_HIDE);
  4863. }
  4864. }
  4865. }
  4866. //---------------------------------------------------------------------------
  4867. void __fastcall TCustomScpExplorerForm::ApplicationRestore(TObject * /*Sender*/)
  4868. {
  4869. // WORKAROUND
  4870. // When restoring maximized window from minimization,
  4871. // rarely some controls do not align properly.
  4872. // Two instances seen (both for Commander):
  4873. // - When restoring, window is temporarily narrower (not maximized),
  4874. // causing toolbars on TopDock to wrap and dock to expand horizontally.
  4875. // Once maximized already, top dock shinks back, but the session PageControl,
  4876. // do not align up, leaving space between TopDock and PageControl.
  4877. // - Similar issue seen with LocalDirView not aligning down to status bar.
  4878. for (int Index = 0; Index < ControlCount; Index++)
  4879. {
  4880. RealignControl(Controls[Index]);
  4881. }
  4882. if (FTrayIcon->Visible)
  4883. {
  4884. FTrayIcon->Visible = false;
  4885. if (Visible)
  4886. {
  4887. ShowWindow(Handle, SW_SHOW);
  4888. }
  4889. }
  4890. if (FNeedSession && DebugAlwaysTrue(Terminal == NULL))
  4891. {
  4892. FNeedSession = false;
  4893. NonVisualDataModule->StartBusy();
  4894. try
  4895. {
  4896. NeedSession(true);
  4897. }
  4898. __finally
  4899. {
  4900. NonVisualDataModule->EndBusy();
  4901. }
  4902. }
  4903. }
  4904. //---------------------------------------------------------------------------
  4905. void __fastcall TCustomScpExplorerForm::UpdateTrayIcon()
  4906. {
  4907. FTrayIcon->Hint = GetMainForm()->Caption;
  4908. }
  4909. //---------------------------------------------------------------------------
  4910. void __fastcall TCustomScpExplorerForm::ApplicationTitleChanged()
  4911. {
  4912. UpdateTrayIcon();
  4913. }
  4914. //---------------------------------------------------------------------------
  4915. void __fastcall TCustomScpExplorerForm::RestoreApp()
  4916. {
  4917. // workaround
  4918. // TApplication.WndProc sets TApplication.FAppIconic to false,
  4919. // on WM_ACTIVATEAPP, what renders TApplication.Restore no-op function.
  4920. // But WM_ACTIVATEAPP message can be received even when
  4921. // the main window is minimized to the tray and internal editor window is focused
  4922. // (after another application was previously active)
  4923. if (::IsIconic(Handle))
  4924. {
  4925. if (!IsAppIconic())
  4926. {
  4927. SetAppIconic(true);
  4928. }
  4929. }
  4930. ::ApplicationRestore();
  4931. Application->BringToFront();
  4932. }
  4933. //---------------------------------------------------------------------------
  4934. void __fastcall TCustomScpExplorerForm::TrayIconClick(TObject * /*Sender*/)
  4935. {
  4936. RestoreApp();
  4937. }
  4938. //---------------------------------------------------------------------------
  4939. void __fastcall TCustomScpExplorerForm::NewSession(const UnicodeString & SessionUrl)
  4940. {
  4941. if (OpenInNewWindow())
  4942. {
  4943. ExecuteNewInstance(SessionUrl);
  4944. }
  4945. else
  4946. {
  4947. TTerminalManager::Instance()->NewSession(SessionUrl);
  4948. }
  4949. }
  4950. //---------------------------------------------------------------------------
  4951. void TCustomScpExplorerForm::NewTab(TOperationSide, bool)
  4952. {
  4953. NewSession();
  4954. }
  4955. //---------------------------------------------------------------------------
  4956. UnicodeString __fastcall TCustomScpExplorerForm::SaveHiddenDuplicateSession(TSessionData * SessionData)
  4957. {
  4958. UnicodeString SessionName = StoredSessions->HiddenPrefix + ManagedSession->SessionData->SessionName;
  4959. StoredSessions->NewSession(SessionName, SessionData);
  4960. // modified only, explicit
  4961. StoredSessions->Save(false, true);
  4962. // encode session name because of slashes in hierarchical sessions
  4963. return EncodeUrlString(SessionName);
  4964. }
  4965. //---------------------------------------------------------------------------
  4966. UnicodeString __fastcall TCustomScpExplorerForm::CreateHiddenDuplicateSession()
  4967. {
  4968. // current working directories become defaults here, what is not right
  4969. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4970. return SaveHiddenDuplicateSession(SessionData.get());
  4971. }
  4972. //---------------------------------------------------------------------------
  4973. void __fastcall TCustomScpExplorerForm::DuplicateTab()
  4974. {
  4975. if (OpenInNewWindow())
  4976. {
  4977. ExecuteNewInstance(CreateHiddenDuplicateSession());
  4978. }
  4979. else
  4980. {
  4981. // current working directories become defaults here, what is not right
  4982. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  4983. TTerminalManager * Manager = TTerminalManager::Instance();
  4984. TManagedTerminal * ASession = Manager->NewManagedTerminal(SessionData.get());
  4985. DebugAssert(ASession->LocalBrowser == ManagedSession->LocalBrowser);
  4986. // We definitely want these
  4987. ASession->Disconnected = ManagedSession->Disconnected;
  4988. // Not sure about these two
  4989. ASession->Permanent = ManagedSession->Permanent;
  4990. ASession->DisconnectedTemporarily = ManagedSession->DisconnectedTemporarily;
  4991. Manager->ActiveSession = ASession;
  4992. }
  4993. }
  4994. //---------------------------------------------------------------------------
  4995. void __fastcall TCustomScpExplorerForm::RenameTab()
  4996. {
  4997. UnicodeString Name = ManagedSession->SessionData->SessionName;
  4998. if (InputDialog(LoadStr(RENAME_TAB_TITLE), LoadStr(RENAME_TAB_PROMPT), Name, HELP_TAB_RENAME) &&
  4999. // When submitting the default name, do not fix it
  5000. (Name != ManagedSession->SessionData->SessionName))
  5001. {
  5002. // Checks for a slash only, so it's not that big deal that we do the check after submitting the dialog only.
  5003. TSessionData::ValidateName(Name);
  5004. // This is inconsistent with how color (for example) is handled.
  5005. ManagedSession->SessionData->Name = Name;
  5006. UpdateControls();
  5007. // Add/Remove distinguishing paths from sessions of the same name.
  5008. SessionListChanged();
  5009. }
  5010. }
  5011. //---------------------------------------------------------------------------
  5012. bool __fastcall TCustomScpExplorerForm::CanCloseQueue(TTerminalQueue * Queue)
  5013. {
  5014. DebugAssert(Queue != NULL);
  5015. bool Result = Queue->IsEmpty;
  5016. if (!Result)
  5017. {
  5018. SetFocus();
  5019. Result = (MessageDialog(LoadStr(PENDING_QUEUE_ITEMS2), qtWarning, qaOK | qaCancel, HELP_NONE) == qaOK);
  5020. }
  5021. return Result;
  5022. }
  5023. //---------------------------------------------------------------------------
  5024. bool __fastcall TCustomScpExplorerForm::CanCloseQueue()
  5025. {
  5026. return CanCloseQueue(FQueue);
  5027. }
  5028. //---------------------------------------------------------------------------
  5029. void __fastcall TCustomScpExplorerForm::CloseTab()
  5030. {
  5031. if (CanCloseQueue())
  5032. {
  5033. TTerminalManager::Instance()->FreeActiveTerminal();
  5034. }
  5035. }
  5036. //---------------------------------------------------------------------------
  5037. void __fastcall TCustomScpExplorerForm::DisconnectSession()
  5038. {
  5039. if (CanCloseQueue())
  5040. {
  5041. TTerminalManager::Instance()->DisconnectActiveTerminal();
  5042. }
  5043. }
  5044. //---------------------------------------------------------------------------
  5045. void __fastcall TCustomScpExplorerForm::TerminalDisconnected()
  5046. {
  5047. DetachTerminal(Terminal);
  5048. RemoteDirView->Terminal = Terminal;
  5049. UpdateRemotePathComboBox(false);
  5050. InitStatusBar();
  5051. UpdateControls();
  5052. }
  5053. //---------------------------------------------------------------------------
  5054. void __fastcall TCustomScpExplorerForm::TerminalConnecting()
  5055. {
  5056. InitStatusBar();
  5057. }
  5058. //---------------------------------------------------------------------------
  5059. void __fastcall TCustomScpExplorerForm::ReconnectSession()
  5060. {
  5061. if (DebugAlwaysTrue(!Terminal->Active))
  5062. {
  5063. TTerminalManager::Instance()->ReconnectActiveTerminal();
  5064. }
  5065. }
  5066. //---------------------------------------------------------------------------
  5067. void __fastcall TCustomScpExplorerForm::OpenStoredSession(TSessionData * Data)
  5068. {
  5069. if (OpenInNewWindow())
  5070. {
  5071. // encode session name because of slashes in hierarchical sessions
  5072. ExecuteNewInstance(EncodeUrlString(Data->Name));
  5073. }
  5074. else
  5075. {
  5076. TTerminalManager * Manager = TTerminalManager::Instance();
  5077. TManagedTerminal * Terminal = Manager->NewManagedTerminal(Data);
  5078. Manager->ActiveSession = Terminal;
  5079. }
  5080. }
  5081. //---------------------------------------------------------------------------
  5082. void TCustomScpExplorerForm::DoOpenFolderOrWorkspace(
  5083. const UnicodeString & Name, bool ConnectFirstTerminal, bool CheckMaxSessions)
  5084. {
  5085. TTerminalManager * Manager = TTerminalManager::Instance();
  5086. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5087. // This asks for a master password. Maybe we should postpone asking until a connection is actually opened.
  5088. StoredSessions->GetFolderOrWorkspace(Name, DataList.get());
  5089. if (!CheckMaxSessions || (DataList->Count <= WinConfiguration->MaxSessions))
  5090. {
  5091. TManagedTerminal * FirstSession = Manager->NewSessions(DataList.get());
  5092. // FirstSession can be null, if none of the workspace sites exist anymore
  5093. // or if all workspace sessions are not suported by the interface
  5094. // (when trying to open all local-local workspace in "explorer" interface)
  5095. if (FirstSession != NULL)
  5096. {
  5097. if (!ConnectFirstTerminal)
  5098. {
  5099. FirstSession->Disconnected = true;
  5100. FirstSession->DisconnectedTemporarily = true;
  5101. }
  5102. Manager->ActiveSession = FirstSession;
  5103. }
  5104. }
  5105. }
  5106. //---------------------------------------------------------------------------
  5107. void __fastcall TCustomScpExplorerForm::OpenFolderOrWorkspace(const UnicodeString & Name)
  5108. {
  5109. if (OpenInNewWindow())
  5110. {
  5111. ExecuteNewInstance(Name);
  5112. }
  5113. else
  5114. {
  5115. DoOpenFolderOrWorkspace(Name, true, false);
  5116. }
  5117. }
  5118. //---------------------------------------------------------------------------
  5119. void __fastcall TCustomScpExplorerForm::FormCloseQuery(TObject * /*Sender*/,
  5120. bool &CanClose)
  5121. {
  5122. AppLog(L"Windows close query");
  5123. // See the comment in CloseApp()
  5124. if (NonVisualDataModule->Busy)
  5125. {
  5126. CanClose = false;
  5127. }
  5128. else
  5129. {
  5130. TTerminalManager * Manager = TTerminalManager::Instance();
  5131. int ActiveSessions = 0;
  5132. for (int Index = 0; Index < Manager->Count; Index++)
  5133. {
  5134. if (Manager->Sessions[Index]->Active)
  5135. {
  5136. ActiveSessions++;
  5137. }
  5138. }
  5139. // Confirm, when there's at least one active remote session or
  5140. // when there are multiple (inactive or local) sessions and auto workspace saving is not enabled.
  5141. if (((ActiveSessions > 0) || ((Manager->Count > 1) && !WinConfiguration->AutoSaveWorkspace)) &&
  5142. WinConfiguration->ConfirmClosingSession)
  5143. {
  5144. unsigned int Result;
  5145. TMessageParams Params(mpNeverAskAgainCheck);
  5146. UnicodeString Message;
  5147. int Answers = qaOK | qaCancel;
  5148. // The current session is the only active session
  5149. if ((ActiveSessions == 1) && (Terminal != NULL) && Terminal->Active)
  5150. {
  5151. if (!WinConfiguration->AutoSaveWorkspace)
  5152. {
  5153. Message = LoadStr(CLOSE_SESSION_WORKSPACE);
  5154. }
  5155. else
  5156. {
  5157. Message = LoadStr(CLOSE_SESSION);
  5158. }
  5159. Message = FORMAT(Message, (Terminal->SessionData->SessionName));
  5160. }
  5161. // Multiple active sessions or one active session, but it's not the current one
  5162. else if (ActiveSessions > 0)
  5163. {
  5164. if (!WinConfiguration->AutoSaveWorkspace)
  5165. {
  5166. Message = LoadStr(CLOSE_SESSIONS_WORKSPACE3);
  5167. }
  5168. else
  5169. {
  5170. Message = LoadStr(CLOSE_SESSIONS);
  5171. }
  5172. }
  5173. // Multiple tabs, but all are inactive or local, and saving of worspace is not enabled
  5174. else
  5175. {
  5176. DebugAlwaysTrue(Manager->Count > 1);
  5177. DebugAlwaysTrue(!WinConfiguration->AutoSaveWorkspace);
  5178. Message = LoadStr(CLOSE_WORKSPACE);
  5179. }
  5180. UnicodeString Note;
  5181. if (WinConfiguration->AutoSaveWorkspace)
  5182. {
  5183. Note = FMTLOAD(AUTO_WORKSPACE, (WorkspaceName()));
  5184. }
  5185. else
  5186. {
  5187. Note = LoadStr(AUTO_WORKSPACE_ENABLE);
  5188. Answers = qaYes | qaNo | qaCancel;
  5189. }
  5190. Message = FORMAT("%s\n\n%s", (MainInstructions(Message), Note));
  5191. SetFocus();
  5192. Result = MessageDialog(Message, qtConfirmation,
  5193. Answers, HELP_CLOSE_SESSION_WORKSPACE, &Params);
  5194. if (Result == qaNeverAskAgain)
  5195. {
  5196. WinConfiguration->ConfirmClosingSession = false;
  5197. }
  5198. if (Result == qaNo)
  5199. {
  5200. CanClose = SaveWorkspace(true);
  5201. // note that the workspace will be saved redundatly again from FormClose
  5202. }
  5203. else
  5204. {
  5205. CanClose =
  5206. (Result == qaOK) ||
  5207. (Result == qaYes) || // CLOSE_SESSIONS_WORKSPACE variant
  5208. (Result == qaNeverAskAgain);
  5209. }
  5210. }
  5211. if (CanClose && HasActiveTerminal())
  5212. {
  5213. CanClose = CanCloseQueue();
  5214. }
  5215. }
  5216. if (CanClose)
  5217. {
  5218. CanClose =
  5219. FEditorManager->CloseInternalEditors(CloseInternalEditor) &&
  5220. FEditorManager->CloseExternalFilesWithoutProcess();
  5221. if (CanClose)
  5222. {
  5223. while (CanClose && (FLocalEditors->Count > 0))
  5224. {
  5225. int PrevCount = FLocalEditors->Count;
  5226. static_cast<TForm *>(FLocalEditors->Items[0])->Close();
  5227. CanClose = (FLocalEditors->Count < PrevCount);
  5228. }
  5229. if (CanClose)
  5230. {
  5231. CanClose = FEditorManager->Empty(true);
  5232. if (!CanClose)
  5233. {
  5234. SetFocus();
  5235. CanClose =
  5236. (MessageDialog(
  5237. LoadStr(PENDING_EDITORS), qtWarning, qaIgnore | qaCancel, HELP_NONE) == qaIgnore);
  5238. }
  5239. }
  5240. }
  5241. }
  5242. }
  5243. //---------------------------------------------------------------------------
  5244. void __fastcall TCustomScpExplorerForm::CloseInternalEditor(TObject * Sender)
  5245. {
  5246. TForm * Form = dynamic_cast<TForm *>(Sender);
  5247. DebugAssert(Form != NULL);
  5248. Form->Close();
  5249. }
  5250. //---------------------------------------------------------------------------
  5251. void __fastcall TCustomScpExplorerForm::ForceCloseInternalEditor(TObject * Sender)
  5252. {
  5253. TForm * Form = dynamic_cast<TForm *>(Sender);
  5254. delete Form;
  5255. }
  5256. //---------------------------------------------------------------------------
  5257. void __fastcall TCustomScpExplorerForm::ForceCloseLocalEditors()
  5258. {
  5259. while (FLocalEditors->Count > 0)
  5260. {
  5261. delete static_cast<TForm *>(FLocalEditors->Items[0]);
  5262. }
  5263. }
  5264. //---------------------------------------------------------------------------
  5265. void __fastcall TCustomScpExplorerForm::RemoteDirViewDisplayProperties(
  5266. TObject *Sender)
  5267. {
  5268. TStrings *FileList = ((TUnixDirView*)Sender)->CreateFileList(True, False, NULL);
  5269. try
  5270. {
  5271. SetProperties(osRemote, FileList);
  5272. }
  5273. __finally
  5274. {
  5275. delete FileList;
  5276. }
  5277. }
  5278. //---------------------------------------------------------------------------
  5279. void __fastcall TCustomScpExplorerForm::ComponentShowing(Byte Component, bool value)
  5280. {
  5281. if (value)
  5282. {
  5283. if (Component == fcCustomCommandsBand)
  5284. {
  5285. UpdateCustomCommandsToolbar();
  5286. }
  5287. if (Component == fcQueueFileList)
  5288. {
  5289. DebugAssert(!QueueFileListSplitter->Visible);
  5290. AdjustQueueLayout();
  5291. UpdateQueueFileList();
  5292. }
  5293. }
  5294. }
  5295. //---------------------------------------------------------------------------
  5296. void __fastcall TCustomScpExplorerForm::AdjustQueueLayout()
  5297. {
  5298. int MinHeightLimit =
  5299. GetStaticQueuePanelComponentsHeight() +
  5300. QueueFileListSplitter->Height +
  5301. QueueFileList->Height +
  5302. GetMinQueueViewHeight();
  5303. if (QueuePanel->ClientHeight < MinHeightLimit)
  5304. {
  5305. QueuePanel->ClientHeight = MinHeightLimit;
  5306. }
  5307. }
  5308. //---------------------------------------------------------------------------
  5309. void __fastcall TCustomScpExplorerForm::SetComponentVisible(Byte Component, Boolean value)
  5310. {
  5311. TControl * Control = GetComponent(Component);
  5312. DebugAssert(Control);
  5313. bool Changed = (Control->Visible != value);
  5314. if (Changed)
  5315. {
  5316. ComponentShowing(Component, value);
  5317. TWinControl * WinControl = dynamic_cast<TWinControl*>(Control);
  5318. bool WasFocused = (WinControl != NULL) && (ActiveControl != NULL) &&
  5319. ((ActiveControl == WinControl) || (ActiveControl->Parent == WinControl));
  5320. if (value)
  5321. {
  5322. int RemainingHeight = Control->Parent->ClientHeight;
  5323. int RemainingWidth = Control->Parent->ClientWidth;
  5324. for (int i = 0; i < Control->Parent->ControlCount; i++)
  5325. {
  5326. TControl * ChildControl = Control->Parent->Controls[i];
  5327. if (ChildControl->Visible)
  5328. {
  5329. switch (ChildControl->Align)
  5330. {
  5331. case alTop:
  5332. case alBottom:
  5333. RemainingHeight -= ChildControl->Height;
  5334. break;
  5335. case alLeft:
  5336. case alRight:
  5337. RemainingWidth -= ChildControl->Width;
  5338. break;
  5339. }
  5340. }
  5341. }
  5342. int Reserve = ScaleByTextHeight(this, 32);
  5343. // queue in explorer, trees in commander
  5344. if (Control->Height > RemainingHeight - Reserve)
  5345. {
  5346. Control->Height = RemainingHeight / 2;
  5347. }
  5348. if (Control->Width > RemainingWidth - Reserve)
  5349. {
  5350. Control->Width = RemainingWidth / 2;
  5351. }
  5352. }
  5353. Control->Visible = value;
  5354. if (WasFocused && Visible)
  5355. {
  5356. DirView(osCurrent)->SetFocus();
  5357. }
  5358. FixControlsPlacement();
  5359. }
  5360. }
  5361. //---------------------------------------------------------------------------
  5362. bool __fastcall TCustomScpExplorerForm::GetComponentVisible(Byte Component)
  5363. {
  5364. TControl * Control = GetComponent(Component);
  5365. if (Control == NULL)
  5366. {
  5367. return false;
  5368. }
  5369. else
  5370. {
  5371. return Control->Visible;
  5372. }
  5373. }
  5374. //---------------------------------------------------------------------------
  5375. bool __fastcall TCustomScpExplorerForm::IsComponentPossible(Byte Component)
  5376. {
  5377. bool Result;
  5378. if ((Component == fcExplorerUpdatesBand) || (Component == fcCommanderUpdatesBand))
  5379. {
  5380. Result = !IsUWP();
  5381. }
  5382. else
  5383. {
  5384. Result = true;
  5385. }
  5386. return Result;
  5387. }
  5388. //---------------------------------------------------------------------------
  5389. void __fastcall TCustomScpExplorerForm::MakeFocusedItemVisible(TCustomDirView * DirView)
  5390. {
  5391. if (DirView->ItemFocused != NULL)
  5392. {
  5393. DirView->ItemFocused->MakeVisible(false);
  5394. }
  5395. }
  5396. //---------------------------------------------------------------------------
  5397. void __fastcall TCustomScpExplorerForm::FixControlsPlacement()
  5398. {
  5399. MakeFocusedItemVisible(RemoteDirView);
  5400. QueueSplitter->Visible = QueuePanel->Visible;
  5401. QueueFileListSplitter->Visible = QueueFileList->Visible;
  5402. RemotePanelSplitter->Visible = RemoteDrivePanel->Visible;
  5403. TControl * TopControlsOrder[] =
  5404. { TopDock, MessageDock, SessionsPageControl };
  5405. SetVerticalControlsOrder(TopControlsOrder, LENOF(TopControlsOrder));
  5406. TControl * QueueControlsOrder[] =
  5407. { QueueDock, QueueView3, QueueFileListSplitter, QueueFileList };
  5408. SetVerticalControlsOrder(QueueControlsOrder, LENOF(QueueControlsOrder));
  5409. }
  5410. //---------------------------------------------------------------------------
  5411. TControl * __fastcall TCustomScpExplorerForm::GetComponent(Byte Component)
  5412. {
  5413. switch (Component) {
  5414. case fcStatusBar: return RemoteStatusBar;
  5415. case fcRemotePopup: return reinterpret_cast<TControl *>(NonVisualDataModule->RemoteFilePopup);
  5416. case fcQueueView: return QueuePanel;
  5417. case fcQueueToolbar: return QueueDock;
  5418. case fcRemoteTree: return RemoteDrivePanel;
  5419. case fcSessionsTabs: return SessionsPageControl;
  5420. case fcQueueFileList: return QueueFileList;
  5421. default: return NULL;
  5422. }
  5423. }
  5424. //---------------------------------------------------------------------------
  5425. void __fastcall TCustomScpExplorerForm::DirViewColumnRightClick(
  5426. TObject *Sender, TListColumn *Column, TPoint &Point)
  5427. {
  5428. DebugAssert(NonVisualDataModule && Column && Sender);
  5429. NonVisualDataModule->ListColumn = Column;
  5430. TPopupMenu * DirViewColumnMenu;
  5431. if (Sender == DirView(osOther))
  5432. {
  5433. DirViewColumnMenu = NonVisualDataModule->RemoteDirViewColumnPopup;
  5434. NonVisualDataModule->RemoteSortByExtColumnPopupItem->Visible = (Column->Index == uvName);
  5435. bool SizeColumn = (Column->Index == uvSize);
  5436. NonVisualDataModule->RemoteFormatSizeBytesPopupItem->Visible = SizeColumn;
  5437. NonVisualDataModule->RemoteCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5438. }
  5439. else
  5440. {
  5441. DirViewColumnMenu = NonVisualDataModule->LocalDirViewColumnPopup;
  5442. NonVisualDataModule->LocalSortByExtColumnPopupItem->Visible = (Column->Index == dvName);
  5443. bool SizeColumn = (Column->Index == dvSize);
  5444. NonVisualDataModule->LocalFormatSizeBytesPopupItem->Visible = SizeColumn;
  5445. NonVisualDataModule->LocalCalculateDirectorySizesPopupItem->Visible = SizeColumn;
  5446. }
  5447. TCustomListView * ListView = DebugNotNull(dynamic_cast<TCustomListView *>(Sender));
  5448. TPoint ScreenPoint = ListView->ClientToScreen(Point);
  5449. ScreenPoint.x -= GetScrollPos(ListView->Handle, SB_HORZ);
  5450. DirViewColumnMenu->Popup(ScreenPoint.x, ScreenPoint.y);
  5451. }
  5452. //---------------------------------------------------------------------------
  5453. void __fastcall TCustomScpExplorerForm::DirViewExecFile(
  5454. TObject *Sender, TListItem *Item, bool &AllowExec)
  5455. {
  5456. DoDirViewExecFile(Sender, Item, AllowExec);
  5457. }
  5458. //---------------------------------------------------------------------------
  5459. void __fastcall TCustomScpExplorerForm::DoDirViewExecFile(TObject * Sender,
  5460. TListItem * Item, bool & AllowExec)
  5461. {
  5462. DebugAssert(Sender && Item && Configuration);
  5463. DebugAssert(AllowExec);
  5464. TCustomDirView * ADirView = (TCustomDirView *)Sender;
  5465. TOperationSide Side = ((ADirView == DirView(osRemote)) ? osRemote : osLocal);
  5466. bool Remote = !IsSideLocalBrowser(Side);
  5467. DebugAssert(Item == ADirView->ItemFocused);
  5468. bool IsDirectory = ADirView->ItemIsDirectory(Item);
  5469. TResolvedDoubleClickAction Action;
  5470. if (FForceExecution)
  5471. {
  5472. Action = IsDirectory ? rdcaChangeDir : rdcaOpen;
  5473. }
  5474. else
  5475. {
  5476. TTerminal * ATerminal = !IsSideLocalBrowser(Side) ? Terminal : NULL;
  5477. Action = WinConfiguration->ResolveDoubleClickAction(IsDirectory, ATerminal);
  5478. }
  5479. if (Action == rdcaCopy)
  5480. {
  5481. // To counter the lock in DirViewBusy (called from TCustomDirView.DoExecute)
  5482. UnlockWindow();
  5483. try
  5484. {
  5485. if (IsLocalBrowserMode())
  5486. {
  5487. LocalLocalCopy(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation, false, 0);
  5488. }
  5489. else
  5490. {
  5491. if (HasActiveTerminal())
  5492. {
  5493. ExecuteFileOperation(foCopy, Side, true, !WinConfiguration->CopyOnDoubleClickConfirmation);
  5494. }
  5495. }
  5496. }
  5497. __finally
  5498. {
  5499. LockWindow();
  5500. }
  5501. AllowExec = false;
  5502. }
  5503. else if (Action == rdcaEdit)
  5504. {
  5505. if (!Remote || !WinConfiguration->DisableOpenEdit)
  5506. {
  5507. ExecuteFile(Side, efDefaultEditor);
  5508. AllowExec = false;
  5509. }
  5510. }
  5511. else if (Action == rdcaOpen)
  5512. {
  5513. if (DebugAlwaysTrue(!IsDirectory) && Remote && !WinConfiguration->DisableOpenEdit)
  5514. {
  5515. ExecuteFile(osRemote, efShell);
  5516. AllowExec = false;
  5517. }
  5518. }
  5519. }
  5520. //---------------------------------------------------------------------------
  5521. bool __fastcall TCustomScpExplorerForm::GetHasDirView(TOperationSide Side)
  5522. {
  5523. return ((Side == osRemote) || (Side == osCurrent));
  5524. }
  5525. //---------------------------------------------------------------------------
  5526. void __fastcall TCustomScpExplorerForm::CompareDirectories()
  5527. {
  5528. DebugFail();
  5529. }
  5530. //---------------------------------------------------------------------------
  5531. void __fastcall TCustomScpExplorerForm::SynchronizeDirectories()
  5532. {
  5533. DebugFail();
  5534. }
  5535. //---------------------------------------------------------------------------
  5536. bool __fastcall TCustomScpExplorerForm::DoSynchronizeDirectories(
  5537. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory, int UseDefaults)
  5538. {
  5539. TSynchronizeParamType Params;
  5540. Params.LocalDirectory = LocalDirectory;
  5541. Params.RemoteDirectory = RemoteDirectory;
  5542. int UnusedParams =
  5543. (GUIConfiguration->SynchronizeParams &
  5544. (TTerminal::spPreviewChanges | TTerminal::spTimestamp | TTerminal::spNotByTime | TTerminal::spBySize |
  5545. TTerminal::spCaseSensitive | TTerminal::spMirror | TTerminal::spByChecksum));
  5546. Params.Params = GUIConfiguration->SynchronizeParams & ~UnusedParams;
  5547. Params.Options = GUIConfiguration->SynchronizeOptions;
  5548. bool SaveSettings = false;
  5549. TSynchronizeController Controller(&DoSynchronize, &DoSynchronizeInvalid,
  5550. &DoSynchronizeTooManyDirectories);
  5551. DebugAssert(FSynchronizeController == NULL);
  5552. FSynchronizeController = &Controller;
  5553. bool Result;
  5554. try
  5555. {
  5556. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  5557. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).Upload;
  5558. int Options =
  5559. FLAGMASK(SynchronizeAllowSelectedOnly(), soAllowSelectedOnly);
  5560. DebugAssert(FOnFeedSynchronizeError == NULL);
  5561. DebugAssert(FOnSynchronizeAbort == NULL);
  5562. DebugAssert(FSynchronizeTerminal == NULL);
  5563. FSynchronizeTerminal = Terminal;
  5564. Result = DoSynchronizeDialog(Params, &CopyParam, Controller.StartStop,
  5565. SaveSettings, Options, CopyParamAttrs, GetSynchronizeOptions, SynchronizeSessionLog,
  5566. FOnFeedSynchronizeError, FOnSynchronizeAbort, SynchronizeInNewWindow, UseDefaults);
  5567. if (Result)
  5568. {
  5569. if (SaveSettings)
  5570. {
  5571. GUIConfiguration->SynchronizeParams = Params.Params | UnusedParams;
  5572. GUIConfiguration->SynchronizeOptions = Params.Options;
  5573. }
  5574. else
  5575. {
  5576. if (FLAGSET(GUIConfiguration->SynchronizeOptions, soSynchronizeAsk) &&
  5577. FLAGCLEAR(Params.Options, soSynchronizeAsk) &&
  5578. FLAGSET(Params.Options, soSynchronize))
  5579. {
  5580. GUIConfiguration->SynchronizeOptions =
  5581. (GUIConfiguration->SynchronizeOptions & ~soSynchronizeAsk) |
  5582. soSynchronize;
  5583. }
  5584. }
  5585. LocalDirectory = Params.LocalDirectory;
  5586. RemoteDirectory = Params.RemoteDirectory;
  5587. }
  5588. }
  5589. __finally
  5590. {
  5591. FSynchronizeController = NULL;
  5592. DebugAssert(FOnFeedSynchronizeError == NULL);
  5593. FOnFeedSynchronizeError = NULL;
  5594. DebugAssert(FOnSynchronizeAbort == NULL);
  5595. FOnSynchronizeAbort = NULL;
  5596. FSynchronizeTerminal = NULL;
  5597. }
  5598. return Result;
  5599. }
  5600. //---------------------------------------------------------------------------
  5601. void __fastcall TCustomScpExplorerForm::DoSynchronize(
  5602. TSynchronizeController * /*Sender*/, const UnicodeString LocalDirectory,
  5603. const UnicodeString RemoteDirectory, const TCopyParamType & CopyParam,
  5604. const TSynchronizeParamType & Params, TSynchronizeChecklist ** Checklist,
  5605. TSynchronizeOptions * Options, bool Full)
  5606. {
  5607. // Keep-up-to-date mode
  5608. if (Terminal->Status == ssOpened)
  5609. {
  5610. try
  5611. {
  5612. int PParams = Params.Params;
  5613. if (!Full)
  5614. {
  5615. PParams |= TTerminal::spNoRecurse | TTerminal::spUseCache | TTerminal::spDelayProgress;
  5616. if (FLAGSET(Params.Options, soRecurse))
  5617. {
  5618. PParams |= TTerminal::spSubDirs;
  5619. }
  5620. }
  5621. else
  5622. {
  5623. // if keepuptodate is non-recursive,
  5624. // full sync before has to be non-recursive as well
  5625. if (FLAGCLEAR(Params.Options, soRecurse))
  5626. {
  5627. PParams |= TTerminal::spNoRecurse;
  5628. }
  5629. }
  5630. Synchronize(LocalDirectory, RemoteDirectory, smRemote, CopyParam,
  5631. PParams, Checklist, Options);
  5632. }
  5633. catch (Exception & E)
  5634. {
  5635. if (!Terminal->Active)
  5636. {
  5637. ShowExtendedExceptionEx(Terminal, &E);
  5638. // Do not abort the "keep up to date" when the session was succesfully reconnected.
  5639. if (!Terminal->Active)
  5640. {
  5641. throw;
  5642. }
  5643. }
  5644. else
  5645. {
  5646. if (FLAGSET(Params.Options, soContinueOnError) &&
  5647. DebugAlwaysTrue(FOnFeedSynchronizeError != NULL))
  5648. {
  5649. // noop, already logged in MoreMessageDialog
  5650. }
  5651. else
  5652. {
  5653. // We get mostly EAbort here, so this is noop.
  5654. // Exception is an error when listing directories while looking for differences.
  5655. ShowExtendedExceptionEx(Terminal, &E);
  5656. throw;
  5657. }
  5658. }
  5659. }
  5660. }
  5661. }
  5662. //---------------------------------------------------------------------------
  5663. void __fastcall TCustomScpExplorerForm::DoSynchronizeInvalid(
  5664. TSynchronizeController * /*Sender*/, const UnicodeString Directory,
  5665. const UnicodeString ErrorStr)
  5666. {
  5667. if (!Directory.IsEmpty())
  5668. {
  5669. SimpleErrorDialog(FMTLOAD(WATCH_ERROR_DIRECTORY, (Directory)), ErrorStr);
  5670. }
  5671. else
  5672. {
  5673. SimpleErrorDialog(LoadStr(WATCH_ERROR_GENERAL), ErrorStr);
  5674. }
  5675. }
  5676. //---------------------------------------------------------------------------
  5677. void __fastcall TCustomScpExplorerForm::DoSynchronizeTooManyDirectories(
  5678. TSynchronizeController * /*Sender*/, int & MaxDirectories)
  5679. {
  5680. if (MaxDirectories < GUIConfiguration->MaxWatchDirectories)
  5681. {
  5682. MaxDirectories = GUIConfiguration->MaxWatchDirectories;
  5683. }
  5684. else
  5685. {
  5686. TMessageParams Params(mpNeverAskAgainCheck);
  5687. unsigned int Result = MessageDialog(
  5688. FMTLOAD(TOO_MANY_WATCH_DIRECTORIES, (MaxDirectories, MaxDirectories)),
  5689. qtConfirmation, qaYes | qaNo, HELP_TOO_MANY_WATCH_DIRECTORIES, &Params);
  5690. if ((Result == qaYes) || (Result == qaNeverAskAgain))
  5691. {
  5692. MaxDirectories *= 2;
  5693. if (Result == qaNeverAskAgain)
  5694. {
  5695. GUIConfiguration->MaxWatchDirectories = MaxDirectories;
  5696. }
  5697. }
  5698. else
  5699. {
  5700. Abort();
  5701. }
  5702. }
  5703. }
  5704. //---------------------------------------------------------------------------
  5705. void __fastcall TCustomScpExplorerForm::Synchronize(const UnicodeString LocalDirectory,
  5706. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5707. const TCopyParamType & CopyParam, int Params, TSynchronizeChecklist ** Checklist,
  5708. TSynchronizeOptions * Options)
  5709. {
  5710. // Keep-up-to-date mode
  5711. DebugAssert(!FAutoOperation);
  5712. void * BatchStorage;
  5713. BatchStart(BatchStorage);
  5714. FAutoOperation = true;
  5715. bool AnyOperation = false;
  5716. TDateTime StartTime = Now();
  5717. TSynchronizeChecklist * AChecklist = NULL;
  5718. try
  5719. {
  5720. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, -1);
  5721. if (FLAGCLEAR(Params, TTerminal::spDelayProgress))
  5722. {
  5723. FSynchronizeProgressForm->Start();
  5724. }
  5725. AChecklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  5726. static_cast<TTerminal::TSynchronizeMode>(Mode),
  5727. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5728. Options);
  5729. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  5730. SAFE_DESTROY(FSynchronizeProgressForm);
  5731. AnyOperation = (AChecklist->CheckedCount > 0);
  5732. if (AnyOperation)
  5733. {
  5734. TSynchronizeProgress SynchronizeProgress(AChecklist);
  5735. CreateProgressForm(&SynchronizeProgress);
  5736. try
  5737. {
  5738. Terminal->SynchronizeApply(
  5739. AChecklist, &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  5740. SynchronizeProcessedItem, NULL, NULL, NULL);
  5741. }
  5742. __finally
  5743. {
  5744. DestroyProgressForm();
  5745. }
  5746. }
  5747. }
  5748. __finally
  5749. {
  5750. if (Checklist == NULL)
  5751. {
  5752. delete AChecklist;
  5753. }
  5754. else
  5755. {
  5756. *Checklist = AChecklist;
  5757. }
  5758. FAutoOperation = false;
  5759. SAFE_DESTROY(FSynchronizeProgressForm);
  5760. BatchEnd(BatchStorage);
  5761. ReloadLocalDirectory();
  5762. if (AnyOperation)
  5763. {
  5764. OperationComplete(StartTime);
  5765. }
  5766. }
  5767. }
  5768. //---------------------------------------------------------------------------
  5769. bool __fastcall TCustomScpExplorerForm::SynchronizeAllowSelectedOnly()
  5770. {
  5771. // can be called from command line
  5772. return Visible &&
  5773. ((DirView(osRemote)->SelCount > 0) ||
  5774. (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0)));
  5775. }
  5776. //---------------------------------------------------------------------------
  5777. void __fastcall TCustomScpExplorerForm::SynchronizeSessionLog(const UnicodeString & Message)
  5778. {
  5779. LogSynchronizeEvent(Terminal, Message);
  5780. }
  5781. //---------------------------------------------------------------------------
  5782. void __fastcall TCustomScpExplorerForm::GetSynchronizeOptions(
  5783. int Params, TSynchronizeOptions & Options)
  5784. {
  5785. DebugAssert(!IsLocalBrowserMode());
  5786. if (FLAGSET(Params, TTerminal::spSelectedOnly) && SynchronizeAllowSelectedOnly())
  5787. {
  5788. Options.Filter = new TStringList();
  5789. Options.Filter->CaseSensitive = false;
  5790. Options.Filter->Duplicates = Types::dupAccept;
  5791. if (DirView(osRemote)->SelCount > 0)
  5792. {
  5793. DirView(osRemote)->CreateFileList(false, false, Options.Filter);
  5794. }
  5795. if (HasDirView[osLocal] && (DirView(osLocal)->SelCount > 0))
  5796. {
  5797. DirView(osLocal)->CreateFileList(false, false, Options.Filter);
  5798. }
  5799. Options.Filter->Sort();
  5800. }
  5801. }
  5802. //---------------------------------------------------------------------------
  5803. UnicodeString __fastcall TCustomScpExplorerForm::SerializeCopyParamForCommandLine(const TCopyParamType * CopyParams)
  5804. {
  5805. TCopyParamType Defaults;
  5806. std::unique_ptr<THierarchicalStorage> ConfigStorage(Configuration->CreateConfigStorage());
  5807. ConfigStorage->AccessMode = smRead;
  5808. if (ConfigStorage->OpenSubKey(Configuration->ConfigurationSubKey, false))
  5809. {
  5810. GUIConfiguration->LoadCopyParam(ConfigStorage.get(), &Defaults);
  5811. }
  5812. ConfigStorage.reset(NULL);
  5813. std::unique_ptr<TStringList> Options(new TStringList());
  5814. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  5815. CopyParams->Save(OptionsStorage.get(), &Defaults);
  5816. UnicodeString Result;
  5817. if (Options->Count > 0)
  5818. {
  5819. Result =
  5820. FORMAT(L" %s%s", (TProgramParams::FormatSwitch(RAWTRANSFERSETTINGS_SWITCH), StringsToParams(Options.get())));
  5821. }
  5822. return Result;
  5823. }
  5824. //---------------------------------------------------------------------------
  5825. void __fastcall TCustomScpExplorerForm::SynchronizeInNewWindow(
  5826. const TSynchronizeParamType & Params, const TCopyParamType * CopyParams)
  5827. {
  5828. UnicodeString SessionName = CreateHiddenDuplicateSession();
  5829. UnicodeString AdditionalParams =
  5830. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  5831. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  5832. SerializeCopyParamForCommandLine(CopyParams),
  5833. TProgramParams::FormatSwitch(KEEP_UP_TO_DATE_SWITCH),
  5834. Params.LocalDirectory, Params.RemoteDirectory, Params.Params, Params.Options));
  5835. ExecuteNewInstance(SessionName, AdditionalParams);
  5836. }
  5837. //---------------------------------------------------------------------------
  5838. struct TSynchronizeParams
  5839. {
  5840. UnicodeString LocalDirectory;
  5841. UnicodeString RemoteDirectory;
  5842. TSynchronizeMode Mode;
  5843. TSynchronizeChecklist * Checklist;
  5844. int Params;
  5845. TCopyParamType * CopyParam;
  5846. TDateTime CollectElapsed;
  5847. TDateTime * StartTime;
  5848. TProcessedSynchronizationChecklistItem OnProcessedItem;
  5849. };
  5850. //---------------------------------------------------------------------------
  5851. void __fastcall TCustomScpExplorerForm::FullSynchronize(
  5852. TSynchronizeParams & Params, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5853. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5854. {
  5855. DebugAssert(!FAutoOperation);
  5856. void * BatchStorage;
  5857. BatchStart(BatchStorage);
  5858. FAutoOperation = true;
  5859. TFileOperationStatistics Statistics;
  5860. TDateTime Start = Now();
  5861. try
  5862. {
  5863. Params.OnProcessedItem = OnProcessedItem;
  5864. TSynchronizeProgress SynchronizeProgress(Params.Checklist);
  5865. CreateProgressForm(&SynchronizeProgress);
  5866. Terminal->SynchronizeApply(
  5867. Params.Checklist, Params.CopyParam, Params.Params | TTerminal::spNoConfirmation,
  5868. TerminalSynchronizeDirectory, SynchronizeProcessedItem, OnUpdatedSynchronizationChecklistItems, &Params,
  5869. &Statistics);
  5870. }
  5871. __finally
  5872. {
  5873. Params.OnProcessedItem = NULL;
  5874. FAutoOperation = false;
  5875. DestroyProgressForm();
  5876. BatchEnd(BatchStorage);
  5877. ReloadLocalDirectory();
  5878. }
  5879. if (WinConfiguration->SynchronizeSummary)
  5880. {
  5881. UnicodeString Message = MainInstructions(LoadStr(SYNCHRONIZE_COMPLETE)) + L"\n";
  5882. // The statistics should be 0 anyway in this case
  5883. if (FLAGCLEAR(Params.Params, TTerminal::spTimestamp))
  5884. {
  5885. Message += L"\n";
  5886. if (Statistics.FilesUploaded > 0)
  5887. {
  5888. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 1), (FormatNumber(Statistics.FilesUploaded), FormatBytes(Statistics.TotalUploaded))) + L"\n";
  5889. }
  5890. if (Statistics.FilesDownloaded > 0)
  5891. {
  5892. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 2), (FormatNumber(Statistics.FilesDownloaded), FormatBytes(Statistics.TotalDownloaded))) + L"\n";
  5893. }
  5894. if (Statistics.FilesDeletedLocal > 0)
  5895. {
  5896. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 3), (FormatNumber(Statistics.FilesDeletedLocal))) + L"\n";
  5897. }
  5898. if (Statistics.FilesDeletedRemote > 0)
  5899. {
  5900. Message += FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 4), (FormatNumber(Statistics.FilesDeletedRemote))) + L"\n";
  5901. }
  5902. }
  5903. TDateTime Elapsed = (Now() - Start);
  5904. Message +=
  5905. L"\n" +
  5906. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 5), (FormatDateTimeSpan(Params.CollectElapsed))) + L"\n" +
  5907. FORMAT(LoadStrPart(SYNCHRONIZE_SUMMARY, 6), (FormatDateTimeSpan(Elapsed)));
  5908. TMessageParams Params(mpNeverAskAgainCheck);
  5909. unsigned int Result = MessageDialog(Message, qtInformation, qaOK, HELP_NONE, &Params);
  5910. if (Result == qaNeverAskAgain)
  5911. {
  5912. WinConfiguration->SynchronizeSummary = false;
  5913. }
  5914. }
  5915. }
  5916. //---------------------------------------------------------------------------
  5917. void __fastcall TCustomScpExplorerForm::SynchronizeProcessedItem(void * Token, const TSynchronizeChecklist::TItem * ChecklistItem)
  5918. {
  5919. if (DebugAlwaysTrue(FProgressForm != NULL) && DebugAlwaysTrue(FProgressForm->SynchronizeProgress != NULL))
  5920. {
  5921. FProgressForm->SynchronizeProgress->ItemProcessed(ChecklistItem);
  5922. }
  5923. // Not set in keep-up-to-date mode - Synchronize() method
  5924. if (Token != NULL)
  5925. {
  5926. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5927. if (Params.OnProcessedItem != NULL)
  5928. {
  5929. Params.OnProcessedItem(NULL, ChecklistItem);
  5930. }
  5931. }
  5932. }
  5933. //---------------------------------------------------------------------------
  5934. void __fastcall TCustomScpExplorerForm::DoFullSynchronize(
  5935. void * Token, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5936. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems)
  5937. {
  5938. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5939. *Params.StartTime = Now();
  5940. FullSynchronize(Params, OnProcessedItem, OnUpdatedSynchronizationChecklistItems);
  5941. }
  5942. //---------------------------------------------------------------------------
  5943. void __fastcall TCustomScpExplorerForm::DoSynchronizeChecklistCalculateSize(
  5944. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items, void * Token)
  5945. {
  5946. // terminal can be already closed (e.g. dropped connection)
  5947. if (Terminal != NULL)
  5948. {
  5949. TSynchronizeParams & Params = *static_cast<TSynchronizeParams *>(Token);
  5950. Terminal->SynchronizeChecklistCalculateSize(Checklist, Items, Params.CopyParam);
  5951. }
  5952. }
  5953. //---------------------------------------------------------------------------
  5954. void __fastcall TCustomScpExplorerForm::DoSynchronizeMove(
  5955. TOperationSide Side, const UnicodeString & FileName, const UnicodeString & NewFileName, TRemoteFile * RemoteFile)
  5956. {
  5957. DebugAssert(!IsLocalBrowserMode());
  5958. TAutoBatch AutoBatch(this);
  5959. TAutoFlag AutoOperationFlag(FAutoOperation);
  5960. if (Side == osRemote)
  5961. {
  5962. std::unique_ptr<TStrings> FileList(new TStringList());
  5963. FileList->AddObject(FileName, RemoteFile);
  5964. UnicodeString Target = UnixExtractFileDir(NewFileName);
  5965. UnicodeString FileMask = DelimitFileNameMask(UnixExtractFileName(NewFileName));
  5966. RemoteDirView->SaveSelection();
  5967. RemoteDirView->SaveSelectedNames();
  5968. try
  5969. {
  5970. Terminal->MoveFiles(FileList.get(), Target, FileMask, false);
  5971. }
  5972. catch(...)
  5973. {
  5974. RemoteDirView->DiscardSavedSelection();
  5975. throw;
  5976. }
  5977. RemoteDirView->RestoreSelection();
  5978. }
  5979. else if (DebugAlwaysTrue(Side == osLocal))
  5980. {
  5981. if (!MoveFile(FileName.c_str(), NewFileName.c_str()))
  5982. {
  5983. throw EOSExtException(FMTLOAD(RENAME_FILE_ERROR, (FileName, NewFileName)));
  5984. }
  5985. UnicodeString Directory = ExtractFileDir(FileName);
  5986. ReloadLocalDirectory(Directory);
  5987. UnicodeString NewDirectory = ExtractFileDir(NewFileName);
  5988. if (!SamePaths(Directory, NewDirectory))
  5989. {
  5990. ReloadLocalDirectory(NewDirectory);
  5991. }
  5992. }
  5993. }
  5994. //---------------------------------------------------------------------------
  5995. void __fastcall TCustomScpExplorerForm::DoSynchronizeBrowse(TOperationSide Side, TSynchronizeChecklist::TAction Action, const TSynchronizeChecklist::TItem * Item)
  5996. {
  5997. UnicodeString LocalPath = ExcludeTrailingBackslash(Item->Local.Directory);
  5998. if (Side == osLocal)
  5999. {
  6000. if (Action == TSynchronizeChecklist::saDownloadNew)
  6001. {
  6002. OpenFolderInExplorer(LocalPath);
  6003. }
  6004. else
  6005. {
  6006. OpenFileInExplorer(CombinePaths(LocalPath, Item->GetFileName()));
  6007. }
  6008. }
  6009. else if (DebugAlwaysTrue(Side == osRemote))
  6010. {
  6011. // Similar to CreateHiddenDuplicateSession, except that it modifies the initial directories
  6012. std::unique_ptr<TSessionData> SessionData(CloneCurrentSessionData());
  6013. SessionData->RemoteDirectory = UnixExcludeTrailingBackslash(Item->Remote.Directory);
  6014. if (!LocalPath.IsEmpty())
  6015. {
  6016. SessionData->LocalDirectory = LocalPath;
  6017. }
  6018. UnicodeString SessionName = SaveHiddenDuplicateSession(SessionData.get());
  6019. ExecuteNewInstance(SessionName, FORMAT(L"%s=\"%s\"", (TProgramParams::FormatSwitch(BROWSE_SWITCH), Item->GetFileName())));
  6020. }
  6021. }
  6022. //---------------------------------------------------------------------------
  6023. void __fastcall TCustomScpExplorerForm::FullSynchronizeInNewWindow(
  6024. TSynchronizeMode Mode, int Params, const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6025. const TCopyParamType * CopyParams)
  6026. {
  6027. UnicodeString SessionName = CreateHiddenDuplicateSession();
  6028. UnicodeString AdditionalParams =
  6029. FORMAT(L"%s%s %s // \"%s\" \"%s\" %d %d", (
  6030. TProgramParams::FormatSwitch(DEFAULTS_SWITCH),
  6031. SerializeCopyParamForCommandLine(CopyParams),
  6032. TProgramParams::FormatSwitch(SYNCHRONIZE_SWITCH),
  6033. LocalDirectory, RemoteDirectory, Mode, Params));
  6034. ExecuteNewInstance(SessionName, AdditionalParams);
  6035. }
  6036. //---------------------------------------------------------------------------
  6037. int __fastcall TCustomScpExplorerForm::DoFullSynchronizeDirectories(
  6038. UnicodeString & LocalDirectory, UnicodeString & RemoteDirectory,
  6039. TSynchronizeMode & Mode, int Params, bool & SaveMode, int UseDefaults)
  6040. {
  6041. int Result;
  6042. bool SaveSettings = false;
  6043. int Options =
  6044. FLAGMASK(!Terminal->IsCapable[fcTimestampChanging], fsoDisableTimestamp) |
  6045. FLAGMASK(!CanCalculateChecksum(), fsoDisableByChecksum) |
  6046. FLAGMASK(SynchronizeAllowSelectedOnly(), fsoAllowSelectedOnly);
  6047. TCopyParamType CopyParam = GUIConfiguration->CurrentCopyParam;
  6048. TUsableCopyParamAttrs CopyParamAttrs = Terminal->UsableCopyParamAttrs(0);
  6049. bool Continue =
  6050. ((UseDefaults == 0) ||
  6051. DoFullSynchronizeDialog(Mode, Params, LocalDirectory, RemoteDirectory,
  6052. &CopyParam, SaveSettings, SaveMode, Options, CopyParamAttrs, FullSynchronizeInNewWindow, UseDefaults)) &&
  6053. (FLAGCLEAR(Params, TTerminal::spByChecksum) || EnsureCommandSessionFallback(fcCalculatingChecksum));
  6054. if (Continue)
  6055. {
  6056. Configuration->Usage->Inc(L"Synchronizations");
  6057. CopyParam.IncludeFileMask.SetRoots(LocalDirectory, RemoteDirectory);
  6058. UpdateCopyParamCounters(CopyParam);
  6059. TSynchronizeOptions SynchronizeOptions;
  6060. GetSynchronizeOptions(Params, SynchronizeOptions);
  6061. if (SaveSettings)
  6062. {
  6063. GUIConfiguration->SynchronizeParams = Params;
  6064. }
  6065. else
  6066. {
  6067. SaveMode = false;
  6068. }
  6069. TDateTime StartTime = Now();
  6070. TSynchronizeChecklist * Checklist = NULL;
  6071. try
  6072. {
  6073. DebugAssert(!FAutoOperation);
  6074. FAutoOperation = true;
  6075. try
  6076. {
  6077. UnicodeString SessionKey = Terminal->SessionData->SessionKey;
  6078. std::unique_ptr<TStrings> DataList(Configuration->LoadDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam));
  6079. int Files = -1;
  6080. if (DataList->Count >= 1)
  6081. {
  6082. Files = StrToIntDef(DataList->Strings[0], Files);
  6083. }
  6084. else
  6085. {
  6086. DataList->Add(UnicodeString());
  6087. }
  6088. FSynchronizeProgressForm = new TSynchronizeProgressForm(Application, true, Files);
  6089. FSynchronizeProgressForm->Start();
  6090. Checklist = Terminal->SynchronizeCollect(LocalDirectory, RemoteDirectory,
  6091. static_cast<TTerminal::TSynchronizeMode>(Mode),
  6092. &CopyParam, Params | TTerminal::spNoConfirmation, TerminalSynchronizeDirectory,
  6093. &SynchronizeOptions);
  6094. if (Terminal->SessionData->CacheDirectories)
  6095. {
  6096. DataList->Strings[0] = IntToStr(SynchronizeOptions.Files);
  6097. Configuration->SaveDirectoryStatisticsCache(SessionKey, RemoteDirectory, CopyParam, DataList.get());
  6098. }
  6099. }
  6100. __finally
  6101. {
  6102. FAutoOperation = false;
  6103. SetTaskbarListProgressState(TBPF_NOPROGRESS);
  6104. SAFE_DESTROY(FSynchronizeProgressForm);
  6105. }
  6106. TSynchronizeParams SynchronizeParams;
  6107. SynchronizeParams.LocalDirectory = LocalDirectory;
  6108. SynchronizeParams.RemoteDirectory = RemoteDirectory;
  6109. SynchronizeParams.Mode = Mode;
  6110. SynchronizeParams.CopyParam = &CopyParam;
  6111. SynchronizeParams.Params = Params;
  6112. SynchronizeParams.Checklist = Checklist;
  6113. SynchronizeParams.CollectElapsed = (Now() - StartTime);
  6114. SynchronizeParams.StartTime = &StartTime;
  6115. SynchronizeParams.OnProcessedItem = NULL;
  6116. Result = Checklist->Count;
  6117. if (Checklist->Count > 0)
  6118. {
  6119. if (FLAGSET(Params, TTerminal::spPreviewChanges))
  6120. {
  6121. if (!DoSynchronizeChecklistDialog(
  6122. Checklist, Mode, Params, LocalDirectory, RemoteDirectory, CustomCommandMenu, DoFullSynchronize,
  6123. DoSynchronizeChecklistCalculateSize, DoSynchronizeMove, DoSynchronizeBrowse, &SynchronizeParams))
  6124. {
  6125. Result = -1;
  6126. }
  6127. }
  6128. else
  6129. {
  6130. FullSynchronize(SynchronizeParams, NULL, NULL);
  6131. }
  6132. }
  6133. else
  6134. {
  6135. UnicodeString Message = MainInstructions(LoadStr(COMPARE_NO_DIFFERENCES));
  6136. MessageDialog(Message, qtInformation, qaOK, HELP_SYNCHRONIZE_NO_DIFFERENCES);
  6137. }
  6138. }
  6139. __finally
  6140. {
  6141. delete Checklist;
  6142. }
  6143. OperationComplete(StartTime);
  6144. }
  6145. else
  6146. {
  6147. Result = -1;
  6148. }
  6149. return Result;
  6150. }
  6151. //---------------------------------------------------------------------------
  6152. void __fastcall TCustomScpExplorerForm::TerminalSynchronizeDirectory(
  6153. const UnicodeString & LocalDirectory, const UnicodeString & RemoteDirectory,
  6154. bool & Continue, bool Collect, const TSynchronizeOptions * Options)
  6155. {
  6156. if (Collect)
  6157. {
  6158. DebugAssert(FSynchronizeProgressForm != NULL);
  6159. if (!FSynchronizeProgressForm->Started)
  6160. {
  6161. FSynchronizeProgressForm->Start();
  6162. }
  6163. int CompareProgress = FSynchronizeProgressForm->SetData(LocalDirectory, RemoteDirectory, Options->Files, Continue);
  6164. SetTaskbarListProgressValue(CompareProgress);
  6165. }
  6166. else
  6167. {
  6168. DebugAssert(FSynchronizeProgressForm == NULL);
  6169. DebugAssert(FProgressForm != NULL);
  6170. }
  6171. }
  6172. //---------------------------------------------------------------------------
  6173. void __fastcall TCustomScpExplorerForm::StandaloneEdit(const UnicodeString & FileName)
  6174. {
  6175. UnicodeString FullFileName = AbsolutePath(Terminal->CurrentDirectory, FileName);
  6176. std::unique_ptr<TRemoteFile> File(Terminal->ReadFile(FullFileName));
  6177. if (File.get() != NULL)
  6178. {
  6179. ExecuteRemoteFile(FullFileName, File.get(), efInternalEditor);
  6180. Application->ShowMainForm = false;
  6181. Application->Run();
  6182. }
  6183. }
  6184. //---------------------------------------------------------------------------
  6185. void __fastcall TCustomScpExplorerForm::ExploreLocalDirectory(TOperationSide)
  6186. {
  6187. DebugFail();
  6188. }
  6189. //---------------------------------------------------------------------------
  6190. TSessionData * __fastcall TCustomScpExplorerForm::CloneCurrentSessionData()
  6191. {
  6192. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  6193. SessionData->Assign(ManagedSession->SessionData);
  6194. UpdateSessionData(SessionData.get());
  6195. DebugAssert(SessionData->IsLocalBrowser == IsLocalBrowserMode());
  6196. if (IsActiveTerminal(ManagedSession))
  6197. {
  6198. ManagedSession->UpdateSessionCredentials(SessionData.get());
  6199. }
  6200. if (!ManagedSession->SessionData->HasSessionName())
  6201. {
  6202. // Particularly for "Workspace/XXXX" name, we need to reset it, as it would become user-visible
  6203. // once IsWorkspace is cleared
  6204. SessionData->Name = UnicodeString();
  6205. }
  6206. // Most uses of this method ends with saving the session, and we do not want to store the IsWorkspace flag.
  6207. // Particularly, with SaveHiddenDuplicateSession, it won't work as TSessionData::ParseUrl explicitly ignored workspace sessions.
  6208. SessionData->IsWorkspace = false;
  6209. return SessionData.release();
  6210. }
  6211. //---------------------------------------------------------------------------
  6212. void __fastcall TCustomScpExplorerForm::SaveCurrentSession()
  6213. {
  6214. TSessionData * SessionData = CloneCurrentSessionData();
  6215. try
  6216. {
  6217. TSessionData * EditingSessionData = StoredSessions->FindSame(SessionData);
  6218. DoSaveSession(SessionData, EditingSessionData, true, NULL);
  6219. }
  6220. __finally
  6221. {
  6222. delete SessionData;
  6223. }
  6224. }
  6225. //---------------------------------------------------------------------------
  6226. TObjectList * __fastcall TCustomScpExplorerForm::DoCollectWorkspace()
  6227. {
  6228. TTerminalManager * Manager = TTerminalManager::Instance();
  6229. std::unique_ptr<TObjectList> DataList(new TObjectList());
  6230. if (DebugAlwaysTrue(ManagedSession != NULL))
  6231. {
  6232. // Update ManagedSession->StateData
  6233. UpdateSession(ManagedSession);
  6234. }
  6235. Manager->SaveWorkspace(DataList.get());
  6236. return DataList.release();
  6237. }
  6238. //---------------------------------------------------------------------------
  6239. void __fastcall TCustomScpExplorerForm::DoSaveWorkspace(
  6240. const UnicodeString & Name, TObjectList * DataList, bool SavePasswords, bool Explicit)
  6241. {
  6242. WinConfiguration->LastWorkspace = Name;
  6243. if (!SavePasswords)
  6244. {
  6245. for (int Index = 0; Index < DataList->Count; Index++)
  6246. {
  6247. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6248. if (SessionData->Link.IsEmpty())
  6249. {
  6250. SessionData->ClearSessionPasswords();
  6251. }
  6252. }
  6253. }
  6254. StoredSessions->NewWorkspace(Name, DataList);
  6255. // modified only
  6256. StoredSessions->Save(false, Explicit);
  6257. }
  6258. //---------------------------------------------------------------------------
  6259. UnicodeString __fastcall TCustomScpExplorerForm::WorkspaceName()
  6260. {
  6261. return
  6262. DefaultStr(WinConfiguration->LastWorkspace,
  6263. DefaultStr(WinConfiguration->AutoWorkspace, LoadStr(NEW_WORKSPACE)));
  6264. }
  6265. //---------------------------------------------------------------------------
  6266. bool __fastcall TCustomScpExplorerForm::SaveWorkspace(bool EnableAutoSave)
  6267. {
  6268. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  6269. bool AnyNonStoredSessionWithPassword = false;
  6270. bool AnyNonStoredNonWorkspaceSessionWithPassword = false;
  6271. bool AllNonStoredSessionsAnonymous = true;
  6272. TTerminalManager * Manager = TTerminalManager::Instance();
  6273. for (int Index = 0; Index < DataList->Count; Index++)
  6274. {
  6275. TSessionData * SessionData = dynamic_cast<TSessionData *>(DataList->Items[Index]);
  6276. if (SessionData->Link.IsEmpty())
  6277. {
  6278. if (SessionData->HasAnySessionPassword())
  6279. {
  6280. AnyNonStoredSessionWithPassword = true;
  6281. if (!Manager->Sessions[Index]->SessionData->IsWorkspace)
  6282. {
  6283. AnyNonStoredNonWorkspaceSessionWithPassword = true;
  6284. }
  6285. }
  6286. if (!SameText(SessionData->UserName, AnonymousUserName))
  6287. {
  6288. AllNonStoredSessionsAnonymous = false;
  6289. }
  6290. }
  6291. }
  6292. bool SavePasswords;
  6293. bool * PSavePasswords;
  6294. bool NotRecommendedSavingPasswords =
  6295. !CustomWinConfiguration->UseMasterPassword &&
  6296. !AllNonStoredSessionsAnonymous;
  6297. if (Configuration->DisablePasswordStoring ||
  6298. !AnyNonStoredSessionWithPassword)
  6299. {
  6300. PSavePasswords = NULL;
  6301. SavePasswords = false;
  6302. }
  6303. else
  6304. {
  6305. PSavePasswords = &SavePasswords;
  6306. SavePasswords =
  6307. !AnyNonStoredNonWorkspaceSessionWithPassword ||
  6308. !NotRecommendedSavingPasswords;
  6309. }
  6310. UnicodeString Name = WorkspaceName();
  6311. bool CreateShortcut = false;
  6312. bool Result =
  6313. DoSaveWorkspaceDialog(
  6314. Name, PSavePasswords, NotRecommendedSavingPasswords, CreateShortcut,
  6315. EnableAutoSave);
  6316. if (Result)
  6317. {
  6318. DoSaveWorkspace(Name, DataList.get(), SavePasswords, true);
  6319. if (CreateShortcut)
  6320. {
  6321. TOperationVisualizer Visualizer;
  6322. UnicodeString AdditionalParams = TProgramParams::FormatSwitch(DESKTOP_SWITCH);
  6323. CreateDesktopSessionShortCut(Name, L"", AdditionalParams, -1, WORKSPACE_ICON);
  6324. }
  6325. if (EnableAutoSave)
  6326. {
  6327. WinConfiguration->AutoSaveWorkspace = true;
  6328. WinConfiguration->AutoWorkspace = Name;
  6329. if (PSavePasswords != NULL)
  6330. {
  6331. WinConfiguration->AutoSaveWorkspacePasswords = SavePasswords;
  6332. }
  6333. }
  6334. }
  6335. return Result;
  6336. }
  6337. //---------------------------------------------------------------------------
  6338. void __fastcall TCustomScpExplorerForm::UpdateSession(TManagedTerminal * Session)
  6339. {
  6340. DebugAssert(IsLocalBrowserMode() == Session->LocalBrowser);
  6341. DebugAssert(Session == ManagedSession);
  6342. if (!IsLocalBrowserMode())
  6343. {
  6344. SAFE_DESTROY(Session->RemoteExplorerState);
  6345. if (WinConfiguration->PreservePanelState)
  6346. {
  6347. Session->RemoteExplorerState = RemoteDirView->SaveState();
  6348. }
  6349. }
  6350. UpdateSessionData(Session->StateData);
  6351. }
  6352. //---------------------------------------------------------------------------
  6353. void __fastcall TCustomScpExplorerForm::UpdateSessionData(TSessionData * Data)
  6354. {
  6355. // Keep in sync with TSessionData::CopyStateData
  6356. DebugAssert(Data != NULL);
  6357. // This is inconsistent with how color (for example) is handled.
  6358. Data->Name = ManagedSession->SessionData->Name;
  6359. if (!IsLocalBrowserMode())
  6360. {
  6361. // cannot use RemoteDirView->Path, because it is empty if connection
  6362. // was already closed
  6363. // also only peek, we may not be connected at all atm
  6364. // so make sure we do not try retrieving current directory from the server
  6365. // (particularly with FTP)
  6366. UnicodeString ACurrentDirectory = Terminal->PeekCurrentDirectory();
  6367. if (!ACurrentDirectory.IsEmpty())
  6368. {
  6369. Data->RemoteDirectory = ACurrentDirectory;
  6370. }
  6371. }
  6372. Data->Color = SessionColor;
  6373. }
  6374. //---------------------------------------------------------------------------
  6375. void __fastcall TCustomScpExplorerForm::ToolBarResize(TObject *Sender)
  6376. {
  6377. TTBXToolbar * Toolbar = dynamic_cast<TTBXToolbar*>(Sender);
  6378. DebugAssert(Toolbar != NULL);
  6379. for (int i = 0; i < Toolbar->Items->Count; i++)
  6380. {
  6381. TTBXCustomDropDownItem * DropDownItem;
  6382. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6383. if (DropDownItem != NULL)
  6384. {
  6385. ToolbarItemResize(DropDownItem,
  6386. Toolbar->Width - (Toolbar->View->BaseSize.x - DropDownItem->EditWidth) -
  6387. Toolbar->NonClientWidth);
  6388. break;
  6389. }
  6390. }
  6391. }
  6392. //---------------------------------------------------------------------------
  6393. void __fastcall TCustomScpExplorerForm::ToolbarItemResize(TTBXCustomDropDownItem * Item, int Width)
  6394. {
  6395. Item->EditWidth = Width;
  6396. }
  6397. //---------------------------------------------------------------------------
  6398. void __fastcall TCustomScpExplorerForm::ToolbarGetBaseSize(
  6399. TTBCustomToolbar * Toolbar, TPoint & ASize)
  6400. {
  6401. for (int i = 0; i < Toolbar->Items->Count; i++)
  6402. {
  6403. TTBXCustomDropDownItem * DropDownItem;
  6404. DropDownItem = dynamic_cast<TTBXCustomDropDownItem *>(Toolbar->Items->Items[i]);
  6405. if (DropDownItem != NULL)
  6406. {
  6407. ASize.x -= DropDownItem->EditWidth;
  6408. ASize.x += ScaleByTextHeight(this, 50) /* minimal combo width */;
  6409. }
  6410. }
  6411. }
  6412. //---------------------------------------------------------------------------
  6413. void __fastcall TCustomScpExplorerForm::DoWarnLackOfTempSpace(
  6414. const UnicodeString Path, __int64 RequiredSpace, bool & Continue)
  6415. {
  6416. if (WinConfiguration->DDWarnLackOfTempSpace)
  6417. {
  6418. UnicodeString ADrive = ExtractFileDrive(ExpandFileName(Path));
  6419. if (!ADrive.IsEmpty())
  6420. {
  6421. __int64 FreeSpace = DiskFree((Byte)(ADrive[1]-'A'+1));
  6422. DebugAssert(RequiredSpace >= 0);
  6423. __int64 RequiredWithReserve;
  6424. RequiredWithReserve = (__int64)(RequiredSpace * WinConfiguration->DDWarnLackOfTempSpaceRatio);
  6425. if (FreeSpace < RequiredWithReserve)
  6426. {
  6427. unsigned int Result;
  6428. TMessageParams Params(mpNeverAskAgainCheck);
  6429. Result = MessageDialog(FMTLOAD(DD_WARN_LACK_OF_TEMP_SPACE, (Path,
  6430. FormatBytes(FreeSpace), FormatBytes(RequiredSpace))),
  6431. qtWarning, qaYes | qaNo, HELP_DD_WARN_LACK_OF_TEMP_SPACE, &Params);
  6432. if (Result == qaNeverAskAgain)
  6433. {
  6434. WinConfiguration->DDWarnLackOfTempSpace = false;
  6435. }
  6436. Continue = (Result == qaYes || Result == qaNeverAskAgain);
  6437. }
  6438. }
  6439. }
  6440. }
  6441. //---------------------------------------------------------------------------
  6442. void __fastcall TCustomScpExplorerForm::AddBookmark(TOperationSide Side)
  6443. {
  6444. DoOpenDirectoryDialog(odAddBookmark, Side);
  6445. }
  6446. //---------------------------------------------------------------------------
  6447. TStrings * __fastcall TCustomScpExplorerForm::CreateVisitedDirectories(TOperationSide Side)
  6448. {
  6449. // we should better use TCustomDirView::FCaseSensitive, but it is private
  6450. TStringList * VisitedDirectories = CreateSortedStringList(!IsSideLocalBrowser(Side));
  6451. try
  6452. {
  6453. TCustomDirView * DView = DirView(Side);
  6454. for (int Index = -DView->BackCount; Index <= DView->ForwardCount; Index++)
  6455. {
  6456. VisitedDirectories->Add(DView->HistoryPath[Index]);
  6457. }
  6458. }
  6459. catch (...)
  6460. {
  6461. delete VisitedDirectories;
  6462. throw;
  6463. }
  6464. return VisitedDirectories;
  6465. }
  6466. //---------------------------------------------------------------------------
  6467. void __fastcall TCustomScpExplorerForm::DoOpenDirectoryDialog(
  6468. TOpenDirectoryMode Mode, TOperationSide Side)
  6469. {
  6470. bool Continue = true;
  6471. if (Mode == odAddBookmark)
  6472. {
  6473. TMessageParams Params(mpNeverAskAgainCheck);
  6474. Params.NeverAskAgainTitle = LoadStr(ADD_BOOKMARK_SHARED);
  6475. Params.NeverAskAgainCheckedInitially = WinConfiguration->UseSharedBookmarks;
  6476. UnicodeString Message = MainInstructions(FMTLOAD(ADD_BOOKMARK_CONFIRM, (DirView(Side)->PathName)));
  6477. unsigned int Answer =
  6478. MessageDialog(Message,
  6479. qtConfirmation, qaOK | qaCancel, HELP_ADD_BOOKMARK_CONFIRM, &Params);
  6480. if (Answer == qaNeverAskAgain)
  6481. {
  6482. Continue = true;
  6483. WinConfiguration->UseSharedBookmarks = true;
  6484. }
  6485. else if (Answer == qaOK)
  6486. {
  6487. Continue = true;
  6488. WinConfiguration->UseSharedBookmarks = false;
  6489. }
  6490. else
  6491. {
  6492. Continue = false;
  6493. }
  6494. }
  6495. if (Continue)
  6496. {
  6497. TStrings * VisitedDirectories = CreateVisitedDirectories(Side);
  6498. try
  6499. {
  6500. UnicodeString Name = DirView(Side)->PathName;
  6501. bool Repeat;
  6502. do
  6503. {
  6504. Repeat = false;
  6505. TOperationSide BookmarkSide = IsSideLocalBrowser(Side) ? osLocal : osRemote;
  6506. if (::DoOpenDirectoryDialog(Mode, BookmarkSide, Name, VisitedDirectories, Terminal,
  6507. // do not allow switching to location profiles,
  6508. // if we are not connected
  6509. HasDirView[osLocal] && (Terminal != NULL)))
  6510. {
  6511. TWindowLock Lock(this);
  6512. if (!TryOpenDirectory(Side, Name))
  6513. {
  6514. Repeat = true;
  6515. Mode = odBrowse;
  6516. }
  6517. }
  6518. }
  6519. while (Repeat);
  6520. }
  6521. __finally
  6522. {
  6523. delete VisitedDirectories;
  6524. }
  6525. }
  6526. }
  6527. //---------------------------------------------------------------------------
  6528. bool __fastcall TCustomScpExplorerForm::CommandSessionFallback()
  6529. {
  6530. DebugAssert(!Terminal->CommandSessionOpened);
  6531. return TTerminalManager::Instance()->ConnectTerminal(Terminal->CommandSession);
  6532. }
  6533. //---------------------------------------------------------------------------
  6534. bool __fastcall TCustomScpExplorerForm::EnsureCommandSessionFallback(TFSCapability Capability)
  6535. {
  6536. bool Result = Terminal->IsCapable[Capability] ||
  6537. Terminal->CommandSessionOpened;
  6538. if (!Result)
  6539. {
  6540. // We might get here for example when "checksum" synchronization is requested from command-line
  6541. // on server that supports neither checksum nor shell
  6542. if (!Terminal->IsCapable[fcSecondaryShell])
  6543. {
  6544. NotSupported();
  6545. }
  6546. else if (!GUIConfiguration->ConfirmCommandSession)
  6547. {
  6548. Result = true;
  6549. }
  6550. else
  6551. {
  6552. TMessageParams Params(mpNeverAskAgainCheck);
  6553. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo();
  6554. unsigned int Answer = MessageDialog(FMTLOAD(PERFORM_ON_COMMAND_SESSION2,
  6555. (FileSystemInfo.ProtocolName, FileSystemInfo.ProtocolName)), qtConfirmation,
  6556. qaOK | qaCancel, HELP_PERFORM_ON_COMMAND_SESSION, &Params);
  6557. if (Answer == qaNeverAskAgain)
  6558. {
  6559. GUIConfiguration->ConfirmCommandSession = false;
  6560. Result = true;
  6561. }
  6562. else if (Answer == qaOK)
  6563. {
  6564. Result = true;
  6565. }
  6566. }
  6567. if (Result)
  6568. {
  6569. Result = CommandSessionFallback();
  6570. }
  6571. }
  6572. return Result;
  6573. }
  6574. //---------------------------------------------------------------------------
  6575. void __fastcall TCustomScpExplorerForm::OpenConsole(UnicodeString Command)
  6576. {
  6577. if (EnsureCommandSessionFallback(fcAnyCommand))
  6578. {
  6579. DoConsoleDialog(Terminal, Command);
  6580. }
  6581. }
  6582. //---------------------------------------------------------------------------
  6583. void __fastcall TCustomScpExplorerForm::FileControlDDDragEnter(
  6584. TObject *Sender, _di_IDataObject /*DataObj*/, int /*grfKeyState*/,
  6585. const TPoint & /*Point*/, int & /*dwEffect*/, bool & Accept)
  6586. {
  6587. if (!IsSideLocalBrowser(osRemote) &&
  6588. IsFileControl(DropSourceControl, osRemote) &&
  6589. (FDDExtMapFile != NULL))
  6590. {
  6591. Accept = true;
  6592. }
  6593. FDDTargetControl = dynamic_cast<TControl*>(Sender);
  6594. DebugAssert(FDDTargetControl != NULL);
  6595. }
  6596. //---------------------------------------------------------------------------
  6597. void __fastcall TCustomScpExplorerForm::SessionsDDDragEnter(
  6598. _di_IDataObject DataObj, int KeyState,
  6599. const TPoint & Point, int & Effect, bool & Accept)
  6600. {
  6601. FileControlDDDragEnter(SessionsPageControl, DataObj, KeyState, Point, Effect, Accept);
  6602. }
  6603. //---------------------------------------------------------------------------
  6604. void __fastcall TCustomScpExplorerForm::QueueDDDragEnter(
  6605. _di_IDataObject DataObj, int KeyState,
  6606. const TPoint & Point, int & Effect, bool & Accept)
  6607. {
  6608. FileControlDDDragEnter(QueueView3, DataObj, KeyState, Point, Effect, Accept);
  6609. }
  6610. //---------------------------------------------------------------------------
  6611. void __fastcall TCustomScpExplorerForm::FileControlDDDragLeave(
  6612. TObject * Sender)
  6613. {
  6614. DebugUsedParam(Sender);
  6615. DebugAssert(FDDTargetControl == Sender);
  6616. FDDTargetControl = NULL;
  6617. }
  6618. //---------------------------------------------------------------------------
  6619. void __fastcall TCustomScpExplorerForm::SessionsDDDragLeave()
  6620. {
  6621. FileControlDDDragLeave(SessionsPageControl);
  6622. }
  6623. //---------------------------------------------------------------------------
  6624. void __fastcall TCustomScpExplorerForm::QueueDDDragLeave()
  6625. {
  6626. FileControlDDDragLeave(QueueView3);
  6627. }
  6628. //---------------------------------------------------------------------------
  6629. void __fastcall TCustomScpExplorerForm::AddEditLink(TOperationSide Side, bool Add)
  6630. {
  6631. DebugAssert(!IsSideLocalBrowser(Side));
  6632. DebugUsedParam(Side);
  6633. bool Edit = false;
  6634. TRemoteFile * File = NULL;
  6635. UnicodeString FileName;
  6636. UnicodeString PointTo;
  6637. bool SymbolicLink = true;
  6638. if (RemoteDirView->ItemFocused)
  6639. {
  6640. DebugAssert(RemoteDirView->ItemFocused->Data);
  6641. File = (TRemoteFile *)RemoteDirView->ItemFocused->Data;
  6642. Edit = !Add && File->IsSymLink && Terminal->SessionData->ResolveSymlinks;
  6643. if (Edit)
  6644. {
  6645. FileName = File->FileName;
  6646. PointTo = File->LinkTo;
  6647. }
  6648. else if (!File->IsParentDirectory)
  6649. {
  6650. PointTo = File->FileName;
  6651. }
  6652. }
  6653. if (DoSymlinkDialog(FileName, PointTo, osRemote, SymbolicLink, Edit,
  6654. Terminal->IsCapable[fcHardLink]))
  6655. {
  6656. Configuration->Usage->Inc(L"RemoteLinksCreated");
  6657. if (Edit)
  6658. {
  6659. DebugAssert(File->FileName == FileName);
  6660. int Params = dfNoRecursive;
  6661. Terminal->ExceptionOnFail = true;
  6662. try
  6663. {
  6664. Terminal->DeleteFile(L"", File, &Params);
  6665. }
  6666. __finally
  6667. {
  6668. Terminal->ExceptionOnFail = false;
  6669. }
  6670. }
  6671. Terminal->CreateLink(FileName, PointTo, SymbolicLink);
  6672. }
  6673. }
  6674. //---------------------------------------------------------------------------
  6675. bool __fastcall TCustomScpExplorerForm::CanAddEditLink(TOperationSide Side)
  6676. {
  6677. return
  6678. (IsSideLocalBrowser(Side) ||
  6679. (HasActiveTerminal() &&
  6680. Terminal->ResolvingSymlinks &&
  6681. Terminal->IsCapable[fcSymbolicLink]));
  6682. }
  6683. //---------------------------------------------------------------------------
  6684. bool __fastcall TCustomScpExplorerForm::LinkFocused()
  6685. {
  6686. return
  6687. !IsSideLocalBrowser(FCurrentSide) &&
  6688. (RemoteDirView->ItemFocused != NULL) &&
  6689. ((TRemoteFile *)RemoteDirView->ItemFocused->Data)->IsSymLink &&
  6690. Terminal->SessionData->ResolveSymlinks;
  6691. }
  6692. //---------------------------------------------------------------------------
  6693. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFile()
  6694. {
  6695. DebugAssert(!WinConfiguration->DisableOpenEdit);
  6696. FForceExecution = true;
  6697. try
  6698. {
  6699. DirView(osCurrent)->ExecuteCurrentFile();
  6700. }
  6701. __finally
  6702. {
  6703. FForceExecution = false;
  6704. }
  6705. }
  6706. //---------------------------------------------------------------------------
  6707. void __fastcall TCustomScpExplorerForm::ExecuteCurrentFileWith(bool OnFocused)
  6708. {
  6709. TEditorData ExternalEditor;
  6710. ExternalEditor.Editor = edExternal;
  6711. bool Remember = false;
  6712. if (DoEditorPreferencesDialog(&ExternalEditor, Remember, epmAdHoc, !IsSideLocalBrowser(osCurrent)))
  6713. {
  6714. if (Remember)
  6715. {
  6716. TEditorList * EditorList = new TEditorList;
  6717. try
  6718. {
  6719. *EditorList = *WinConfiguration->EditorList;
  6720. bool Found = false;
  6721. int i = 0;
  6722. while (!Found && (i < EditorList->Count))
  6723. {
  6724. const TEditorPreferences * Editor = EditorList->Editors[i];
  6725. if ((Editor->Data->Editor == edExternal) &&
  6726. (Editor->Data->ExternalEditor == ExternalEditor.ExternalEditor))
  6727. {
  6728. Found = true;
  6729. }
  6730. i++;
  6731. }
  6732. if (!Found)
  6733. {
  6734. EditorList->Add(new TEditorPreferences(ExternalEditor));
  6735. WinConfiguration->EditorList = EditorList;
  6736. }
  6737. }
  6738. __finally
  6739. {
  6740. delete EditorList;
  6741. }
  6742. }
  6743. ExecuteFile(osCurrent, efExternalEditor, &ExternalEditor, true, OnFocused);
  6744. }
  6745. }
  6746. //---------------------------------------------------------------------------
  6747. void __fastcall TCustomScpExplorerForm::DetachTerminal(TObject * ATerminal)
  6748. {
  6749. if (FFileFindTerminal == ATerminal)
  6750. {
  6751. FFileFindTerminal = NULL;
  6752. HideFileFindDialog();
  6753. }
  6754. if (FClipboardTerminal == ATerminal)
  6755. {
  6756. ClipboardClear(); // implies ClipboardStop
  6757. }
  6758. if ((FOnSynchronizeAbort != NULL) &&
  6759. (ATerminal == FManagedSession))
  6760. {
  6761. FOnSynchronizeAbort(NULL);
  6762. }
  6763. }
  6764. //---------------------------------------------------------------------------
  6765. void __fastcall TCustomScpExplorerForm::TerminalRemoved(TObject * Sender)
  6766. {
  6767. FEditorManager->ProcessFiles(FileTerminalRemoved, Sender);
  6768. DetachTerminal(Sender);
  6769. }
  6770. //---------------------------------------------------------------------------
  6771. void __fastcall TCustomScpExplorerForm::FileTerminalReplaced(
  6772. const UnicodeString FileName, TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6773. {
  6774. TManagedTerminal * ATerminal = static_cast<TManagedTerminal *>(Arg);
  6775. if (Data->Terminal == Terminal)
  6776. {
  6777. Data->Terminal = ATerminal;
  6778. }
  6779. }
  6780. //---------------------------------------------------------------------------
  6781. void __fastcall TCustomScpExplorerForm::FileTerminalRemoved(const UnicodeString FileName,
  6782. TEditedFileData * Data, TObject * /*Token*/, void * Arg)
  6783. {
  6784. TTerminal * Terminal = static_cast<TTerminal *>(Arg);
  6785. DebugAssert(Terminal != NULL);
  6786. if (Data->Terminal == Terminal)
  6787. {
  6788. Data->Terminal = NULL;
  6789. }
  6790. }
  6791. //---------------------------------------------------------------------------
  6792. TManagedTerminal * TCustomScpExplorerForm::GetReplacementForLastSession()
  6793. {
  6794. return NULL;
  6795. }
  6796. //---------------------------------------------------------------------------
  6797. void __fastcall TCustomScpExplorerForm::LastTerminalClosed()
  6798. {
  6799. UpdateControls();
  6800. SessionColor = TColor(0);
  6801. UpdateRemotePathComboBox(false);
  6802. NeedSession(false);
  6803. }
  6804. //---------------------------------------------------------------------------
  6805. void __fastcall TCustomScpExplorerForm::NeedSession(bool Startup)
  6806. {
  6807. try
  6808. {
  6809. // Cache, as the login dialog can change its value.
  6810. // See also DoShow. Also see TTerminalManager::NewSession.
  6811. bool ShowLogin = WinConfiguration->ShowLoginWhenNoSession;
  6812. try
  6813. {
  6814. if (ShowLogin)
  6815. {
  6816. bool ReloadSessions = !Startup;
  6817. TTerminalManager::Instance()->NewSession(L"", ReloadSessions, this, true);
  6818. }
  6819. }
  6820. __finally
  6821. {
  6822. // Do not terminate, if we are only starting up and we are not showing Login dialog
  6823. // (so there was no chance for the user to open any session yet)
  6824. if ((ShowLogin || !Startup) &&
  6825. !WinConfiguration->KeepOpenWhenNoSession &&
  6826. // this rules out the implicit Commander's local-local browser
  6827. ((Terminal == NULL) || (!Terminal->Active && !Terminal->Permanent)))
  6828. {
  6829. TerminateApplication();
  6830. }
  6831. }
  6832. }
  6833. catch (EAbort &)
  6834. {
  6835. // swallow
  6836. // The TTerminalManager does not expect the OnLastTerminalClose to throw without trying to connect.
  6837. // Also when called from TWinControl.UpdateShowing => CMShowingChanged, the showing is aborted on exception
  6838. }
  6839. }
  6840. //---------------------------------------------------------------------------
  6841. void __fastcall TCustomScpExplorerForm::SessionListChanged(bool ForceTruncationUpdate)
  6842. {
  6843. TTerminalManager * Manager = TTerminalManager::Instance();
  6844. DebugAssert(!Manager->Updating);
  6845. TAutoFlag UpdatingSessionTabsFlag(FUpdatingSessionTabs);
  6846. int ActiveSessionIndex = Manager->ActiveSessionIndex;
  6847. Configuration->Usage->SetMax(L"MaxOpenedSessions", Manager->Count);
  6848. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 0, 0);
  6849. try
  6850. {
  6851. int PrevTabsWidth = SessionsPageControl->TotalTabsWidth();
  6852. while (SessionsPageControl->PageCount > Manager->Count + 1)
  6853. {
  6854. delete SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6855. }
  6856. for (int Index = 0; Index <= Manager->Count; Index++)
  6857. {
  6858. TThemeTabSheet * TabSheet;
  6859. if (Index >= SessionsPageControl->PageCount)
  6860. {
  6861. TabSheet = new TThemeTabSheet(SessionsPageControl);
  6862. TabSheet->PageControl = SessionsPageControl;
  6863. }
  6864. else
  6865. {
  6866. TabSheet = SessionsPageControl->Pages[Index];
  6867. }
  6868. bool IsSessionTab = (Index < Manager->Count);
  6869. if (IsSessionTab)
  6870. {
  6871. TTerminal * Terminal = Manager->Sessions[Index];
  6872. TabSheet->Tag = reinterpret_cast<int>(Terminal);
  6873. TabSheet->CaptionTruncation = WinConfiguration->SessionTabCaptionTruncation ? tttEllipsis : tttNone;
  6874. UpdateSessionTab(TabSheet);
  6875. }
  6876. else
  6877. {
  6878. TabSheet->Tag = 0; // not really needed
  6879. TabSheet->Shadowed = false;
  6880. TabSheet->Button = SupportsLocalBrowser() ? ttbDropDown : ttbNone;
  6881. TabSheet->CaptionTruncation = GetNewTabTabCaptionTruncation();
  6882. // We know that we are at the last page, otherwise we could not call this (it assumes that new session tab is the last one)
  6883. UpdateNewTabTab();
  6884. }
  6885. }
  6886. // Prevent flicker on the right side where scrolling buttons would be, unless really needed
  6887. if (ForceTruncationUpdate || (SessionsPageControl->TotalTabsWidth() != PrevTabsWidth))
  6888. {
  6889. SessionsPageControl->UpdateTabsCaptionTruncation();
  6890. }
  6891. }
  6892. __finally
  6893. {
  6894. SendMessage(SessionsPageControl->Handle, WM_SETREDRAW, 1, 0);
  6895. }
  6896. SessionsPageControl->ActivePageIndex = ActiveSessionIndex;
  6897. }
  6898. //---------------------------------------------------------------------------
  6899. TThemeTabCaptionTruncation TCustomScpExplorerForm::GetNewTabTabCaptionTruncation()
  6900. {
  6901. return WinConfiguration->SessionTabCaptionTruncation ? tttNoText : tttNone;
  6902. }
  6903. //---------------------------------------------------------------------------
  6904. UnicodeString TCustomScpExplorerForm::GetNewTabTabCaption()
  6905. {
  6906. return StripHotkey(StripTrailingPunctuation(NonVisualDataModule->NewTabAction->Caption));
  6907. }
  6908. //---------------------------------------------------------------------------
  6909. TThemeTabSheet * TCustomScpExplorerForm::GetNewTabTab()
  6910. {
  6911. return SessionsPageControl->Pages[SessionsPageControl->PageCount - 1];
  6912. }
  6913. //---------------------------------------------------------------------------
  6914. void __fastcall TCustomScpExplorerForm::UpdateNewTabTab()
  6915. {
  6916. TThemeTabSheet * TabSheet = GetNewTabTab();
  6917. UnicodeString TabCaption;
  6918. if (WinConfiguration->SelectiveToolbarText)
  6919. {
  6920. TabCaption = GetNewTabTabCaption();
  6921. }
  6922. TabSheet->BaseCaption = TabCaption;
  6923. TabSheet->ImageIndex = GetNewTabTabImageIndex(osCurrent);
  6924. }
  6925. //---------------------------------------------------------------------------
  6926. TManagedTerminal * __fastcall TCustomScpExplorerForm::GetSessionTabSession(TTabSheet * TabSheet)
  6927. {
  6928. return reinterpret_cast<TManagedTerminal *>(TabSheet->Tag);
  6929. }
  6930. //---------------------------------------------------------------------------
  6931. UnicodeString TCustomScpExplorerForm::GetLocalBrowserSessionTitle(TManagedTerminal *)
  6932. {
  6933. DebugFail();
  6934. return UnicodeString();
  6935. }
  6936. //---------------------------------------------------------------------------
  6937. void TCustomScpExplorerForm::UpdateSessionTab(TThemeTabSheet * TabSheet)
  6938. {
  6939. if (DebugAlwaysTrue(TabSheet != NULL))
  6940. {
  6941. TManagedTerminal * ASession = GetSessionTabSession(TabSheet);
  6942. if (DebugAlwaysTrue(ASession != NULL))
  6943. {
  6944. TColor Color = (ASession == Terminal) ? FSessionColor : ASession->StateData->Color;
  6945. if (ASession->LocalBrowser)
  6946. {
  6947. TabSheet->ImageIndex = FLocalBrowserTabImageIndex;
  6948. }
  6949. else
  6950. {
  6951. TabSheet->ImageIndex = AddSessionColor(Color);
  6952. }
  6953. TTerminalManager * Manager = TTerminalManager::Instance();
  6954. TabSheet->Shadowed = !ASession->Active && !ASession->LocalBrowser;
  6955. TabSheet->Button = CanCloseSession(ASession) ? ttbClose : ttbNone;
  6956. TabSheet->BaseCaption = Manager->GetSessionTitle(ASession, true);
  6957. }
  6958. }
  6959. }
  6960. //---------------------------------------------------------------------------
  6961. bool TCustomScpExplorerForm::CanCloseSession(TManagedTerminal * Session)
  6962. {
  6963. return !Session->LocalBrowser || (TTerminalManager::Instance()->Count > 1);
  6964. }
  6965. //---------------------------------------------------------------------------
  6966. bool __fastcall TCustomScpExplorerForm::SessionTabSwitched()
  6967. {
  6968. DebugAssert(SessionsPageControl->ActivePage != NULL);
  6969. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->ActivePage);
  6970. bool Result = (Session != NULL);
  6971. if (Result)
  6972. {
  6973. TTerminalManager::Instance()->ActiveSession = Session;
  6974. }
  6975. else
  6976. {
  6977. try
  6978. {
  6979. NewTab();
  6980. }
  6981. __finally
  6982. {
  6983. SessionListChanged();
  6984. }
  6985. FSessionsPageControlNewTabTime = Now();
  6986. }
  6987. return Result;
  6988. }
  6989. //---------------------------------------------------------------------------
  6990. void __fastcall TCustomScpExplorerForm::SessionsPageControlChange(TObject * /*Sender*/)
  6991. {
  6992. TWindowLock Lock(this);
  6993. SessionTabSwitched();
  6994. }
  6995. //---------------------------------------------------------------------------
  6996. void __fastcall TCustomScpExplorerForm::TransferListChange(TObject * Sender)
  6997. {
  6998. TTBXStringList * TransferList = dynamic_cast<TTBXStringList *>(Sender);
  6999. DebugAssert(TransferList != NULL);
  7000. UnicodeString Name;
  7001. if (TransferList->ItemIndex <= 0)
  7002. {
  7003. Name = L"";
  7004. }
  7005. else
  7006. {
  7007. Name = GUIConfiguration->CopyParamList->Names[TransferList->ItemIndex - 1];
  7008. }
  7009. if (FCopyParamAutoSelected.IsEmpty())
  7010. {
  7011. // if previous preset was not autoselected, make new preset the "default"
  7012. FCopyParamDefault = Name;
  7013. }
  7014. GUIConfiguration->CopyParamCurrent = Name;
  7015. }
  7016. //---------------------------------------------------------------------------
  7017. void __fastcall TCustomScpExplorerForm::UpdateTransferLabel()
  7018. {
  7019. // sanity check
  7020. bool ExistingPreset =
  7021. (FTransferListHoverIndex >= 0) &&
  7022. (FTransferListHoverIndex < 1 + GUIConfiguration->CopyParamList->Count);
  7023. DebugAssert(ExistingPreset);
  7024. if (ExistingPreset)
  7025. {
  7026. HDC DC = GetDC(0);
  7027. TCanvas * Canvas = new TCanvas();
  7028. try
  7029. {
  7030. Canvas->Handle = DC;
  7031. Canvas->Font = GetToolbarFont(this);
  7032. UnicodeString Name;
  7033. if (FTransferListHoverIndex == 0)
  7034. {
  7035. Name = L"";
  7036. }
  7037. else
  7038. {
  7039. Name = GUIConfiguration->CopyParamList->Names[FTransferListHoverIndex - 1];
  7040. }
  7041. TTBXLabelItem * TransferLabel = dynamic_cast<TTBXLabelItem*>(
  7042. static_cast<TComponent*>(GetComponent(fcTransferLabel)));
  7043. TTBXStringList * TransferList = dynamic_cast<TTBXStringList*>(
  7044. static_cast<TObject*>(GetComponent(fcTransferList)));
  7045. UnicodeString InfoStr =
  7046. GUIConfiguration->CopyParamPreset[Name].
  7047. GetInfoStr(L"; ",
  7048. FLAGMASK(HasActiveTerminal(), Terminal->UsableCopyParamAttrs(0).General));
  7049. int MaxWidth = TransferList->MinWidth - (2 * TransferLabel->Margin) - ScaleByTextHeight(this, 10);
  7050. if (Canvas->TextExtent(InfoStr).cx > MaxWidth)
  7051. {
  7052. while (Canvas->TextExtent(InfoStr + Ellipsis).cx > MaxWidth)
  7053. {
  7054. InfoStr.SetLength(InfoStr.Length() - 1);
  7055. }
  7056. InfoStr += Ellipsis;
  7057. }
  7058. // UpdateCaption does not cause invalidation of whole submenu, while
  7059. // setting Caption property does.
  7060. // also it probably does not resize the label, even if necessary
  7061. // (we do not want that anyway)
  7062. TransferLabel->UpdateCaption(InfoStr);
  7063. }
  7064. __finally
  7065. {
  7066. Canvas->Handle = NULL;
  7067. ReleaseDC(0, DC);
  7068. delete Canvas;
  7069. }
  7070. }
  7071. }
  7072. //---------------------------------------------------------------------------
  7073. void __fastcall TCustomScpExplorerForm::TransferListDrawItem(
  7074. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, const TRect & /*ARect*/,
  7075. int /*AIndex*/, int AHoverIndex, bool & /*DrawDefault*/)
  7076. {
  7077. if (FTransferListHoverIndex != AHoverIndex)
  7078. {
  7079. FTransferListHoverIndex = AHoverIndex;
  7080. UpdateTransferLabel();
  7081. }
  7082. }
  7083. //---------------------------------------------------------------------------
  7084. void __fastcall TCustomScpExplorerForm::WMAppCommand(TMessage & Message)
  7085. {
  7086. int Command = GET_APPCOMMAND_LPARAM(Message.LParam);
  7087. TShiftState Shift = KeyDataToShiftState(GET_KEYSTATE_LPARAM(Message.LParam));
  7088. if ((Shift * (TShiftState() << ssShift << ssAlt << ssCtrl)).Empty())
  7089. {
  7090. if (Command == APPCOMMAND_BROWSER_FAVORITES)
  7091. {
  7092. if (!NonVisualDataModule->Busy)
  7093. {
  7094. OpenDirectory(GetSide(osCurrent));
  7095. }
  7096. Message.Result = 1;
  7097. }
  7098. else
  7099. {
  7100. TForm::Dispatch(&Message);
  7101. }
  7102. }
  7103. else
  7104. {
  7105. TForm::Dispatch(&Message);
  7106. }
  7107. }
  7108. //---------------------------------------------------------------------------
  7109. void __fastcall TCustomScpExplorerForm::CMDialogChar(TMessage & AMessage)
  7110. {
  7111. TCMDialogChar & Message = reinterpret_cast<TCMDialogChar &>(AMessage);
  7112. if ((FIgnoreNextDialogChar != 0) &&
  7113. (towupper(Message.CharCode) == towupper(FIgnoreNextDialogChar)))
  7114. {
  7115. Message.Result = 1;
  7116. }
  7117. else
  7118. {
  7119. TForm::Dispatch(&Message);
  7120. }
  7121. FIgnoreNextDialogChar = 0;
  7122. }
  7123. //---------------------------------------------------------------------------
  7124. void __fastcall TCustomScpExplorerForm::WMSysCommand(TMessage & Message)
  7125. {
  7126. // The four low-order bits are used internally by Windows
  7127. unsigned int Cmd = (Message.WParam & 0xFFF0);
  7128. // SC_RESTORE, SC_MAXIMIZE, SC_MINIMIZE - buttons on windows title
  7129. // SC_DEFAULT - double click on windows title (does not work, at least on WinXP)
  7130. // 61730 - restore thru double click - undocumented
  7131. // 61490 - maximize thru double click - undocumented
  7132. if ((Cmd == SC_RESTORE) || (Cmd == SC_MAXIMIZE) ||
  7133. (Cmd == SC_MINIMIZE) || (Cmd == SC_DEFAULT))
  7134. {
  7135. SysResizing(Cmd);
  7136. }
  7137. TForm::Dispatch(&Message);
  7138. }
  7139. //---------------------------------------------------------------------------
  7140. void __fastcall TCustomScpExplorerForm::WMQueryEndSession(TMessage & Message)
  7141. {
  7142. AppLog(L"Windows session end query");
  7143. // We were actually never able to make ENDSESSION_CRITICAL happen.
  7144. // Also there no point returning TRUE as we are not able to
  7145. // handle the abrupt termination caused by subsequent WM_ENDSESSION cleanly.
  7146. // Hence the process termination might be safer :)
  7147. if ((Message.LParam != ENDSESSION_CRITICAL) &&
  7148. (((FQueue != NULL) && !FQueue->IsEmpty) || (FProgressForm != NULL)))
  7149. {
  7150. Message.Result = FALSE;
  7151. }
  7152. else
  7153. {
  7154. Message.Result = TRUE;
  7155. }
  7156. // Do not call default handling as that triggers OnCloseQuery,
  7157. // where our implementation will popup confirmation dialogs, what we do not want,
  7158. // as per Vista guidelines:
  7159. // https://learn.microsoft.com/en-us/windows/win32/shutdown/shutting-down
  7160. }
  7161. //---------------------------------------------------------------------------
  7162. void __fastcall TCustomScpExplorerForm::WMEndSession(TWMEndSession & Message)
  7163. {
  7164. AppLog(L"Windows session end");
  7165. if (Message.EndSession && IsApplicationMinimized())
  7166. {
  7167. // WORKAROUND
  7168. // TApplication.WndProc() calls Application.Terminate() before Halt(),
  7169. // when it receives WM_ENDSESSION,
  7170. // but that sometimes (particularly when application is minimized) cause crashes.
  7171. // Crash popups message that blocks log off.
  7172. // Obviously application cannot shutdown cleanly after WM_ENDSESSION,
  7173. // so we call ExitProcess() immediately, not even trying to cleanup.
  7174. // It still causes beep, so there's likely some popup, but it does not block
  7175. // log off.
  7176. ExitProcess(0);
  7177. }
  7178. TForm::Dispatch(&Message);
  7179. }
  7180. #ifdef _DEBUG
  7181. //---------------------------------------------------------------------------
  7182. void __fastcall TCustomScpExplorerForm::WMWindowPosChanged(TWMWindowPosMsg & Message)
  7183. {
  7184. TForm::Dispatch(&Message);
  7185. }
  7186. #endif
  7187. //---------------------------------------------------------------------------
  7188. void __fastcall TCustomScpExplorerForm::SysResizing(unsigned int /*Cmd*/)
  7189. {
  7190. }
  7191. //---------------------------------------------------------------------------
  7192. void __fastcall TCustomScpExplorerForm::DoShow()
  7193. {
  7194. // Called from TCustomScpExplorerForm::CMShowingChanged
  7195. // only now are the controls resized finally, so the size constraints
  7196. // will not conflict with possibly very small window size
  7197. RestoreFormParams();
  7198. // This indicates that the form was rescaled after parameters were loaded and
  7199. // as most probably the parameters were actually saved with the current form scaling
  7200. // (windows was the last time likely closed on the same monitor, where it is starting now),
  7201. // rescaling happened twice already. Reload the parameters, as now they likely won't need any scaling
  7202. // and no rounding problems will occur.
  7203. // See also RestoreForm.
  7204. // (we should be safe to call RestoreParams unconditionally)
  7205. if (PixelsPerInch != Screen->PixelsPerInch)
  7206. {
  7207. RestoreParams();
  7208. }
  7209. FixControlsPlacement();
  7210. if (Position == poDefaultPosOnly)
  7211. {
  7212. CutFormToDesktop(this);
  7213. }
  7214. TForm::DoShow();
  7215. FSessionsDragDropFilesEx->DragDropControl = SessionsPageControl;
  7216. FQueueDragDropFilesEx->DragDropControl = QueueView3;
  7217. // This was previously in NeedSession, where other related code is.
  7218. // But that is called from CMShowingChanged, when the window is already visible and the local-local window state
  7219. // unpleasantly shows briefly.
  7220. if ((ManagedSession == NULL) &&
  7221. !WinConfiguration->ShowLoginWhenNoSession &&
  7222. WinConfiguration->AutoSaveWorkspace && !WinConfiguration->AutoWorkspace.IsEmpty() &&
  7223. // This detects if workspace was saved the last time the main widow was closed
  7224. SameText(WinConfiguration->LastStoredSession, WinConfiguration->AutoWorkspace))
  7225. {
  7226. DoOpenFolderOrWorkspace(WinConfiguration->AutoWorkspace, false, true);
  7227. Configuration->Usage->Inc(L"OpenedWorkspacesAuto");
  7228. }
  7229. // Before main window displays
  7230. if (ManagedSession == NULL)
  7231. {
  7232. StartingWithoutSession();
  7233. }
  7234. UpdatePixelsPerInchMainWindowCounter();
  7235. FShowing = true;
  7236. }
  7237. //---------------------------------------------------------------------------
  7238. void __fastcall TCustomScpExplorerForm::UpdatePixelsPerInchMainWindowCounter()
  7239. {
  7240. Configuration->Usage->Set(L"PixelsPerInchMainWindow", PixelsPerInch);
  7241. }
  7242. //---------------------------------------------------------------------------
  7243. void __fastcall TCustomScpExplorerForm::StartingWithoutSession()
  7244. {
  7245. SessionListChanged();
  7246. InitStatusBar();
  7247. UpdateControls();
  7248. }
  7249. //---------------------------------------------------------------------------
  7250. void __fastcall TCustomScpExplorerForm::PopupTrayBalloon(TTerminal * Terminal,
  7251. const UnicodeString & Str, TQueryType Type, Exception * E, unsigned int Seconds,
  7252. TNotifyEvent OnBalloonClick, TObject * UserData)
  7253. {
  7254. bool Do;
  7255. UnicodeString Message;
  7256. if (E == NULL)
  7257. {
  7258. Message = Str;
  7259. Do = true;
  7260. }
  7261. else
  7262. {
  7263. Do = ExceptionMessage(E, Message);
  7264. }
  7265. if (Do && WinConfiguration->BalloonNotifications)
  7266. {
  7267. UnicodeString Title;
  7268. if ((Terminal == NULL) && (Type == qtInformation) && ExtractMainInstructions(Message, Title))
  7269. {
  7270. Message = TrimLeft(Message);
  7271. }
  7272. else
  7273. {
  7274. Message = UnformatMessage(Message);
  7275. const ResourceString * Captions[] = { &_SMsgDlgConfirm, &_SMsgDlgWarning,
  7276. &_SMsgDlgError, &_SMsgDlgInformation, NULL };
  7277. Title = LoadResourceString(Captions[Type]);
  7278. if (Terminal != NULL)
  7279. {
  7280. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal->PrimaryTerminal));
  7281. Title = TTerminalManager::Instance()->GetSessionTitle(Session, true) + TitleSeparator + Title;
  7282. }
  7283. }
  7284. if (Seconds == 0)
  7285. {
  7286. Seconds = WinConfiguration->NotificationsTimeout;
  7287. }
  7288. FTrayIcon->PopupBalloon(Title, Message, Type, Seconds * MSecsPerSec, OnBalloonClick, UserData);
  7289. }
  7290. }
  7291. //---------------------------------------------------------------------------
  7292. unsigned int __fastcall TCustomScpExplorerForm::MoreMessageDialog(const UnicodeString Message,
  7293. TStrings * MoreMessages, TQueryType Type, unsigned int Answers,
  7294. UnicodeString HelpKeyword, const TMessageParams * Params,
  7295. TTerminal * Terminal)
  7296. {
  7297. if (((WinConfiguration->ContinueOnError && (FErrorList != NULL)) ||
  7298. (FOnFeedSynchronizeError != NULL)) &&
  7299. (Params != NULL) && (Params->Params & mpAllowContinueOnError) )
  7300. {
  7301. if (FOnFeedSynchronizeError != NULL)
  7302. {
  7303. FOnFeedSynchronizeError(Message, MoreMessages, Type, HelpKeyword);
  7304. }
  7305. else
  7306. {
  7307. DebugAssert(FErrorList != NULL);
  7308. TStringList * MoreMessagesCopy = NULL;
  7309. if (MoreMessages)
  7310. {
  7311. MoreMessagesCopy = new TStringList();
  7312. MoreMessagesCopy->Assign(MoreMessages);
  7313. }
  7314. FErrorList->AddObject(Message, MoreMessagesCopy);
  7315. }
  7316. PopupTrayBalloon(Terminal, Message, Type);
  7317. return ContinueAnswer(Answers);
  7318. }
  7319. else
  7320. {
  7321. bool UseBalloon = FTrayIcon->Visible;
  7322. if (UseBalloon)
  7323. {
  7324. PopupTrayBalloon(Terminal, Message, Type);
  7325. }
  7326. unsigned int Result;
  7327. try
  7328. {
  7329. Result = ::MoreMessageDialog(Message, MoreMessages, Type, Answers, HelpKeyword, Params);
  7330. }
  7331. __finally
  7332. {
  7333. // cancel only balloon we popped up, otherwise we may cancel notification
  7334. // balloon that was there before the message dialog
  7335. // (such as "dd confirmation opt in balloon)
  7336. if (UseBalloon)
  7337. {
  7338. FTrayIcon->CancelBalloon();
  7339. }
  7340. }
  7341. return Result;
  7342. }
  7343. }
  7344. //---------------------------------------------------------------------------
  7345. void __fastcall TCustomScpExplorerForm::ShowExtendedException(
  7346. TTerminal * Terminal, Exception * E)
  7347. {
  7348. if (FTrayIcon->Visible)
  7349. {
  7350. PopupTrayBalloon(Terminal, L"", qtError, E);
  7351. }
  7352. // particularly prevent opening new session from jump list,
  7353. // while exception is shown
  7354. NonVisualDataModule->StartBusy();
  7355. try
  7356. {
  7357. ShowExtendedExceptionEx(Terminal, E);
  7358. }
  7359. __finally
  7360. {
  7361. NonVisualDataModule->EndBusy();
  7362. FTrayIcon->CancelBalloon();
  7363. }
  7364. }
  7365. //---------------------------------------------------------------------------
  7366. void __fastcall TCustomScpExplorerForm::SessionReady()
  7367. {
  7368. InitStatusBar();
  7369. // cannot rely on active page being page for active terminal,
  7370. // as it can happen that active page is the "new session" page
  7371. // (e.g. when reconnecting active terminal, while login dialog
  7372. // invoked from "new session" page is modal)
  7373. int ActiveSessionIndex = TTerminalManager::Instance()->ActiveSessionIndex;
  7374. UpdateSessionTab(SessionsPageControl->Pages[ActiveSessionIndex]);
  7375. }
  7376. //---------------------------------------------------------------------------
  7377. void __fastcall TCustomScpExplorerForm::InactiveTerminalException(
  7378. TTerminal * Terminal, Exception * E)
  7379. {
  7380. Notify(Terminal, L"", qtError, false, NULL, NULL, E);
  7381. if (!Terminal->Active)
  7382. {
  7383. int Index = TTerminalManager::Instance()->IndexOf(Terminal);
  7384. if (DebugAlwaysTrue((Index >= 0) && (Index < SessionsPageControl->PageCount)))
  7385. {
  7386. UpdateSessionTab(SessionsPageControl->Pages[Index]);
  7387. }
  7388. }
  7389. }
  7390. //---------------------------------------------------------------------------
  7391. void __fastcall TCustomScpExplorerForm::Notify(TTerminal * Terminal,
  7392. UnicodeString Message, TQueryType Type,
  7393. bool Important, TNotifyEvent OnClick, TObject * UserData, Exception * E)
  7394. {
  7395. if ((E == NULL) ||
  7396. ExceptionMessage(E, Message))
  7397. {
  7398. unsigned int Seconds = WinConfiguration->NotificationsTimeout;
  7399. if (Important)
  7400. {
  7401. Seconds *= 5;
  7402. }
  7403. UnicodeString NoteMessage(UnformatMessage(Message));
  7404. if (Terminal != NULL)
  7405. {
  7406. TManagedTerminal * Session = DebugNotNull(dynamic_cast<TManagedTerminal *>(Terminal));
  7407. NoteMessage = FORMAT(L"%s: %s",
  7408. (TTerminalManager::Instance()->GetSessionTitle(Session, true), NoteMessage));
  7409. }
  7410. if (WinConfiguration->BalloonNotifications)
  7411. {
  7412. AddNote(NoteMessage);
  7413. PopupTrayBalloon(Terminal, Message, Type, NULL, Seconds, OnClick, UserData);
  7414. }
  7415. else
  7416. {
  7417. FlashOnBackground();
  7418. PostNote(NoteMessage, Seconds, OnClick, UserData);
  7419. }
  7420. }
  7421. }
  7422. //---------------------------------------------------------------------------
  7423. void __fastcall TCustomScpExplorerForm::QueueEmptyNoteClicked(TObject * Sender)
  7424. {
  7425. RestoreApp();
  7426. TTerminalNoteData * TerminalNoteData = dynamic_cast<TTerminalNoteData *>(Sender);
  7427. if (DebugAlwaysTrue(TerminalNoteData != NULL) &&
  7428. !NonVisualDataModule->Busy)
  7429. {
  7430. TManagedTerminal * Terminal = TerminalNoteData->Terminal;
  7431. TTerminalManager::Instance()->ActiveSession = Terminal;
  7432. if (!ComponentVisible[fcQueueView])
  7433. {
  7434. ToggleQueueVisibility();
  7435. GoToQueue();
  7436. }
  7437. }
  7438. }
  7439. //---------------------------------------------------------------------------
  7440. void __fastcall TCustomScpExplorerForm::QueueEvent(TManagedTerminal * ATerminal,
  7441. TTerminalQueue * /*Queue*/, TQueueEvent Event)
  7442. {
  7443. UnicodeString Message;
  7444. TNotifyEvent OnClick = NULL;
  7445. TObject * UserData = NULL;
  7446. bool QueueInvisible = !ComponentVisible[fcQueueView] || IsApplicationMinimized();
  7447. switch (Event)
  7448. {
  7449. case qeEmptyButMonitored:
  7450. if ((ATerminal != Terminal) || QueueInvisible)
  7451. {
  7452. Message = LoadStr(BALLOON_QUEUE_EMPTY);
  7453. OnClick = QueueEmptyNoteClicked;
  7454. TTerminalNoteData * TerminalNoteData = new TTerminalNoteData();
  7455. TerminalNoteData->Terminal = ATerminal;
  7456. UserData = TerminalNoteData;
  7457. }
  7458. break;
  7459. case qeEmpty:
  7460. OperationComplete(ATerminal->QueueOperationStart);
  7461. break;
  7462. case qePendingUserAction:
  7463. if ((ATerminal != Terminal) ||
  7464. (QueueInvisible && !IsQueueAutoPopup()))
  7465. {
  7466. Message = LoadStr(BALLOON_QUEUE_USER_ACTION);
  7467. }
  7468. break;
  7469. default:
  7470. DebugFail();
  7471. }
  7472. if (!Message.IsEmpty())
  7473. {
  7474. Notify(ATerminal, Message, qtInformation, false, OnClick, UserData);
  7475. }
  7476. }
  7477. //---------------------------------------------------------------------------
  7478. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDragFileList(
  7479. TObject * /*Sender*/, TFileList * FileList, bool & Created)
  7480. {
  7481. if (FDDExtMapFile != NULL)
  7482. {
  7483. CloseHandle(FDDExtMapFile);
  7484. FDDExtMapFile = NULL;
  7485. }
  7486. if (WinConfiguration->DDFakeFile)
  7487. {
  7488. DDFakeFileInitDrag(FileList, Created);
  7489. }
  7490. }
  7491. //---------------------------------------------------------------------------
  7492. void __fastcall TCustomScpExplorerForm::DDFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  7493. {
  7494. if (DebugAlwaysTrue(!FDragFakeDirectory.IsEmpty()) &&
  7495. SameText(ExtractFileName(FileName), ExtractFileName(FDragFakeDirectory)))
  7496. {
  7497. FFakeFileDropTarget = FileName;
  7498. }
  7499. }
  7500. //---------------------------------------------------------------------------
  7501. UnicodeString __fastcall TCustomScpExplorerForm::CreateFakeTransferDirectory()
  7502. {
  7503. UnicodeString Result = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir());
  7504. if (!ForceDirectories(ApiPath(Result)))
  7505. {
  7506. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (Result)));
  7507. }
  7508. FileSetAttr(ApiPath(Result), faHidden);
  7509. return Result;
  7510. }
  7511. //---------------------------------------------------------------------------
  7512. void __fastcall TCustomScpExplorerForm::DDFakeFileInitDrag(TFileList * FileList,
  7513. bool & Created)
  7514. {
  7515. FFakeFileDropTarget = UnicodeString();
  7516. FDragFakeDirectory = CreateFakeTransferDirectory();
  7517. FileList->AddItem(NULL, FDragFakeDirectory);
  7518. Created = true;
  7519. if (!WinConfiguration->IsDDExtRunning() || WinConfiguration->IsDDExtBroken())
  7520. {
  7521. FDragFakeMonitors = StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, DDFakeCreated);
  7522. }
  7523. FDDExtMapFile = CreateFileMappingA((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE,
  7524. 0, sizeof(TDragExtCommStruct), AnsiString(DRAG_EXT_MAPPING).c_str());
  7525. {
  7526. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7527. TDragExtCommStruct* CommStruct;
  7528. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7529. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7530. DebugAssert(CommStruct != NULL);
  7531. CommStruct->Version = TDragExtCommStruct::CurrentVersion;
  7532. CommStruct->Dragging = true;
  7533. wcsncpy(CommStruct->DropDest, FDragFakeDirectory.c_str(),
  7534. LENOF(CommStruct->DropDest));
  7535. NULL_TERMINATE(CommStruct->DropDest);
  7536. UnmapViewOfFile(CommStruct);
  7537. }
  7538. }
  7539. //---------------------------------------------------------------------------
  7540. bool __fastcall TCustomScpExplorerForm::RemoteFileControlFileOperation(
  7541. TObject * Sender, TFileOperation Operation, bool NoConfirmation, void * Param)
  7542. {
  7543. bool Result;
  7544. DebugAssert(!IsLocalBrowserMode());
  7545. if (Sender == RemoteDirView)
  7546. {
  7547. Result = ExecuteFileOperation(Operation, osRemote, true, NoConfirmation, Param);
  7548. }
  7549. else
  7550. {
  7551. DebugAssert(Sender == RemoteDriveView);
  7552. TStrings * FileList = RemoteDriveView->DragFileList();
  7553. try
  7554. {
  7555. Result = ExecuteFileOperation(Operation, osRemote, FileList, NoConfirmation, Param);
  7556. }
  7557. __finally
  7558. {
  7559. delete FileList;
  7560. }
  7561. }
  7562. if (FDDTargetControl == RemoteDriveView)
  7563. {
  7564. RemoteDriveView->UpdateDropTarget();
  7565. }
  7566. // foRemoteMove happens when file/dir is dragged within the remote tree view
  7567. // or from tree view to dir view.
  7568. // foMove happens when file/dir is dragged from remote tree view outside of
  7569. // application via dragex
  7570. if (((Operation == foRemoteMove) || (Operation == foMove)) &&
  7571. (DropSourceControl == RemoteDriveView))
  7572. {
  7573. RemoteDriveView->UpdateDropSource();
  7574. }
  7575. return Result;
  7576. }
  7577. //---------------------------------------------------------------------------
  7578. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDEnd(TObject * Sender)
  7579. {
  7580. DebugAssert(!IsLocalBrowserMode());
  7581. // This also handles drops of remote files to queue.
  7582. // Drops of local files (uploads) are handled in QueueDDProcessDropped.
  7583. SAFE_DESTROY(FDDFileList);
  7584. if (!FFakeFileDropTarget.IsEmpty())
  7585. {
  7586. RemoveDir(ApiPath(FFakeFileDropTarget));
  7587. }
  7588. if ((FDDExtMapFile != NULL) || (FDDTargetControl == QueueView3))
  7589. {
  7590. try
  7591. {
  7592. TDragResult DDResult = (Sender == RemoteDirView) ?
  7593. RemoteDirView->LastDDResult : RemoteDriveView->LastDDResult;
  7594. // Focus is moved to the target application,
  7595. // but as we are going to present the UI, we need to steal the focus back.
  7596. // This most likely won't work though (windows does not allow application
  7597. // to steal focus most of the time)
  7598. Application->BringToFront();
  7599. // On older version of Windows we never got drMove here, see also comment below.
  7600. // On Windows 10, we get the "move".
  7601. if ((DDResult == drCopy) || (DDResult == drMove) || (DDResult == drInvalid))
  7602. {
  7603. UnicodeString TargetDirectory;
  7604. TFileOperation Operation;
  7605. // drInvalid may mean drMove, see comment below
  7606. switch (DDResult)
  7607. {
  7608. case drCopy:
  7609. Operation = foCopy;
  7610. break;
  7611. case drMove:
  7612. Operation = foMove;
  7613. break;
  7614. default:
  7615. DebugFail();
  7616. case drInvalid:
  7617. // prefer "copy" for safety
  7618. Operation = FLAGSET(FLastDropEffect, DROPEFFECT_MOVE) ? foMove : foCopy;
  7619. break;
  7620. }
  7621. TTransferOperationParam Param;
  7622. UnicodeString CounterName;
  7623. bool ForceQueue;
  7624. if (!DDGetTarget(Param.TargetDirectory, ForceQueue, CounterName))
  7625. {
  7626. // we get drInvalid both if d&d was intercepted by ddext,
  7627. // and when users drops on no-drop location.
  7628. // we tell the difference by existence of response from ddext,
  7629. // so we ignore absence of response in this case
  7630. if (DDResult != drInvalid)
  7631. {
  7632. // here we know that the extension is installed,
  7633. // as it is checked as soon as drag&drop starts from
  7634. // RemoteFileControlDDCreateDragFileList
  7635. Configuration->Usage->Inc(L"DownloadsDragDropExternalExtTargetUnknown");
  7636. if (!WinConfiguration->DDExtInstalled || WinConfiguration->IsDDExtBroken())
  7637. {
  7638. throw ExtException(NULL, LoadStr(DD_TARGET_UNKNOWN), HELP_DD_TARGET_UNKNOWN);
  7639. }
  7640. else
  7641. {
  7642. throw ExtException(NULL, LoadStr(DRAGEXT_TARGET_UNKNOWN2), HELP_DRAGEXT_TARGET_UNKNOWN);
  7643. }
  7644. }
  7645. }
  7646. else
  7647. {
  7648. // download using fake file
  7649. Param.Temp = false;
  7650. Param.DragDrop = true;
  7651. if (ForceQueue)
  7652. {
  7653. Param.Queue = asOn;
  7654. }
  7655. if (Sender == RemoteDirView)
  7656. {
  7657. Param.Options = FLAGMASK(SelectedAllFilesInDirView(RemoteDirView), coAllFiles);
  7658. }
  7659. if (RemoteFileControlFileOperation(Sender, Operation,
  7660. (WinConfiguration->DDTransferConfirmation == asOff), &Param))
  7661. {
  7662. Configuration->Usage->Inc(CounterName);
  7663. }
  7664. }
  7665. }
  7666. }
  7667. __finally
  7668. {
  7669. CloseHandle(FDDExtMapFile);
  7670. FDDExtMapFile = NULL;
  7671. delete FDragFakeMonitors;
  7672. FDragFakeMonitors = NULL;
  7673. RemoveDir(ApiPath(FDragFakeDirectory));
  7674. FDragFakeDirectory = L"";
  7675. FFakeFileDropTarget = UnicodeString();
  7676. }
  7677. }
  7678. if (FDragDropSshTerminate.get() != NULL)
  7679. {
  7680. FDragDropSshTerminate->Rethrow();
  7681. }
  7682. }
  7683. //---------------------------------------------------------------------------
  7684. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDGiveFeedback(
  7685. TObject * /*Sender*/, int dwEffect, HRESULT & /*Result*/)
  7686. {
  7687. // Remember drop effect so we know (when user drops files), if we copy or move
  7688. FLastDropEffect = dwEffect;
  7689. }
  7690. //---------------------------------------------------------------------------
  7691. bool __fastcall TCustomScpExplorerForm::DDGetTarget(
  7692. UnicodeString & Directory, bool & ForceQueue, UnicodeString & CounterName)
  7693. {
  7694. bool Result;
  7695. if (FDDTargetControl == QueueView3)
  7696. {
  7697. Directory = DefaultDownloadTargetDirectory();
  7698. Result = true;
  7699. CounterName = L"DownloadsDragDropQueue";
  7700. ForceQueue = true;
  7701. }
  7702. else if (!FFakeFileDropTarget.IsEmpty())
  7703. {
  7704. Directory = ExcludeTrailingBackslash(ExtractFilePath(FFakeFileDropTarget));
  7705. Result = true;
  7706. ForceQueue = false;
  7707. CounterName = L"DownloadsDragDropFakeFile";
  7708. }
  7709. else
  7710. {
  7711. ForceQueue = false;
  7712. Enabled = false;
  7713. try
  7714. {
  7715. int Timer = 0;
  7716. Result = false;
  7717. while (!Result && (Timer < WinConfiguration->DDExtTimeout))
  7718. {
  7719. {
  7720. TMutexGuard Guard(FDDExtMutex, DRAGEXT_MUTEX_RELEASE_TIMEOUT);
  7721. TDragExtCommStruct* CommStruct;
  7722. CommStruct = static_cast<TDragExtCommStruct*>(MapViewOfFile(FDDExtMapFile,
  7723. FILE_MAP_ALL_ACCESS, 0, 0, 0));
  7724. DebugAssert(CommStruct != NULL);
  7725. Result = !CommStruct->Dragging;
  7726. if (Result)
  7727. {
  7728. Directory = ExtractFilePath(CommStruct->DropDest);
  7729. CounterName = L"DownloadsDragDropExternalExt";
  7730. }
  7731. UnmapViewOfFile(CommStruct);
  7732. }
  7733. if (!Result)
  7734. {
  7735. Sleep(50);
  7736. Timer += 50;
  7737. Application->ProcessMessages();
  7738. }
  7739. }
  7740. }
  7741. __finally
  7742. {
  7743. Enabled = true;
  7744. }
  7745. }
  7746. return Result;
  7747. }
  7748. //---------------------------------------------------------------------------
  7749. void __fastcall TCustomScpExplorerForm::AddDelayedDirectoryDeletion(
  7750. const UnicodeString TempDir, int SecDelay)
  7751. {
  7752. TDateTime Alarm = IncSecond(Now(), SecDelay);
  7753. FDelayedDeletionList->AddObject(TempDir, reinterpret_cast<TObject*>(Alarm.FileDate()));
  7754. if (FDelayedDeletionTimer == NULL)
  7755. {
  7756. DebugAssert(HandleAllocated());
  7757. FDelayedDeletionTimer = new TTimer(this);
  7758. FDelayedDeletionTimer->Interval = 10000;
  7759. FDelayedDeletionTimer->OnTimer = DoDelayedDeletion;
  7760. }
  7761. else
  7762. {
  7763. FDelayedDeletionTimer->Enabled = true;
  7764. }
  7765. }
  7766. //---------------------------------------------------------------------------
  7767. void __fastcall TCustomScpExplorerForm::DoDelayedDeletion(TObject * Sender)
  7768. {
  7769. DebugAssert(FDelayedDeletionList != NULL);
  7770. TDateTime N = Now();
  7771. TDateTime Alert;
  7772. UnicodeString Directory;
  7773. for (int Index = FDelayedDeletionList->Count-1; Index >= 0; Index--)
  7774. {
  7775. Alert = FileDateToDateTime(reinterpret_cast<int>(FDelayedDeletionList->Objects[Index]));
  7776. if ((N >= Alert) || (Sender == NULL))
  7777. {
  7778. Directory = FDelayedDeletionList->Strings[Index];
  7779. if (RecursiveDeleteFile(ExcludeTrailingBackslash(Directory)))
  7780. {
  7781. FDelayedDeletionList->Delete(Index);
  7782. }
  7783. }
  7784. }
  7785. if (FDelayedDeletionList->Count == 0)
  7786. {
  7787. FDelayedDeletionTimer->Enabled = false;
  7788. }
  7789. }
  7790. //---------------------------------------------------------------------------
  7791. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDTargetDrop()
  7792. {
  7793. DebugAssert(!IsLocalBrowserMode());
  7794. if (IsFileControl(FDDTargetControl, osRemote) ||
  7795. (FDDTargetControl == SessionsPageControl))
  7796. {
  7797. TManagedTerminal * TargetTerminal = NULL;
  7798. TFileOperation Operation = foNone;
  7799. if (FDDTargetControl == SessionsPageControl)
  7800. {
  7801. TPoint Point = SessionsPageControl->ScreenToClient(Mouse->CursorPos);
  7802. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  7803. // do not allow dropping on local-local, disconnected and the "+" tab (see also SessionsDDProcessDropped)
  7804. TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  7805. if (IsActiveTerminal(TargetTerminal) && DebugAlwaysTrue(!TargetTerminal->LocalBrowser))
  7806. {
  7807. if ((FLastDropEffect == DROPEFFECT_MOVE) &&
  7808. (TargetTerminal == TTerminalManager::Instance()->ActiveTerminal))
  7809. {
  7810. Operation = foRemoteMove;
  7811. }
  7812. else
  7813. {
  7814. Operation = foRemoteCopy;
  7815. }
  7816. }
  7817. }
  7818. else
  7819. {
  7820. if (FLastDropEffect == DROPEFFECT_MOVE)
  7821. {
  7822. Operation = foRemoteMove;
  7823. }
  7824. else if (FLastDropEffect == DROPEFFECT_COPY)
  7825. {
  7826. Operation = foRemoteCopy;
  7827. }
  7828. }
  7829. if (Operation != foNone)
  7830. {
  7831. RemoteFileControlFileOperation(DropSourceControl,
  7832. Operation, (WinConfiguration->DDTransferConfirmation == asOff), TargetTerminal);
  7833. }
  7834. // abort drag&drop
  7835. Abort();
  7836. }
  7837. else if ((FDDExtMapFile == NULL) && (FLastDropEffect != DROPEFFECT_NONE) &&
  7838. // Drops of remote files to queue are handled in RemoteFileControlDDEnd
  7839. (FDDTargetControl != QueueView3))
  7840. {
  7841. DebugAssert(!FDragTempDir.IsEmpty());
  7842. TTransferType Type;
  7843. UnicodeString TempDir = FDragTempDir;
  7844. // We clear FDragTempDir before calling
  7845. // just in case it fail (raises exception)
  7846. FDragTempDir = L"";
  7847. Type = (FLastDropEffect & DROPEFFECT_MOVE ? ttMove : Type = ttCopy);
  7848. TGUICopyParamType CopyParams = GUIConfiguration->CurrentCopyParam;
  7849. // empty directory parameter means temp directory -> don't display it!
  7850. UnicodeString TargetDir = L"";
  7851. int Options = 0;
  7852. if (!CopyParamDialog(tdToLocal, Type, true, FDDFileList,
  7853. TargetDir, CopyParams, (WinConfiguration->DDTransferConfirmation != asOff), true, Options))
  7854. {
  7855. Abort();
  7856. }
  7857. // TargetDir is set when dropped on local file control
  7858. // (this was workaround for legacy dirview event handling, now it should be
  7859. // made prettier)
  7860. if (TargetDir.IsEmpty())
  7861. {
  7862. TargetDir = TempDir;
  7863. if (ForceDirectories(ApiPath(TargetDir)))
  7864. {
  7865. DebugAssert(Terminal && !TargetDir.IsEmpty());
  7866. FPendingTempSpaceWarn = true;
  7867. try
  7868. {
  7869. FDragDropOperation = true;
  7870. int Params = cpTemporary |
  7871. (Type == ttMove ? cpDelete : 0);
  7872. DDDownload(FDDFileList, TargetDir, &CopyParams, Params);
  7873. Configuration->Usage->Inc(L"DownloadsDragDropExternalTemp");
  7874. }
  7875. __finally
  7876. {
  7877. FDragDropOperation = false;
  7878. FPendingTempSpaceWarn = false;
  7879. AddDelayedDirectoryDeletion(TargetDir, WinConfiguration->DDDeleteDelay);
  7880. }
  7881. }
  7882. else
  7883. {
  7884. throw Exception(FMTLOAD(CREATE_TEMP_DIR_ERROR, (TargetDir)));
  7885. }
  7886. }
  7887. }
  7888. }
  7889. //---------------------------------------------------------------------------
  7890. void __fastcall TCustomScpExplorerForm::DDDownload(
  7891. TStrings * FilesToCopy, const UnicodeString & TargetDir, TCopyParamType * CopyParam, int Params)
  7892. {
  7893. DebugAssert(!IsLocalBrowserMode());
  7894. TAutoBatch AutoBatch(this);
  7895. CopyParam->IncludeFileMask.SetRoots(TargetDir, FilesToCopy);
  7896. UpdateCopyParamCounters(*CopyParam);
  7897. Terminal->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params, NULL);
  7898. if (FLAGSET(Params, cpDelete) && (DropSourceControl == RemoteDriveView))
  7899. {
  7900. RemoteDriveView->UpdateDropSource();
  7901. }
  7902. }
  7903. //---------------------------------------------------------------------------
  7904. class TFakeDataObjectFilesEx : public TDataObjectFilesEx
  7905. {
  7906. public:
  7907. __fastcall TFakeDataObjectFilesEx(TFileList * AFileList, bool RenderPIDL,
  7908. bool RenderFilename) : TDataObjectFilesEx(AFileList, RenderPIDL, RenderFilename, true)
  7909. {
  7910. }
  7911. virtual bool __fastcall AllowData(const tagFORMATETC & FormatEtc)
  7912. {
  7913. return (FormatEtc.cfFormat == CF_HDROP) ? false :
  7914. TDataObjectFilesEx::AllowData(FormatEtc);
  7915. }
  7916. };
  7917. //---------------------------------------------------------------------------
  7918. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDCreateDataObject(
  7919. TObject * Sender, TDataObject *& DataObject)
  7920. {
  7921. if (FDDExtMapFile != NULL)
  7922. {
  7923. TFileList * FileList = DragDropFiles(Sender)->FileList;
  7924. if (!FileList->RenderPIDLs() || !FileList->RenderNames())
  7925. {
  7926. Abort();
  7927. }
  7928. if (FileList->Count > 0)
  7929. {
  7930. TDataObjectFilesEx * FilesObject = new TFakeDataObjectFilesEx(FileList, true, true);
  7931. if (!FilesObject->IsValid(true, true))
  7932. {
  7933. FilesObject->_Release();
  7934. }
  7935. else
  7936. {
  7937. DataObject = FilesObject;
  7938. }
  7939. }
  7940. }
  7941. }
  7942. //---------------------------------------------------------------------------
  7943. void __fastcall TCustomScpExplorerForm::GoToCommandLine()
  7944. {
  7945. DebugFail();
  7946. }
  7947. //---------------------------------------------------------------------------
  7948. void __fastcall TCustomScpExplorerForm::GoToTree()
  7949. {
  7950. ComponentVisible[fcRemoteTree] = true;
  7951. DriveView(osRemote)->SetFocus();
  7952. }
  7953. //---------------------------------------------------------------------------
  7954. TStrings * __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7955. TPanelExport Export)
  7956. {
  7957. TCustomDirView * DirView = this->DirView(Side);
  7958. std::unique_ptr<TStrings> ExportData(new TStringList());
  7959. switch (Export)
  7960. {
  7961. case pePath:
  7962. ExportData->Add(DirView->PathName);
  7963. break;
  7964. case peFileList:
  7965. case peFullFileList:
  7966. {
  7967. bool FullPath = (Export == peFullFileList);
  7968. DirView->CreateFileList(false, FullPath, ExportData.get());
  7969. for (int Index = 0; Index < ExportData->Count; Index++)
  7970. {
  7971. if (ExportData->Strings[Index].Pos(L" ") > 0)
  7972. {
  7973. ExportData->Strings[Index] = FORMAT(L"\"%s\"", (ExportData->Strings[Index]));
  7974. }
  7975. }
  7976. }
  7977. break;
  7978. default:
  7979. DebugFail();
  7980. }
  7981. return ExportData.release();
  7982. }
  7983. //---------------------------------------------------------------------------
  7984. void __fastcall TCustomScpExplorerForm::PanelExport(TOperationSide Side,
  7985. TPanelExport Export, TPanelExportDestination Destination)
  7986. {
  7987. std::unique_ptr<TStrings> ExportData(PanelExport(Side, Export));
  7988. PanelExportStore(Side, Export, Destination, ExportData.get());
  7989. }
  7990. //---------------------------------------------------------------------------
  7991. void __fastcall TCustomScpExplorerForm::PanelExportStore(TOperationSide /*Side*/,
  7992. TPanelExport /*Export*/, TPanelExportDestination Destination,
  7993. TStrings * ExportData)
  7994. {
  7995. if (Destination == pedClipboard)
  7996. {
  7997. TInstantOperationVisualizer Visualizer;
  7998. CopyToClipboard(ExportData);
  7999. }
  8000. else
  8001. {
  8002. DebugFail();
  8003. }
  8004. }
  8005. //---------------------------------------------------------------------------
  8006. void __fastcall TCustomScpExplorerForm::Filter(TOperationSide Side)
  8007. {
  8008. TCustomDirView * DirView = this->DirView(Side);
  8009. UnicodeString Mask = DirView->Mask;
  8010. if (DoFilterMaskDialog(DirView, Mask))
  8011. {
  8012. DirView->Mask = TFileMasks::NormalizeMask(Mask);
  8013. Configuration->Usage->Inc(L"Filters");
  8014. }
  8015. }
  8016. //---------------------------------------------------------------------------
  8017. TQueueOperation __fastcall TCustomScpExplorerForm::DefaultQueueOperation()
  8018. {
  8019. return FQueueController->DefaultOperation();
  8020. }
  8021. //---------------------------------------------------------------------------
  8022. bool __fastcall TCustomScpExplorerForm::AllowQueueOperation(
  8023. TQueueOperation Operation, void ** Param)
  8024. {
  8025. switch (Operation)
  8026. {
  8027. case qoPreferences:
  8028. return true;
  8029. case qoGoTo:
  8030. return ComponentVisible[fcQueueView] && QueueView3->Enabled;
  8031. case qoOnceEmpty:
  8032. return IsAnythingQueued();
  8033. default:
  8034. return FQueueController->AllowOperation(Operation, Param);
  8035. }
  8036. }
  8037. //---------------------------------------------------------------------------
  8038. void __fastcall TCustomScpExplorerForm::GoToQueue()
  8039. {
  8040. if (DebugAlwaysTrue(QueueView3->Visible))
  8041. {
  8042. QueueView3->SetFocus();
  8043. }
  8044. }
  8045. //---------------------------------------------------------------------------
  8046. void __fastcall TCustomScpExplorerForm::ExecuteQueueOperation(
  8047. TQueueOperation Operation, void * Param)
  8048. {
  8049. if (Operation == qoGoTo)
  8050. {
  8051. GoToQueue();
  8052. }
  8053. else if (Operation == qoPreferences)
  8054. {
  8055. PreferencesDialog(pmQueue);
  8056. }
  8057. else
  8058. {
  8059. FQueueController->ExecuteOperation(Operation, Param);
  8060. }
  8061. }
  8062. //---------------------------------------------------------------------------
  8063. bool __fastcall TCustomScpExplorerForm::GetQueueEnabled()
  8064. {
  8065. return (Queue != NULL) && Queue->Enabled;
  8066. }
  8067. //---------------------------------------------------------------------------
  8068. void __fastcall TCustomScpExplorerForm::ToggleQueueEnabled()
  8069. {
  8070. DebugAssert(Queue != NULL);
  8071. if (Queue != NULL)
  8072. {
  8073. Queue->Enabled = !Queue->Enabled;
  8074. }
  8075. }
  8076. //---------------------------------------------------------------------------
  8077. void __fastcall TCustomScpExplorerForm::QueueView3ContextPopup(
  8078. TObject * /*Sender*/, TPoint & /*MousePos*/, bool & /*Handled*/)
  8079. {
  8080. FQueueActedItem = QueueView3->ItemFocused;
  8081. }
  8082. //---------------------------------------------------------------------------
  8083. /*virtual*/ int __fastcall TCustomScpExplorerForm::GetStaticComponentsHeight()
  8084. {
  8085. return TopDock->Height + (MessageDock->Visible ? MessageDock->Height : 0) + QueueSplitter->Height;
  8086. }
  8087. //---------------------------------------------------------------------------
  8088. int __fastcall TCustomScpExplorerForm::GetStaticQueuePanelComponentsHeight()
  8089. {
  8090. return
  8091. (QueueFileListSplitter->Visible ? QueueFileListSplitter->Height : 0) +
  8092. (QueueDock->Visible ? QueueDock->Height : 0) +
  8093. (QueueLabel->Visible ? QueueLabel->Height : 0);
  8094. }
  8095. //---------------------------------------------------------------------------
  8096. int __fastcall TCustomScpExplorerForm::GetMinQueueViewHeight()
  8097. {
  8098. return ScaleByTextHeight(this, 48);
  8099. }
  8100. //---------------------------------------------------------------------------
  8101. void __fastcall TCustomScpExplorerForm::QueueSplitterCanResize(
  8102. TObject * /*Sender*/, int & NewSize, bool & Accept)
  8103. {
  8104. // when queue is hidden by double-clicking splitter, stray attempt to
  8105. // resize the panel with strange value arrives, make sure it is ignored
  8106. if (ComponentVisible[fcQueueView])
  8107. {
  8108. int MaxHeightLimit = ClientHeight - GetStaticComponentsHeight() - RemotePanel->Constraints->MinHeight;
  8109. if (NewSize > MaxHeightLimit)
  8110. {
  8111. NewSize = MaxHeightLimit;
  8112. }
  8113. int MinHeightLimit =
  8114. GetStaticQueuePanelComponentsHeight() +
  8115. (QueueFileList->Visible ? QueueFileList->Height : 0) +
  8116. GetMinQueueViewHeight();
  8117. if (NewSize < MinHeightLimit)
  8118. {
  8119. NewSize = MinHeightLimit;
  8120. }
  8121. }
  8122. else
  8123. {
  8124. Accept = false;
  8125. }
  8126. }
  8127. //---------------------------------------------------------------------------
  8128. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterCanResize(TObject *, int & NewSize, bool &)
  8129. {
  8130. int TotalHeight = GetStaticQueuePanelComponentsHeight() + NewSize;
  8131. int QueueViewHeight = QueuePanel->ClientHeight - TotalHeight;
  8132. if (QueueViewHeight < GetMinQueueViewHeight())
  8133. {
  8134. NewSize -= (GetMinQueueViewHeight() - QueueViewHeight);
  8135. }
  8136. }
  8137. //---------------------------------------------------------------------------
  8138. void __fastcall TCustomScpExplorerForm::QueueView3StartDrag(TObject * /*Sender*/,
  8139. TDragObject *& /*DragObject*/)
  8140. {
  8141. FQueueActedItem = QueueView3->ItemFocused;
  8142. FQueueScrollOnDragOver->StartDrag();
  8143. }
  8144. //---------------------------------------------------------------------------
  8145. void __fastcall TCustomScpExplorerForm::QueueView3EndDrag(
  8146. TObject *, TObject * DebugUsedArg(Target), int DebugUsedArg(X), int DebugUsedArg(Y))
  8147. {
  8148. FQueueScrollOnDragOver->EndDrag();
  8149. }
  8150. //---------------------------------------------------------------------------
  8151. void __fastcall TCustomScpExplorerForm::QueueView3DragOver(TObject * /*Sender*/,
  8152. TObject * Source, int X, int Y, TDragState /*State*/, bool & Accept)
  8153. {
  8154. Accept = true;
  8155. if (Source == QueueView3)
  8156. {
  8157. TListItem * DropTarget = QueueView3->GetItemAt(X, Y);
  8158. Accept = (DropTarget != NULL) && (FQueueActedItem != NULL);
  8159. if (Accept)
  8160. {
  8161. TQueueItemProxy * QueueItem;
  8162. TQueueItemProxy * DestQueueItem;
  8163. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8164. DestQueueItem = static_cast<TQueueItemProxy *>(DropTarget->Data);
  8165. Accept = (QueueItem != DestQueueItem) &&
  8166. (QueueItem->Status == TQueueItem::qsPending) &&
  8167. (DestQueueItem->Status == TQueueItem::qsPending);
  8168. }
  8169. FQueueScrollOnDragOver->DragOver(TPoint(X, Y));
  8170. }
  8171. }
  8172. //---------------------------------------------------------------------------
  8173. void __fastcall TCustomScpExplorerForm::QueueView3DragDrop(TObject * /*Sender*/,
  8174. TObject * /*Source*/, int /*X*/, int /*Y*/)
  8175. {
  8176. if ((FQueueActedItem != NULL) && (QueueView3->DropTarget != NULL))
  8177. {
  8178. TQueueItemProxy * QueueItem;
  8179. TQueueItemProxy * DestQueueItem;
  8180. QueueItem = static_cast<TQueueItemProxy *>(FQueueActedItem->Data);
  8181. DestQueueItem = static_cast<TQueueItemProxy *>(QueueView3->DropTarget->Data);
  8182. QueueItem->Move(DestQueueItem);
  8183. }
  8184. }
  8185. //---------------------------------------------------------------------------
  8186. void __fastcall TCustomScpExplorerForm::QueueView3Enter(TObject * /*Sender*/)
  8187. {
  8188. if ((QueueView3->ItemFocused == NULL) &&
  8189. (QueueView3->Items->Count > 0))
  8190. {
  8191. QueueView3->ItemFocused = QueueView3->Items->Item[0];
  8192. }
  8193. QueueLabelUpdateStatus();
  8194. }
  8195. //---------------------------------------------------------------------------
  8196. void __fastcall TCustomScpExplorerForm::QueueView3Exit(TObject * /*Sender*/)
  8197. {
  8198. QueueLabelUpdateStatus();
  8199. }
  8200. //---------------------------------------------------------------------------
  8201. void __fastcall TCustomScpExplorerForm::QueueLabelUpdateStatus()
  8202. {
  8203. QueueLabel->UpdateStatus();
  8204. }
  8205. //---------------------------------------------------------------------------
  8206. void __fastcall TCustomScpExplorerForm::QueueView3SelectItem(
  8207. TObject * /*Sender*/, TListItem * /*Item*/, bool Selected)
  8208. {
  8209. if (Selected)
  8210. {
  8211. NonVisualDataModule->UpdateNonVisibleActions();
  8212. }
  8213. }
  8214. //---------------------------------------------------------------------------
  8215. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::DragDropFiles(TObject * Sender)
  8216. {
  8217. TDragDropFilesEx * Result = NULL;
  8218. if (Sender == SessionsPageControl)
  8219. {
  8220. Result = FSessionsDragDropFilesEx;
  8221. }
  8222. else if (Sender == QueueView3)
  8223. {
  8224. Result = FQueueDragDropFilesEx;
  8225. }
  8226. else
  8227. {
  8228. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8229. if (DirView != NULL)
  8230. {
  8231. Result = DirView->DragDropFilesEx;
  8232. }
  8233. else
  8234. {
  8235. TCustomDriveView * DriveView = dynamic_cast<TCustomDriveView *>(Sender);
  8236. if (DriveView != NULL)
  8237. {
  8238. Result = DriveView->DragDropFilesEx;
  8239. }
  8240. }
  8241. }
  8242. DebugAssert(Result != NULL);
  8243. return Result;
  8244. }
  8245. //---------------------------------------------------------------------------
  8246. bool __fastcall TCustomScpExplorerForm::SelectedAllFilesInDirView(TCustomDirView * DView)
  8247. {
  8248. return (DView->SelCount == DView->FilesCount);
  8249. }
  8250. //---------------------------------------------------------------------------
  8251. bool __fastcall TCustomScpExplorerForm::DraggingAllFilesFromDirView(TOperationSide Side, TStrings * FileList)
  8252. {
  8253. return HasDirView[Side] && (DropSourceControl == DirView(Side)) && (FileList->Count == DirView(Side)->FilesCount);
  8254. }
  8255. //---------------------------------------------------------------------------
  8256. void __fastcall TCustomScpExplorerForm::RemoteFileControlDragDropFileOperation(
  8257. TObject * Sender, int Effect, UnicodeString TargetPath, bool ForceQueue, bool DragDrop)
  8258. {
  8259. DebugAssert(!IsLocalBrowserMode());
  8260. TFileOperation Operation;
  8261. switch (Effect)
  8262. {
  8263. case DROPEFFECT_MOVE:
  8264. Operation = foMove;
  8265. break;
  8266. case DROPEFFECT_COPY:
  8267. // occures on WinXP (reported by user)
  8268. default:
  8269. Operation = foCopy;
  8270. break;
  8271. };
  8272. TDragDropFilesEx * DragDropFilesEx = DragDropFiles(Sender);
  8273. // see a comment in TUnixDirView::PerformItemDragDropOperation
  8274. if (DragDropFilesEx->FileList->Count > 0)
  8275. {
  8276. TStrings * FileList = new TStringList();
  8277. try
  8278. {
  8279. for (int Index = 0; Index < DragDropFilesEx->FileList->Count; Index++)
  8280. {
  8281. FileList->Add(DragDropFilesEx->FileList->Items[Index]->Name);
  8282. }
  8283. FDragDropOperation = true;
  8284. TTransferOperationParam Param;
  8285. Param.TargetDirectory = TargetPath;
  8286. // upload, no temp dirs
  8287. Param.Temp = false;
  8288. Param.DragDrop = DragDrop;
  8289. Param.Options =
  8290. FLAGMASK(DraggingAllFilesFromDirView(osLocal, FileList), coAllFiles);
  8291. if (ForceQueue)
  8292. {
  8293. Param.Queue = asOn;
  8294. }
  8295. bool NoConfirmation = DragDrop ? (WinConfiguration->DDTransferConfirmation == asOff) : false;
  8296. if (ExecuteFileOperation(Operation, osLocal, FileList, NoConfirmation, &Param))
  8297. {
  8298. if (IsFileControl(DropSourceControl, osLocal))
  8299. {
  8300. Configuration->Usage->Inc(L"UploadsDragDropInternal");
  8301. }
  8302. else
  8303. {
  8304. Configuration->Usage->Inc(L"UploadsDragDropExternal");
  8305. }
  8306. }
  8307. }
  8308. __finally
  8309. {
  8310. FDragDropOperation = false;
  8311. delete FileList;
  8312. }
  8313. }
  8314. }
  8315. //---------------------------------------------------------------------------
  8316. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDFileOperation(
  8317. TObject * Sender, int Effect, UnicodeString /*SourcePath*/,
  8318. UnicodeString TargetPath, bool Paste, bool & /*DoOperation*/)
  8319. {
  8320. RemoteFileControlDragDropFileOperation(Sender, Effect, TargetPath, false, !Paste);
  8321. }
  8322. //---------------------------------------------------------------------------
  8323. void __fastcall TCustomScpExplorerForm::RemoteFileContolDDChooseEffect(
  8324. TObject * Sender, int grfKeyState, int & dwEffect)
  8325. {
  8326. DebugAssert(!IsLocalBrowserMode());
  8327. // if any drop effect is allowed at all (e.g. no drop to self and drop to parent)
  8328. if ((dwEffect != DROPEFFECT_NONE) &&
  8329. IsFileControl(DropSourceControl, osRemote))
  8330. {
  8331. // do not allow drop on remote panel (on free space, still allow drop on directories)
  8332. if ((Sender == RemoteDirView) && (DropSourceControl == RemoteDirView) &&
  8333. (RemoteDirView->DropTarget == NULL))
  8334. {
  8335. dwEffect = DROPEFFECT_NONE;
  8336. }
  8337. else
  8338. {
  8339. if (dwEffect == DROPEFFECT_COPY)
  8340. {
  8341. bool MoveCapable = Terminal->IsCapable[fcRemoteMove];
  8342. // currently we support copying always (at least via temporary directory);
  8343. // remove associated checks once this all proves stable and working
  8344. bool CopyCapable = true;
  8345. // if we do not support neither of operations, there's no discussion
  8346. if (!MoveCapable && !CopyCapable)
  8347. {
  8348. dwEffect = DROPEFFECT_NONE;
  8349. }
  8350. else
  8351. {
  8352. // The default effect inside remote panel is move,
  8353. // unless we do not support it, but support copy
  8354. if (FLAGCLEAR(grfKeyState, MK_CONTROL))
  8355. {
  8356. dwEffect = MoveCapable ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
  8357. }
  8358. else
  8359. {
  8360. // with ctrl-down, we want copy unless it is not supported
  8361. dwEffect = CopyCapable ? DROPEFFECT_COPY : DROPEFFECT_NONE;
  8362. }
  8363. }
  8364. }
  8365. }
  8366. }
  8367. }
  8368. //---------------------------------------------------------------------------
  8369. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragFileName(
  8370. TObject * Sender, TRemoteFile * File, UnicodeString & FileName)
  8371. {
  8372. DebugAssert(!IsLocalBrowserMode());
  8373. if (FDDTotalSize >= 0)
  8374. {
  8375. if (File->IsDirectory)
  8376. {
  8377. FDDTotalSize = -1;
  8378. }
  8379. else
  8380. {
  8381. FDDTotalSize += File->Size;
  8382. }
  8383. }
  8384. DebugAssert(!FDragTempDir.IsEmpty());
  8385. // TODO: this is quite ineffective
  8386. // TODO: what if invalid character replacement is disabled?
  8387. FileName = FDragTempDir + GUIConfiguration->CurrentCopyParam.ValidLocalFileName(File->FileName);
  8388. UnicodeString TransferFileName;
  8389. if (Sender == RemoteDriveView)
  8390. {
  8391. TransferFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  8392. }
  8393. else
  8394. {
  8395. TransferFileName = File->FileName;
  8396. }
  8397. FDDFileList->AddObject(TransferFileName, File);
  8398. }
  8399. //---------------------------------------------------------------------------
  8400. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDDragDetect(
  8401. TObject * /*Sender*/, int /*grfKeyState*/, const TPoint & /*DetectStart*/,
  8402. const TPoint & /*Point*/, TDragDetectStatus /*DragStatus*/)
  8403. {
  8404. // sometimes we do not get DDEnd so the list is not released
  8405. SAFE_DESTROY(FDDFileList);
  8406. FDDFileList = new TStringList();
  8407. FDragTempDir = WinConfiguration->TemporaryDir();
  8408. FDDTotalSize = 0;
  8409. FDragDropSshTerminate.reset(NULL);
  8410. }
  8411. //---------------------------------------------------------------------------
  8412. void __fastcall TCustomScpExplorerForm::RemoteFileControlDDQueryContinueDrag(
  8413. TObject * /*Sender*/, BOOL /*FEscapePressed*/, int /*grfKeyState*/,
  8414. HRESULT & Result)
  8415. {
  8416. if (Result == DRAGDROP_S_DROP)
  8417. {
  8418. try
  8419. {
  8420. GlobalDragImageList->HideDragImage();
  8421. try
  8422. {
  8423. RemoteFileControlDDTargetDrop();
  8424. }
  8425. catch(ESshTerminate & E)
  8426. {
  8427. FDragDropSshTerminate.reset(E.Clone());
  8428. }
  8429. }
  8430. catch (Exception &E)
  8431. {
  8432. // If downloading fails we need to cancel drag&drop, otherwise
  8433. // Explorer shows error
  8434. // But by the way exception probably never reach this point as
  8435. // it's catched on way.
  8436. // Fatal exceptions get here (like when opening a secondary shell extension for file duplication fails).
  8437. Result = DRAGDROP_S_CANCEL;
  8438. ShowExtendedException(Terminal, &E);
  8439. }
  8440. }
  8441. }
  8442. //---------------------------------------------------------------------------
  8443. void __fastcall TCustomScpExplorerForm::DirViewMatchMask(
  8444. TObject * /*Sender*/, UnicodeString FileName, bool Directory, __int64 Size,
  8445. TDateTime Modification, UnicodeString Masks, bool & Matches, bool AllowImplicitMatches)
  8446. {
  8447. TFileMasks::TParams MaskParams;
  8448. MaskParams.Size = Size;
  8449. MaskParams.Modification = Modification;
  8450. // this does not re-parse the mask if it is the same as the last time
  8451. FDirViewMatchMask = Masks;
  8452. bool ImplicitMatch;
  8453. Matches =
  8454. // Local and RecurseInclude parameters have no effect as there's no path.
  8455. // This should use potential MatchesFileName overload with ImplicitMatch argument.
  8456. FDirViewMatchMask.Matches(FileName, false, Directory, &MaskParams, true, ImplicitMatch) &&
  8457. (AllowImplicitMatches || !ImplicitMatch);
  8458. }
  8459. //---------------------------------------------------------------------------
  8460. void __fastcall TCustomScpExplorerForm::DirViewGetOverlay(
  8461. TObject * Sender, TListItem * Item, WORD & Indexes)
  8462. {
  8463. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  8464. if (GetPartialFileExtLen(DirView->ItemFileName(Item)) > 0)
  8465. {
  8466. Indexes |= oiPartial;
  8467. }
  8468. }
  8469. //---------------------------------------------------------------------------
  8470. bool __fastcall TCustomScpExplorerForm::CanPasteToDirViewFromClipBoard()
  8471. {
  8472. return
  8473. DirViewEnabled(osCurrent) &&
  8474. DirView(osCurrent)->CanPasteFromClipBoard();
  8475. }
  8476. //---------------------------------------------------------------------------
  8477. bool __fastcall TCustomScpExplorerForm::CanPasteFromClipBoard()
  8478. {
  8479. bool Result = false;
  8480. if (CanPasteToDirViewFromClipBoard())
  8481. {
  8482. Result = true;
  8483. }
  8484. else
  8485. {
  8486. UnicodeString ClipboardText;
  8487. if (NonEmptyTextFromClipboard(ClipboardText) &&
  8488. (ClipboardText.Pos(L"\n") == 0)) // it's already trimmed
  8489. {
  8490. if (StoredSessions->IsUrl(ClipboardText))
  8491. {
  8492. Result = true;
  8493. }
  8494. else
  8495. {
  8496. Result = DirViewEnabled(osCurrent);
  8497. }
  8498. }
  8499. }
  8500. return Result;
  8501. }
  8502. //---------------------------------------------------------------------------
  8503. void __fastcall TCustomScpExplorerForm::PasteFromClipBoard()
  8504. {
  8505. // Pasting to any local panel is handled in TScpCommanderForm::PasteFromClipBoard()
  8506. if (DoesClipboardContainOurFiles())
  8507. {
  8508. if (DebugAlwaysTrue(CanPasteToDirViewFromClipBoard()))
  8509. {
  8510. DebugAssert(!IsLocalBrowserMode());
  8511. TTerminalManager * Manager = TTerminalManager::Instance();
  8512. TTerminal * TargetTerminal = Manager->ActiveTerminal;
  8513. Manager->ActiveSession = FClipboardTerminal;
  8514. ExecuteFileOperation(foRemoteCopy, osRemote, FClipboardFileList.get(), false, TargetTerminal);
  8515. }
  8516. }
  8517. else if (CanPasteToDirViewFromClipBoard())
  8518. {
  8519. DirView(osCurrent)->PasteFromClipBoard();
  8520. }
  8521. else
  8522. {
  8523. UnicodeString ClipboardText;
  8524. if (NonEmptyTextFromClipboard(ClipboardText))
  8525. {
  8526. if (StoredSessions->IsUrl(ClipboardText))
  8527. {
  8528. NewSession(ClipboardText);
  8529. }
  8530. else
  8531. {
  8532. DirView(osCurrent)->Path = ClipboardText;
  8533. }
  8534. }
  8535. }
  8536. }
  8537. //---------------------------------------------------------------------------
  8538. void __fastcall TCustomScpExplorerForm::FileListFromClipboard()
  8539. {
  8540. // TBD
  8541. }
  8542. //---------------------------------------------------------------------------
  8543. void __fastcall TCustomScpExplorerForm::SelectAll(TOperationSide Side, TSelectMode Mode)
  8544. {
  8545. TCustomDirView * ADirView = DirView(Side);
  8546. ADirView->SelectAll(Mode);
  8547. ADirView->SetFocus();
  8548. }
  8549. //---------------------------------------------------------------------------
  8550. void __fastcall TCustomScpExplorerForm::SelectByMask(TOperationSide Side, bool Select)
  8551. {
  8552. TCustomDirView * ADirView = DirView(Side);
  8553. TFileFilter Filter;
  8554. DefaultFileFilter(Filter);
  8555. if (DoSelectMaskDialog(ADirView, Select, Filter))
  8556. {
  8557. Configuration->Usage->Inc(L"MaskSelections");
  8558. ADirView->SelectFiles(Filter, Select);
  8559. ADirView->SetFocus();
  8560. }
  8561. }
  8562. //---------------------------------------------------------------------------
  8563. void __fastcall TCustomScpExplorerForm::RestoreSelectedNames(TOperationSide Side)
  8564. {
  8565. TCustomDirView * ADirView = DirView(Side);
  8566. ADirView->RestoreSelectedNames();
  8567. ADirView->SetFocus();
  8568. }
  8569. //---------------------------------------------------------------------------
  8570. void __fastcall TCustomScpExplorerForm::SelectSameExt(bool Select)
  8571. {
  8572. TCustomDirView * CurrentDirView = DirView(osCurrent);
  8573. if (DebugAlwaysTrue(CurrentDirView->ItemFocused != NULL))
  8574. {
  8575. UnicodeString FileName = CurrentDirView->ItemFileName(CurrentDirView->ItemFocused);
  8576. UnicodeString Ext;
  8577. if (!IsSideLocalBrowser(osCurrent))
  8578. {
  8579. Ext = UnixExtractFileExt(FileName);
  8580. }
  8581. else
  8582. {
  8583. Ext = ExtractFileExt(FileName);
  8584. }
  8585. if (Ext.IsEmpty())
  8586. {
  8587. Ext = L".";
  8588. }
  8589. TFileFilter Filter;
  8590. Filter.Masks = FORMAT(L"*%s", (Ext));
  8591. Filter.Directories = false;
  8592. CurrentDirView->SelectFiles(Filter, Select);
  8593. }
  8594. }
  8595. //---------------------------------------------------------------------------
  8596. UnicodeString __fastcall TCustomScpExplorerForm::FileStatusBarText(
  8597. const TStatusFileInfo & FileInfo, TOperationSide Side)
  8598. {
  8599. UnicodeString Result;
  8600. if (!FIncrementalSearch.IsEmpty() && (Side == GetSide(osCurrent)))
  8601. {
  8602. Result = FormatIncrementalSearchStatus(FIncrementalSearch, FIncrementalSearchHaveNext);
  8603. }
  8604. else if (!IsSideLocalBrowser(Side) && ((Terminal == NULL) || Terminal->Disconnected))
  8605. {
  8606. // noop
  8607. }
  8608. else
  8609. {
  8610. Result =
  8611. FMTLOAD(FILE_INFO_FORMAT,
  8612. (FormatBytes(FileInfo.SelectedSize),
  8613. FormatBytes(FileInfo.FilesSize),
  8614. FormatNumber(FileInfo.SelectedCount),
  8615. FormatNumber(FileInfo.FilesCount)));
  8616. }
  8617. return Result;
  8618. }
  8619. //---------------------------------------------------------------------------
  8620. void __fastcall TCustomScpExplorerForm::FileStatusBarPanelClick(
  8621. TTBXStatusPanel * Panel, TOperationSide Side)
  8622. {
  8623. if (Panel->Index == 1)
  8624. {
  8625. ToggleShowHiddenFiles();
  8626. }
  8627. else if (Panel->Index == 2)
  8628. {
  8629. Filter(Side);
  8630. }
  8631. }
  8632. //---------------------------------------------------------------------------
  8633. void __fastcall TCustomScpExplorerForm::UpdateFileStatusBar(
  8634. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo, TOperationSide Side)
  8635. {
  8636. DebugAssert(!StatusBar->SimplePanel);
  8637. StatusBar->Panels->Items[0]->Caption = FileStatusBarText(FileInfo, Side);
  8638. UpdateFileStatusExtendedPanels(StatusBar, FileInfo);
  8639. }
  8640. //---------------------------------------------------------------------------
  8641. void __fastcall TCustomScpExplorerForm::UpdateFileStatusExtendedPanels(
  8642. TTBXStatusBar * StatusBar, const TStatusFileInfo & FileInfo)
  8643. {
  8644. DebugAssert(StatusBar->Panels->Count >= 3);
  8645. TTBXStatusPanel * HiddenFilesPanel = StatusBar->Panels->Items[1];
  8646. if (FileInfo.HiddenCount > 0)
  8647. {
  8648. HiddenFilesPanel->Caption = FMTLOAD(FILE_INFO_HIDDEN2, (FormatNumber(FileInfo.HiddenCount)));
  8649. HiddenFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8650. }
  8651. else
  8652. {
  8653. HiddenFilesPanel->ViewPriority = 0;
  8654. // not really necessary, just to cleanup no-longer-valid data
  8655. HiddenFilesPanel->Caption = L"";
  8656. }
  8657. TTBXStatusPanel * FilteredFilesPanel = StatusBar->Panels->Items[2];
  8658. if (FileInfo.FilteredCount > 0)
  8659. {
  8660. FilteredFilesPanel->Caption = FMTLOAD(FILE_INFO_FILTERED2, (FormatNumber(FileInfo.FilteredCount)));
  8661. FilteredFilesPanel->ViewPriority = 90; // <100 allows hiding panel when it does not fit
  8662. }
  8663. else
  8664. {
  8665. FilteredFilesPanel->ViewPriority = 0;
  8666. // not really necessary, just to cleanup no-longer-valid data
  8667. FilteredFilesPanel->Caption = L"";
  8668. }
  8669. }
  8670. //---------------------------------------------------------------------------
  8671. void __fastcall TCustomScpExplorerForm::RemoteStatusBarClick(
  8672. TObject * /*Sender*/)
  8673. {
  8674. if (DirView(osOther)->Enabled)
  8675. {
  8676. DirView(osOther)->SetFocus();
  8677. }
  8678. }
  8679. //---------------------------------------------------------------------------
  8680. void __fastcall TCustomScpExplorerForm::ToggleQueueVisibility()
  8681. {
  8682. TQueueViewConfiguration Config = WinConfiguration->QueueView;
  8683. switch (Config.Show)
  8684. {
  8685. case qvShow:
  8686. if ((FQueueStatus != NULL) && (FQueueStatus->Count > 0))
  8687. {
  8688. Config.Show = qvHide;
  8689. }
  8690. else
  8691. {
  8692. Config.Show = Config.LastHideShow;
  8693. }
  8694. break;
  8695. case qvHideWhenEmpty:
  8696. if (ComponentVisible[fcQueueView])
  8697. {
  8698. Config.Show = qvHide;
  8699. }
  8700. else
  8701. {
  8702. Config.LastHideShow = Config.Show;
  8703. Config.Show = qvShow;
  8704. }
  8705. break;
  8706. case qvHide:
  8707. Config.LastHideShow = Config.Show;
  8708. Config.Show = qvShow;
  8709. break;
  8710. }
  8711. WinConfiguration->QueueView = Config;
  8712. }
  8713. //---------------------------------------------------------------------------
  8714. UnicodeString __fastcall TCustomScpExplorerForm::PathForCaption()
  8715. {
  8716. UnicodeString Result;
  8717. if (Terminal != NULL)
  8718. {
  8719. switch (WinConfiguration->PathInCaption)
  8720. {
  8721. case picShort:
  8722. Result = ExtractShortName(Terminal->CurrentDirectory, true);
  8723. break;
  8724. case picFull:
  8725. Result = Terminal->CurrentDirectory;
  8726. break;
  8727. }
  8728. }
  8729. return Result;
  8730. }
  8731. //---------------------------------------------------------------------------
  8732. TColor __fastcall TCustomScpExplorerForm::PanelColor()
  8733. {
  8734. TColor Result = GetWindowColor(FSessionColor);
  8735. return Result;
  8736. }
  8737. //---------------------------------------------------------------------------
  8738. TColor __fastcall TCustomScpExplorerForm::DisabledPanelColor()
  8739. {
  8740. TColor Result = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x40, 0x40, 0x40)) : clBtnFace);
  8741. return Result;
  8742. }
  8743. //---------------------------------------------------------------------------
  8744. void __fastcall TCustomScpExplorerForm::UpdateControls()
  8745. {
  8746. if (!FSessionChanging)
  8747. {
  8748. TTerminalManager::Instance()->UpdateAppTitle();
  8749. }
  8750. // WORKAROUND: Disabling list view when it is not showing yet does not set its
  8751. // background to gray on Windows 7 (works on Windows 10).
  8752. // See also EnableControl
  8753. if (Showing)
  8754. {
  8755. if (ManagedSession != NULL)
  8756. {
  8757. // Update path when it changes
  8758. if ((SessionsPageControl->ActivePage != NULL) &&
  8759. (GetSessionTabSession(SessionsPageControl->ActivePage) == ManagedSession))
  8760. {
  8761. UpdateSessionTab(SessionsPageControl->ActivePage);
  8762. }
  8763. }
  8764. NonVisualDataModule->ReconnectSessionAction->Update();
  8765. ReconnectToolbar->Visible = NonVisualDataModule->ReconnectSessionAction->Visible;
  8766. // ReconnectSessionAction is hidden when disabled, so enabling it actualy resizes the toolbar
  8767. CenterReconnectToolbar();
  8768. bool HasTerminal = HasActiveTerminal();
  8769. RemoteDirView->Enabled = HasTerminal;
  8770. RemoteDirView->Color = HasTerminal ? PanelColor() : DisabledPanelColor();
  8771. RemoteDirView->Font->Color = GetWindowTextColor(RemoteDirView->Color);
  8772. RemoteDriveView->Enabled = RemoteDirView->Enabled;
  8773. RemoteDriveView->Color = RemoteDirView->Color;
  8774. RemoteDriveView->Font->Color = RemoteDirView->Font->Color;
  8775. QueueView3->Enabled = HasTerminal && Terminal->IsCapable[fcBackgroundTransfers];
  8776. QueueView3->Color = QueueView3->Enabled ? GetWindowColor() : DisabledPanelColor();
  8777. QueueView3->Font->Color = GetWindowTextColor(QueueView3->Color);
  8778. QueueFileList->Enabled = QueueView3->Enabled;
  8779. QueueFileList->Color = QueueView3->Color;
  8780. QueueFileList->Font->Color = QueueView3->Font->Color;
  8781. QueueLabelUpdateStatus();
  8782. bool UseDarkTheme = WinConfiguration->UseDarkTheme();
  8783. RemoteDirView->DarkMode = UseDarkTheme;
  8784. RemoteDriveView->DarkMode = RemoteDirView->DarkMode;
  8785. if (FImmersiveDarkMode != UseDarkTheme)
  8786. {
  8787. UpdateDarkMode();
  8788. }
  8789. SessionsPageControl->TabTheme = UseDarkTheme ? CurrentTheme : NULL;
  8790. UnicodeString CurrentHiContrastThemeName = (FHiContrastTheme != NULL) ? FHiContrastTheme->Name : EmptyStr;
  8791. bool HiContrast = WinConfiguration->HiContrast;
  8792. UnicodeString NewHiContrastThemeName = HiContrast ? GetThemeName(!UseDarkTheme) : EmptyStr;
  8793. if (CurrentHiContrastThemeName != NewHiContrastThemeName)
  8794. {
  8795. ReleaseHiContrastTheme();
  8796. if (!NewHiContrastThemeName.IsEmpty())
  8797. {
  8798. FHiContrastTheme = GetTBXTheme(NewHiContrastThemeName);
  8799. }
  8800. }
  8801. SessionsPageControl->ActiveTabTheme = HiContrast ? DebugNotNull(FHiContrastTheme) : NULL;
  8802. reinterpret_cast<TTBCustomItem *>(GetComponent(fcRemotePathComboBox))->Enabled = HasTerminal || IsLocalBrowserMode();
  8803. MessageDock->Visible = (MessageDock->ToolbarCount > 0);
  8804. }
  8805. }
  8806. //---------------------------------------------------------------------------
  8807. void __fastcall TCustomScpExplorerForm::DoDirViewLoaded(TCustomDirView * /*Sender*/)
  8808. {
  8809. UpdateControls();
  8810. }
  8811. //---------------------------------------------------------------------------
  8812. void __fastcall TCustomScpExplorerForm::DirViewLoaded(
  8813. TObject * Sender)
  8814. {
  8815. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  8816. DebugAssert(DirView != NULL);
  8817. DoDirViewLoaded(DirView);
  8818. TransferPresetAutoSelect();
  8819. }
  8820. //---------------------------------------------------------------------------
  8821. void __fastcall TCustomScpExplorerForm::StartUpdates()
  8822. {
  8823. TUpdatesConfiguration Updates = WinConfiguration->Updates;
  8824. // first run after installation
  8825. if (double(Updates.LastCheck) == 0)
  8826. {
  8827. AppLog(L"First run, scheduling updates check for the next run");
  8828. // make sure next time there will be an update (if enabled)
  8829. Updates.LastCheck = TDateTime(1);
  8830. WinConfiguration->Updates = Updates;
  8831. }
  8832. else
  8833. {
  8834. TDateTime Period;
  8835. if (IsUWP() && !IsOfficialPackage())
  8836. {
  8837. Period = DefaultUpdatesPeriod;
  8838. AppLog(L"Thirdparty UWP package, using default updates check period");
  8839. }
  8840. else
  8841. {
  8842. Period = Updates.Period;
  8843. }
  8844. AppLogFmt(L"Updates check period: %.2f", (double(Period)));
  8845. if (double(Period) > 0)
  8846. {
  8847. TDateTime Interval = Now() - Updates.LastCheck;
  8848. AppLogFmt(L"Interval since the last updates check: %.2f", (double(Interval)));
  8849. if (Interval >= Period)
  8850. {
  8851. StartUpdateThread(UpdatesChecked);
  8852. }
  8853. }
  8854. }
  8855. }
  8856. //---------------------------------------------------------------------------
  8857. void __fastcall TCustomScpExplorerForm::UpdatesChecked()
  8858. {
  8859. AppLog(L"Updates check done");
  8860. UnicodeString Message;
  8861. bool New;
  8862. TQueryType Type;
  8863. GetUpdatesMessage(Message, New, Type, false);
  8864. if (!Message.IsEmpty())
  8865. {
  8866. AppLogFmt(L"Updates check message: %s", (Message));
  8867. if (New)
  8868. {
  8869. AppLog(L"New version detected");
  8870. Message = FMTLOAD(NEW_VERSION_CLICK, (Message));
  8871. }
  8872. if (!New && (Type != qtWarning))
  8873. {
  8874. AppLog(L"Posting non-critical updates note");
  8875. PostNote(UnformatMessage(Message), 0, UpdatesNoteClicked, NULL);
  8876. }
  8877. else
  8878. {
  8879. AppLog(L"Posting new version or critical message notification");
  8880. Notify(NULL, Message, Type, true, UpdatesNoteClicked);
  8881. }
  8882. if (New)
  8883. {
  8884. Configuration->Usage->Inc(L"UpdateNotifications");
  8885. }
  8886. }
  8887. }
  8888. //---------------------------------------------------------------------------
  8889. void __fastcall TCustomScpExplorerForm::UpdatesNoteClicked(TObject * /*Sender*/)
  8890. {
  8891. RestoreApp();
  8892. bool CanDisplay = !NonVisualDataModule->Busy;
  8893. if (!CanDisplay && (Screen->ActiveForm != NULL))
  8894. {
  8895. CanDisplay = (Screen->ActiveForm->Perform(WM_CAN_DISPLAY_UPDATES, 0, 0) != 0);
  8896. }
  8897. if (CanDisplay)
  8898. {
  8899. Configuration->Usage->Inc(L"UpdateNotificationsClicked");
  8900. // Probably not needed as CheckForUpdates is blocking since we started using neon for HTTP implementation.
  8901. NonVisualDataModule->StartBusy();
  8902. try
  8903. {
  8904. CheckForUpdates(true);
  8905. }
  8906. __finally
  8907. {
  8908. NonVisualDataModule->EndBusy();
  8909. }
  8910. }
  8911. else
  8912. {
  8913. Configuration->Usage->Inc(L"UpdateNotificationsBusy");
  8914. }
  8915. }
  8916. //---------------------------------------------------------------------------
  8917. void __fastcall TCustomScpExplorerForm::GetTransferPresetAutoSelectData(
  8918. TCopyParamRuleData & Data)
  8919. {
  8920. DebugAssert(Terminal != NULL);
  8921. Data.HostName = Terminal->SessionData->HostNameExpanded;
  8922. Data.UserName = Terminal->SessionData->UserNameExpanded;
  8923. Data.RemoteDirectory = RemoteDirView->PathName;
  8924. }
  8925. //---------------------------------------------------------------------------
  8926. void __fastcall TCustomScpExplorerForm::TransferPresetAutoSelect()
  8927. {
  8928. // Terminal can be null when we are changing local directory implicitly,
  8929. // because it has been deleted, while no session is connected
  8930. // (Login dialog is open)
  8931. if (FAllowTransferPresetAutoSelect && (Terminal != NULL))
  8932. {
  8933. DebugAssert(!IsLocalBrowserMode());
  8934. TCopyParamRuleData Data;
  8935. GetTransferPresetAutoSelectData(Data);
  8936. int CopyParamIndex = GUIConfiguration->CopyParamList->Find(Data);
  8937. UnicodeString CopyParamCurrent = GUIConfiguration->CopyParamCurrent;
  8938. if (CopyParamIndex < 0)
  8939. {
  8940. // there is no preset that matches autoselection
  8941. // set preset that we consider "default"
  8942. FCopyParamAutoSelected = L""; // forget last autoselected preset
  8943. GUIConfiguration->CopyParamCurrent = FCopyParamDefault;
  8944. }
  8945. else
  8946. {
  8947. // there is preset matching autoselection
  8948. UnicodeString CopyParamName = GUIConfiguration->CopyParamList->Names[CopyParamIndex];
  8949. if (CopyParamName == FCopyParamAutoSelected)
  8950. {
  8951. // autoselected the same preset as the last time
  8952. // make no change (i.e. preserve custom user preset, if any)
  8953. }
  8954. else
  8955. {
  8956. // autoselected the different preset then the last time (or there
  8957. // was default preset set)
  8958. FCopyParamAutoSelected = CopyParamName; // remember autoselection
  8959. GUIConfiguration->CopyParamCurrent = CopyParamName;
  8960. }
  8961. }
  8962. if (GUIConfiguration->CopyParamCurrent != CopyParamCurrent)
  8963. {
  8964. if (CopyParamIndex >= 0)
  8965. {
  8966. Configuration->Usage->Inc(L"CopyParamAutoSelects");
  8967. }
  8968. TTransferPresetNoteData * Data = new TTransferPresetNoteData;
  8969. try
  8970. {
  8971. int Fmt =
  8972. (CopyParamIndex < 0) ?
  8973. (GUIConfiguration->CopyParamIndex < 0 ? COPY_PARAM_DEFAULT_NORM : COPY_PARAM_DEFAULT_CUSTOM) :
  8974. COPY_PARAM_AUTOSELECTED;
  8975. UnicodeString Message = FMTLOAD(Fmt, (StripHotkey(GUIConfiguration->CopyParamCurrent)));
  8976. Data->Message = MainInstructions(Message);
  8977. int CopyParamAttrs = Terminal->UsableCopyParamAttrs(0).General;
  8978. UnicodeString Info = GUIConfiguration->CurrentCopyParam.GetInfoStr(L"\n",
  8979. CopyParamAttrs);
  8980. if (CopyParamIndex >= 0)
  8981. {
  8982. DebugAssert(GUIConfiguration->CopyParamList->Rules[CopyParamIndex] != NULL);
  8983. Info = FORMAT(L"%s\n \n%s", (Info,
  8984. FMTLOAD(COPY_PARAM_RULE,
  8985. (GUIConfiguration->CopyParamList->Rules[CopyParamIndex]->GetInfoStr(L"\n")))));
  8986. }
  8987. Data->Message += L"\n\n" + Info;
  8988. if (WinConfiguration->CopyParamAutoSelectNotice)
  8989. {
  8990. TransferPresetNoteMessage(Data, true);
  8991. }
  8992. else
  8993. {
  8994. PostNote(Message, 0, TransferPresetNoteClicked, Data);
  8995. Data = NULL; // ownership passed
  8996. }
  8997. }
  8998. __finally
  8999. {
  9000. delete Data;
  9001. }
  9002. }
  9003. }
  9004. }
  9005. //---------------------------------------------------------------------------
  9006. void __fastcall TCustomScpExplorerForm::TransferPresetNoteMessage(
  9007. TTransferPresetNoteData * NoteData, bool AllowNeverAskAgain)
  9008. {
  9009. DebugAssert(NoteData != NULL);
  9010. DebugAssert(!IsLocalBrowserMode());
  9011. TMessageParams Params(AllowNeverAskAgain ? mpNeverAskAgainCheck : 0);
  9012. TQueryButtonAlias Aliases[1];
  9013. Aliases[0].Button = qaIgnore; // "ignore" is after "ok"
  9014. Aliases[0].Alias = LoadStr(CONFIGURE_BUTTON);
  9015. Params.Aliases = Aliases;
  9016. Params.AliasesCount = LENOF(Aliases);
  9017. unsigned int Result =
  9018. MoreMessageDialog(NoteData->Message, NULL, qtInformation,
  9019. qaOK | qaIgnore, HELP_COPY_PARAM_AUTOSELECTED, &Params);
  9020. switch (Result)
  9021. {
  9022. case qaNeverAskAgain:
  9023. DebugAssert(AllowNeverAskAgain);
  9024. WinConfiguration->CopyParamAutoSelectNotice = false;
  9025. break;
  9026. case qaIgnore:
  9027. PreferencesDialog(pmPresets);
  9028. break;
  9029. }
  9030. }
  9031. //---------------------------------------------------------------------------
  9032. void __fastcall TCustomScpExplorerForm::TransferPresetNoteClicked(TObject * Sender)
  9033. {
  9034. // as of now useless, as this is used for notes only, never for balloons, ...
  9035. RestoreApp();
  9036. // .. and we should never be busy here
  9037. if (DebugAlwaysTrue(!NonVisualDataModule->Busy))
  9038. {
  9039. TransferPresetNoteMessage(DebugNotNull(dynamic_cast<TTransferPresetNoteData *>(Sender)), false);
  9040. }
  9041. }
  9042. //---------------------------------------------------------------------------
  9043. void __fastcall TCustomScpExplorerForm::PreferencesDialog(
  9044. TPreferencesMode APreferencesMode)
  9045. {
  9046. std::unique_ptr<TPreferencesDialogData> PreferencesData;
  9047. TCopyParamRuleData Data;
  9048. if (Terminal != NULL)
  9049. {
  9050. PreferencesData.reset(new TPreferencesDialogData());
  9051. GetTransferPresetAutoSelectData(Data);
  9052. PreferencesData->CopyParamRuleData = &Data;
  9053. }
  9054. DoPreferencesDialog(APreferencesMode, PreferencesData.get());
  9055. }
  9056. //---------------------------------------------------------------------------
  9057. void __fastcall TCustomScpExplorerForm::AdHocCustomCommandValidate(
  9058. const TCustomCommandType & Command)
  9059. {
  9060. if (CustomCommandState(Command, FEditingFocusedAdHocCommand, ccltAll) <= 0)
  9061. {
  9062. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (Command.Command)));
  9063. }
  9064. }
  9065. //---------------------------------------------------------------------------
  9066. void __fastcall TCustomScpExplorerForm::AdHocCustomCommand(bool OnFocused)
  9067. {
  9068. bool RemoteAllowed = CustomCommandRemoteAllowed();
  9069. TCustomCommandType Command;
  9070. // make sure we use local custom command when remote are not supported
  9071. if (RemoteAllowed || FLAGSET(FLastCustomCommand.Params, ccLocal))
  9072. {
  9073. Command = FLastCustomCommand;
  9074. }
  9075. else
  9076. {
  9077. Command.Params = Command.Params | ccLocal;
  9078. }
  9079. Command.Name = LoadStr(CUSTOM_COMMAND_AD_HOC_NAME);
  9080. FEditingFocusedAdHocCommand = OnFocused;
  9081. bool LocalSide = IsSideLocalBrowser(FCurrentSide);
  9082. int Options =
  9083. FLAGMASK((!RemoteAllowed || LocalSide), ccoDisableRemote) |
  9084. FLAGMASK(LocalSide, ccoDisableRemoteFiles);
  9085. if (DoCustomCommandDialog(Command, WinConfiguration->CustomCommandList,
  9086. ccmAdHoc, Options, AdHocCustomCommandValidate, NULL))
  9087. {
  9088. FLastCustomCommand = Command;
  9089. UpdateCustomCommandsToolbar();
  9090. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &Command);
  9091. }
  9092. }
  9093. //---------------------------------------------------------------------------
  9094. void __fastcall TCustomScpExplorerForm::LastCustomCommand(bool OnFocused)
  9095. {
  9096. DebugAssert(!FLastCustomCommand.Command.IsEmpty());
  9097. int State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9098. DebugAssert(State > 0);
  9099. if (State <= 0)
  9100. {
  9101. throw Exception(FMTLOAD(CUSTOM_COMMAND_IMPOSSIBLE2, (FLastCustomCommand.Command)));
  9102. }
  9103. ExecuteFileOperation(foCustomCommand, osRemote, OnFocused, false, &FLastCustomCommand);
  9104. }
  9105. //---------------------------------------------------------------------------
  9106. bool __fastcall TCustomScpExplorerForm::GetLastCustomCommand(bool OnFocused,
  9107. TCustomCommandType & Command, int & State)
  9108. {
  9109. bool Result = !FLastCustomCommand.Command.IsEmpty();
  9110. if (Result)
  9111. {
  9112. Command = FLastCustomCommand;
  9113. State = CustomCommandState(FLastCustomCommand, OnFocused, ccltAll);
  9114. }
  9115. return Result;
  9116. }
  9117. //---------------------------------------------------------------------------
  9118. void __fastcall TCustomScpExplorerForm::BeforeAction()
  9119. {
  9120. ResetIncrementalSearch();
  9121. }
  9122. //---------------------------------------------------------------------------
  9123. void __fastcall TCustomScpExplorerForm::PostComponentHide(Byte Component)
  9124. {
  9125. DebugAssert(ComponentVisible[Component]);
  9126. PostMessage(Handle, WM_COMPONENT_HIDE, Component, 0);
  9127. }
  9128. //---------------------------------------------------------------------------
  9129. void __fastcall TCustomScpExplorerForm::QueueSplitterDblClick(TObject * /*Sender*/)
  9130. {
  9131. // when queue panel is resized here directly, the status bar is stretched
  9132. // over whole space the panel occupied
  9133. PostComponentHide(fcQueueView);
  9134. }
  9135. //---------------------------------------------------------------------------
  9136. void __fastcall TCustomScpExplorerForm::QueueFileListSplitterDblClick(TObject *)
  9137. {
  9138. ComponentVisible[fcQueueFileList] = false;
  9139. }
  9140. //---------------------------------------------------------------------------
  9141. void __fastcall TCustomScpExplorerForm::ThemeChanged()
  9142. {
  9143. // We hoped this will refresh scrollbar colors, but it does not have any effect here.
  9144. RefreshColorMode();
  9145. ResetSysDarkTheme();
  9146. ConfigurationChanged();
  9147. ConfigureInterface();
  9148. // Should be called for all controls
  9149. RemoteDirView->Perform(WM_THEMECHANGED, 0, 0);
  9150. }
  9151. //---------------------------------------------------------------------------
  9152. void __fastcall TCustomScpExplorerForm::WMSettingChange(TMessage & Message)
  9153. {
  9154. // Do not handle, when shutting down anyway (maybe also when not setup completely yet?)
  9155. if (!FInvalid &&
  9156. (Message.LParam != 0) &&
  9157. (wcscmp(reinterpret_cast<LPCWCH>(Message.LParam), L"ImmersiveColorSet") == 0))
  9158. {
  9159. ThemeChanged();
  9160. }
  9161. TForm::Dispatch(&Message);
  9162. }
  9163. //---------------------------------------------------------------------------
  9164. void __fastcall TCustomScpExplorerForm::Dispatch(void * Message)
  9165. {
  9166. TMessage * M = static_cast<TMessage*>(Message);
  9167. switch (M->Msg)
  9168. {
  9169. case CM_DIALOGCHAR:
  9170. CMDialogChar(*M);
  9171. break;
  9172. case WM_APPCOMMAND:
  9173. WMAppCommand(*M);
  9174. break;
  9175. case WM_SYSCOMMAND:
  9176. WMSysCommand(*M);
  9177. break;
  9178. case WM_QUERYENDSESSION:
  9179. WMQueryEndSession(*M);
  9180. break;
  9181. case WM_ENDSESSION:
  9182. WMEndSession(*reinterpret_cast<TWMEndSession *>(M));
  9183. break;
  9184. #ifdef _DEBUG
  9185. case WM_WINDOWPOSCHANGED:
  9186. WMWindowPosChanged(*reinterpret_cast<TWMWindowPosMsg *>(M));
  9187. break;
  9188. case CM_CUSTOMSTYLECHANGED:
  9189. TForm::Dispatch(Message);
  9190. break;
  9191. #endif
  9192. case WM_COMPONENT_HIDE:
  9193. {
  9194. Byte Component = static_cast<Byte>(M->WParam);
  9195. // sanity check
  9196. if (ComponentVisible[Component])
  9197. {
  9198. // special treatment
  9199. if (Component == fcQueueView)
  9200. {
  9201. ToggleQueueVisibility();
  9202. DebugAssert(!ComponentVisible[fcQueueView]);
  9203. }
  9204. else
  9205. {
  9206. ComponentVisible[Component] = false;
  9207. }
  9208. }
  9209. }
  9210. break;
  9211. case WM_COPYDATA:
  9212. WMCopyData(*M);
  9213. break;
  9214. case WM_MANAGES_CAPTION:
  9215. // caption managed in TTerminalManager::UpdateAppTitle()
  9216. M->Result = 1;
  9217. break;
  9218. case WM_WANTS_MOUSEWHEEL:
  9219. M->Result = 1;
  9220. break;
  9221. case CM_SHOWINGCHANGED:
  9222. CMShowingChanged(*M);
  9223. break;
  9224. case WM_CLOSE:
  9225. WMClose(*M);
  9226. break;
  9227. case WM_DPICHANGED:
  9228. WMDpiChanged(*M);
  9229. break;
  9230. case CM_DPICHANGED:
  9231. CMDpiChanged(*M);
  9232. break;
  9233. case WM_SETTINGCHANGE:
  9234. WMSettingChange(*M);
  9235. break;
  9236. case CM_DIALOGKEY:
  9237. CMDialogKey(*reinterpret_cast<TWMKeyDown *>(M));
  9238. break;
  9239. case WM_PASTE_FILES:
  9240. PasteFiles();
  9241. break;
  9242. case WM_IS_HIDDEN:
  9243. // To treat master password prompt as a main window while showing it when workspace is loading while
  9244. // the exporer is showing up (Visible is true already)
  9245. M->Result = !FShowing;
  9246. break;
  9247. case WM_SHOWWINDOW:
  9248. if (M->WParam)
  9249. {
  9250. AddStartupSequence(L"J");
  9251. }
  9252. TForm::Dispatch(Message);
  9253. break;
  9254. default:
  9255. TForm::Dispatch(Message);
  9256. break;
  9257. }
  9258. }
  9259. //---------------------------------------------------------------------------
  9260. void __fastcall TCustomScpExplorerForm::UpdateImages()
  9261. {
  9262. // noop
  9263. }
  9264. //---------------------------------------------------------------------------
  9265. void __fastcall TCustomScpExplorerForm::CMDpiChanged(TMessage & Message)
  9266. {
  9267. TForm::Dispatch(&Message);
  9268. FSessionColors->Clear();
  9269. AddFixedSessionImages();
  9270. RegenerateSessionColorsImageList(FSessionColors, FSessionColorMaskImageIndex);
  9271. UpdateImages();
  9272. }
  9273. //---------------------------------------------------------------------------
  9274. void __fastcall TCustomScpExplorerForm::WMDpiChanged(TMessage & Message)
  9275. {
  9276. TForm::Dispatch(&Message);
  9277. Configuration->Usage->Inc(L"PixelsPerInchChanged");
  9278. UpdatePixelsPerInchMainWindowCounter();
  9279. }
  9280. //---------------------------------------------------------------------------
  9281. void __fastcall TCustomScpExplorerForm::WMClose(TMessage & Message)
  9282. {
  9283. AppLog(L"Main window WM_CLOSE");
  9284. // Cannot close window while we are busy.
  9285. // We cannot test this in FormCloseQuery as that is called also from
  9286. // Close(), which is called by CloseApplicationAction. So we can be busy
  9287. // there already even, when it is legitimate to close the application.
  9288. // Possibly a better place to handle this would be WMSysCommand.
  9289. if (NonVisualDataModule->Busy)
  9290. {
  9291. Message.Result = 1;
  9292. }
  9293. else
  9294. {
  9295. TForm::Dispatch(&Message);
  9296. }
  9297. }
  9298. //---------------------------------------------------------------------------
  9299. void __fastcall TCustomScpExplorerForm::CMShowingChanged(TMessage & Message)
  9300. {
  9301. if (!FShowingChanged)
  9302. {
  9303. AddStartupSequence(L"D");
  9304. FShowingChanged = true;
  9305. }
  9306. // Ignoring implicit local-local browser of Commander, opened from DoShow
  9307. bool NoSession = (ManagedSession == NULL);
  9308. // This calls TCustomScpExplorerForm::DoShow
  9309. TForm::Dispatch(&Message);
  9310. // Now the window is visible (TForm::Dispatch is what usually takes long, like when loading a "local" network directory)
  9311. if (Showing && !FStarted)
  9312. {
  9313. FStarted = true;
  9314. InterfaceStarted();
  9315. }
  9316. if (Showing && NoSession)
  9317. {
  9318. // When we are starting minimized (i.e. from an installer),
  9319. // postpone showing Login dialog until we get restored.
  9320. // Otherwise the Login dialog (and Authentication window) show restored
  9321. // over invisible (minimized) main window.
  9322. if (WindowState == wsMinimized)
  9323. {
  9324. FNeedSession = true;
  9325. }
  9326. else
  9327. {
  9328. // This happens before application ever goes idle, so the toolbars would
  9329. // stay enabled (initial state) until the Login dialog is dismissed.
  9330. UpdateActions();
  9331. NonVisualDataModule->StartBusy();
  9332. try
  9333. {
  9334. // Need to process WM_ACTIVATEAPP before showing the Login dialog,
  9335. // otherwise the dialog does not receive focus.
  9336. // With Commander interface the ProcessMessages is called already
  9337. // by TDriveView, but with Explorer interface, we need to call it explicily
  9338. Application->ProcessMessages();
  9339. // do not reload sessions, they have been loaded just now (optimization)
  9340. NeedSession(true);
  9341. }
  9342. __finally
  9343. {
  9344. NonVisualDataModule->EndBusy();
  9345. }
  9346. }
  9347. }
  9348. }
  9349. //---------------------------------------------------------------------------
  9350. void __fastcall TCustomScpExplorerForm::CenterReconnectToolbar()
  9351. {
  9352. ReconnectToolbar->Left = (ReconnectToolbar->Parent->ClientWidth - ReconnectToolbar->Width) / 2;
  9353. ReconnectToolbar->Top = (ReconnectToolbar->Parent->ClientHeight - ReconnectToolbar->Height) / 2;
  9354. }
  9355. //---------------------------------------------------------------------------
  9356. void __fastcall TCustomScpExplorerForm::FormConstrainedResize(
  9357. TObject * /*Sender*/, int & MinWidth, int & MinHeight, int & MaxWidth,
  9358. int & MaxHeight)
  9359. {
  9360. // workaround for bug in TWinControl.CalcConstraints
  9361. // Check for empty rect (restore from iconic state) is done there only after
  9362. // call to AdjustClientRect, which enlarges the rect (for forms).
  9363. TRect R = GetClientRect();
  9364. // when restoring from iconic state, place no restrictions
  9365. if (IsRectEmpty(R))
  9366. {
  9367. MinWidth = 0;
  9368. MinHeight = 0;
  9369. MaxWidth = 32000;
  9370. MaxHeight = 32000;
  9371. }
  9372. }
  9373. //---------------------------------------------------------------------------
  9374. void __fastcall TCustomScpExplorerForm::GetSpaceAvailable(const UnicodeString Path,
  9375. TSpaceAvailable & ASpaceAvailable, bool & Close)
  9376. {
  9377. // terminal can be already closed (e.g. dropped connection)
  9378. if ((Terminal != NULL) && Terminal->IsCapable[fcCheckingSpaceAvailable])
  9379. {
  9380. Configuration->Usage->Inc(L"SpaceAvailableChecks");
  9381. try
  9382. {
  9383. Terminal->SpaceAvailable(Path, ASpaceAvailable);
  9384. }
  9385. catch(...)
  9386. {
  9387. if (!Terminal->Active)
  9388. {
  9389. Close = true;
  9390. }
  9391. throw;
  9392. }
  9393. }
  9394. }
  9395. //---------------------------------------------------------------------------
  9396. void __fastcall TCustomScpExplorerForm::FileSystemInfo()
  9397. {
  9398. const TSessionInfo & SessionInfo = Terminal->GetSessionInfo();
  9399. const TFileSystemInfo & FileSystemInfo = Terminal->GetFileSystemInfo(true);
  9400. TGetSpaceAvailable OnGetSpaceAvailable = NULL;
  9401. if (Terminal->IsCapable[fcCheckingSpaceAvailable])
  9402. {
  9403. OnGetSpaceAvailable = GetSpaceAvailable;
  9404. }
  9405. DoFileSystemInfoDialog(SessionInfo, FileSystemInfo, Terminal->CurrentDirectory,
  9406. OnGetSpaceAvailable);
  9407. }
  9408. //---------------------------------------------------------------------------
  9409. TSessionData * __fastcall TCustomScpExplorerForm::SessionDataForCode()
  9410. {
  9411. std::unique_ptr<TSessionData> Data(CloneCurrentSessionData());
  9412. Terminal->FillSessionDataForCode(Data.get());
  9413. return Data.release();
  9414. }
  9415. //---------------------------------------------------------------------------
  9416. void __fastcall TCustomScpExplorerForm::GenerateUrl(TStrings * Paths)
  9417. {
  9418. std::unique_ptr<TSessionData> Data(SessionDataForCode());
  9419. DoGenerateUrlDialog(Data.get(), Paths);
  9420. }
  9421. //---------------------------------------------------------------------------
  9422. void __fastcall TCustomScpExplorerForm::SessionGenerateUrl()
  9423. {
  9424. GenerateUrl(NULL);
  9425. }
  9426. //---------------------------------------------------------------------------
  9427. void __fastcall TCustomScpExplorerForm::FileGenerateUrl()
  9428. {
  9429. std::unique_ptr<TStrings> Paths(new TStringList());
  9430. DirView(osCurrent)->CreateFileList(false, true, Paths.get());
  9431. GenerateUrl(Paths.get());
  9432. }
  9433. //---------------------------------------------------------------------------
  9434. void __fastcall TCustomScpExplorerForm::UpdateSessionColor(TColor value)
  9435. {
  9436. FSessionColor = value;
  9437. TColor C = (value != 0 ? value : Vcl::Graphics::clNone);
  9438. TTBXColorItem * ColorItem = dynamic_cast<TTBXColorItem *>(
  9439. static_cast<TObject *>(GetComponent(fcColorMenu)));
  9440. DebugAssert(ColorItem != NULL);
  9441. ColorItem->Color = C;
  9442. NonVisualDataModule->ColorMenuItem->Color = C;
  9443. UpdateControls();
  9444. }
  9445. //---------------------------------------------------------------------------
  9446. void __fastcall TCustomScpExplorerForm::SetSessionColor(TColor value)
  9447. {
  9448. if (value != FSessionColor)
  9449. {
  9450. UpdateSessionColor(value);
  9451. // Is null when called from LastTerminalClosed
  9452. if (Terminal != NULL)
  9453. {
  9454. SessionsPageControl->ActivePage->ImageIndex = AddSessionColor(value);
  9455. }
  9456. }
  9457. }
  9458. //---------------------------------------------------------------------------
  9459. bool __fastcall TCustomScpExplorerForm::CancelNote(bool Force)
  9460. {
  9461. bool Result = FNoteTimer->Enabled;
  9462. if (Result)
  9463. {
  9464. // cannot cancel note too early
  9465. bool NotEarly =
  9466. (Now() - FNoteShown >
  9467. EncodeTimeVerbose(0, 0, (unsigned short)(WinConfiguration->NotificationsStickTime), 0));
  9468. if (Force || NotEarly)
  9469. {
  9470. FNoteTimer->Enabled = false;
  9471. FNote = L"";
  9472. SAFE_DESTROY(FNoteData);
  9473. FOnNoteClick = NULL;
  9474. FNoteHints = FNotes->Text;
  9475. FNoteHints.Delete(FNoteHints.Length() - 1, 2);
  9476. UpdateStatusBar();
  9477. }
  9478. }
  9479. return Result;
  9480. }
  9481. //---------------------------------------------------------------------------
  9482. void __fastcall TCustomScpExplorerForm::NoteTimer(TObject * /*Sender*/)
  9483. {
  9484. DebugAssert(FNoteTimer->Enabled);
  9485. CancelNote(true);
  9486. }
  9487. //---------------------------------------------------------------------------
  9488. void __fastcall TCustomScpExplorerForm::UpdateNoteHints()
  9489. {
  9490. FNoteHints = FNotes->Text.TrimRight();
  9491. }
  9492. //---------------------------------------------------------------------------
  9493. void __fastcall TCustomScpExplorerForm::AddNote(UnicodeString Note, bool UpdateNow)
  9494. {
  9495. int P = Note.Pos(L"\n");
  9496. if (P > 0)
  9497. {
  9498. Note.SetLength(P - 1);
  9499. }
  9500. FNotes->Add(FORMAT(L"[%s] %s",
  9501. (FormatDateTime(Configuration->TimeFormat, Now()), Note)));
  9502. while (FNotes->Count > 10)
  9503. {
  9504. FNotes->Delete(0);
  9505. }
  9506. if (UpdateNow)
  9507. {
  9508. UpdateNoteHints();
  9509. UpdateStatusBar();
  9510. }
  9511. }
  9512. //---------------------------------------------------------------------------
  9513. void __fastcall TCustomScpExplorerForm::PostNote(UnicodeString Note,
  9514. unsigned int Seconds, TNotifyEvent OnNoteClick, TObject * NoteData)
  9515. {
  9516. int P = Note.Pos(L"\n");
  9517. if (P > 0)
  9518. {
  9519. Note.SetLength(P - 1);
  9520. }
  9521. UpdateNoteHints();
  9522. FNote = Note;
  9523. SAFE_DESTROY(FNoteData);
  9524. FNoteData = NoteData;
  9525. FOnNoteClick = OnNoteClick;
  9526. AddNote(Note, false);
  9527. UpdateStatusBar();
  9528. FNoteShown = Now();
  9529. FNoteTimer->Enabled = false;
  9530. if (Seconds == 0)
  9531. {
  9532. Seconds = WinConfiguration->NotificationsTimeout;
  9533. }
  9534. FNoteTimer->Interval = Seconds * MSecsPerSec;
  9535. FNoteTimer->Enabled = true;
  9536. }
  9537. //---------------------------------------------------------------------------
  9538. void __fastcall TCustomScpExplorerForm::ReadDirectoryCancelled()
  9539. {
  9540. PostNote(LoadStr(DIRECTORY_READING_CANCELLED), 0, NULL, NULL);
  9541. }
  9542. //---------------------------------------------------------------------------
  9543. void __fastcall TCustomScpExplorerForm::SynchronizeBrowsingChanged()
  9544. {
  9545. if (NonVisualDataModule->SynchronizeBrowsingAction2->Checked)
  9546. {
  9547. Configuration->Usage->Inc(L"SynchronizeBrowsingEnabled");
  9548. }
  9549. PostNote(FORMAT(LoadStrPart(SYNC_DIR_BROWSE_TOGGLE, 1),
  9550. (LoadStrPart(SYNC_DIR_BROWSE_TOGGLE,
  9551. (NonVisualDataModule->SynchronizeBrowsingAction2->Checked ? 2 : 3)))),
  9552. 0, NULL, NULL);
  9553. }
  9554. //---------------------------------------------------------------------------
  9555. void __fastcall TCustomScpExplorerForm::ToggleShowHiddenFiles()
  9556. {
  9557. bool NewShowHiddenFiles = !WinConfiguration->ShowHiddenFiles;
  9558. UnicodeString Note =
  9559. FORMAT(LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, 1), (LoadStrPart(SHOW_HIDDEN_FILES_TOGGLE, (NewShowHiddenFiles ? 2 : 3))));
  9560. PostNote(Note, 0, NULL, NULL);
  9561. GetComponent(fcStatusBar)->Repaint(); // toggling ShowHiddenFiles takes time, force repaint beforehand
  9562. WinConfiguration->ShowHiddenFiles = NewShowHiddenFiles;
  9563. }
  9564. //---------------------------------------------------------------------------
  9565. void __fastcall TCustomScpExplorerForm::SetFormatSizeBytes(TFormatBytesStyle Style)
  9566. {
  9567. WinConfiguration->FormatSizeBytes = Style;
  9568. }
  9569. //---------------------------------------------------------------------------
  9570. void __fastcall TCustomScpExplorerForm::ToggleAutoReadDirectoryAfterOp()
  9571. {
  9572. Configuration->AutoReadDirectoryAfterOp = !Configuration->AutoReadDirectoryAfterOp;
  9573. PostNote(FORMAT(LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE, 1),
  9574. (LoadStrPart(AUTO_READ_DIRECTORY_TOGGLE,
  9575. (Configuration->AutoReadDirectoryAfterOp ? 2 : 3)))), 0, NULL, NULL);
  9576. }
  9577. //---------------------------------------------------------------------------
  9578. void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
  9579. TTBXCustomStatusBar * Sender, TTBXStatusPanel * Panel)
  9580. {
  9581. if (Panel->Index == 0)
  9582. {
  9583. if (FOnNoteClick != NULL)
  9584. {
  9585. // prevent the user data from being freed by possible call
  9586. // to CancelNote or PostNote during call to OnNoteClick
  9587. std::unique_ptr<TObject> NoteData(FNoteData);
  9588. TNotifyEvent OnNoteClick = FOnNoteClick;
  9589. FNoteData = NULL;
  9590. // need to cancel the note as we are going to delete its user data
  9591. CancelNote(true);
  9592. OnNoteClick(NoteData.get());
  9593. }
  9594. }
  9595. if (HasActiveTerminal() &&
  9596. (Panel->Index >= Sender->Panels->Count - SessionPanelCount))
  9597. {
  9598. FileSystemInfo();
  9599. }
  9600. }
  9601. //---------------------------------------------------------------------------
  9602. void __fastcall TCustomScpExplorerForm::LockWindow(bool Force)
  9603. {
  9604. // workaround:
  9605. // 1) for unknown reason, disabling window, while minimized,
  9606. // prevents it from restoring, even if it was enabled again meanwhile
  9607. // 2) when disabling the main window, while another has focus
  9608. // minimize is no longer possible
  9609. // ("keep up to date" dialog - though does not seem to be the case with "find file" -
  9610. // so it has probably something to do with the semi-modalness of the "keep up to date" dialog)
  9611. // Shouldn't we use IsApplicationMinimized() here?
  9612. if ((FLockSuspendLevel == 0) && !IsIconic(Application->Handle) && (Force || (Screen->ActiveForm == this)))
  9613. {
  9614. Enabled = false;
  9615. }
  9616. FLockLevel++;
  9617. }
  9618. //---------------------------------------------------------------------------
  9619. void __fastcall TCustomScpExplorerForm::UnlockWindow()
  9620. {
  9621. DebugAssert(FLockLevel > 0);
  9622. FLockLevel--;
  9623. if (FLockLevel == 0)
  9624. {
  9625. DebugAssert(FLockSuspendLevel == 0);
  9626. Enabled = true;
  9627. // VCL_COPY (TCustomForm.SetWindowFocus)
  9628. if (Active && (ActiveControl != NULL))
  9629. {
  9630. ::SetFocus(ActiveControl->Handle);
  9631. if (GetFocus() == ActiveControl->Handle)
  9632. {
  9633. ActiveControl->Perform(CM_UIACTIVATE, 0, 0);
  9634. }
  9635. }
  9636. }
  9637. }
  9638. //---------------------------------------------------------------------------
  9639. void __fastcall TCustomScpExplorerForm::SuspendWindowLock()
  9640. {
  9641. // We need to make sure that window is enabled when the last modal window closes
  9642. // otherwise focus is not restored correctly.
  9643. // So we re-enable the window when modal window opens and
  9644. // disable it back after is closes
  9645. if (FLockLevel > 0)
  9646. {
  9647. // while we have nesting counter, we know that we never be called
  9648. // recursivelly as Application->OnModalBegin is called only
  9649. // for the top-level modal window
  9650. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9651. {
  9652. // won't be disabled when conditions in LockWindow() were not satisfied
  9653. FDisabledOnLockSuspend = !Enabled;
  9654. // When minimized to tray (or actually when set to SW_HIDE),
  9655. // setting Enabled makes the window focusable even when there's
  9656. // modal window over it
  9657. if (!FTrayIcon->Visible)
  9658. {
  9659. Enabled = true;
  9660. }
  9661. }
  9662. FLockSuspendLevel++;
  9663. }
  9664. }
  9665. //---------------------------------------------------------------------------
  9666. void __fastcall TCustomScpExplorerForm::ResumeWindowLock()
  9667. {
  9668. if (FLockSuspendLevel > 0)
  9669. {
  9670. DebugAssert(FLockLevel > 0);
  9671. FLockSuspendLevel--;
  9672. // see comment in SuspendWindowLock
  9673. if (DebugAlwaysTrue(FLockSuspendLevel == 0))
  9674. {
  9675. // Note that window can be enabled here, when we were minized to tray when
  9676. // was SuspendWindowLock() called.
  9677. // We should possibly do the same check as in LockWindow(),
  9678. // if it is ever possible that the consitions change between
  9679. // SuspendWindowLock() and ResumeWindowLock()
  9680. Enabled = !FDisabledOnLockSuspend;
  9681. }
  9682. }
  9683. }
  9684. //---------------------------------------------------------------------------
  9685. void __fastcall TCustomScpExplorerForm::UpdateRemotePathComboBox(bool TextOnly)
  9686. {
  9687. TTBXComboBoxItem * RemotePathComboBox =
  9688. reinterpret_cast<TTBXComboBoxItem *>(GetComponent(fcRemotePathComboBox));
  9689. if (!TextOnly)
  9690. {
  9691. TStrings * Items = RemotePathComboBox->Strings;
  9692. Items->BeginUpdate();
  9693. try
  9694. {
  9695. Items->Clear();
  9696. if ((Terminal != NULL) && !RemoteDirView->Path.IsEmpty())
  9697. {
  9698. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9699. while (!IsUnixRootPath(APath))
  9700. {
  9701. int P = APath.LastDelimiter(L'/');
  9702. DebugAssert(P >= 0);
  9703. Items->Insert(0, APath.SubString(P + 1, APath.Length() - P));
  9704. APath.SetLength(P - 1);
  9705. }
  9706. Items->Insert(0, Customunixdirview_SUnixDefaultRootName);
  9707. }
  9708. }
  9709. __finally
  9710. {
  9711. Items->EndUpdate();
  9712. }
  9713. }
  9714. RemotePathComboBox->ItemIndex = RemotePathComboBox->Strings->Count - 1;
  9715. // Setting ItemIndex to -1 does not reset its text
  9716. if (RemotePathComboBox->Strings->Count == 0)
  9717. {
  9718. RemotePathComboBox->Text = L"";
  9719. }
  9720. }
  9721. //---------------------------------------------------------------------------
  9722. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxAdjustImageIndex(
  9723. TTBXComboBoxItem * Sender, const UnicodeString DebugUsedArg(AText), int AIndex, int & ImageIndex)
  9724. {
  9725. if (AIndex < 0)
  9726. {
  9727. AIndex = Sender->ItemIndex;
  9728. }
  9729. ImageIndex = (AIndex < Sender->Strings->Count - 1 ? StdDirIcon : StdDirSelIcon);
  9730. }
  9731. //---------------------------------------------------------------------------
  9732. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxAdjustImageIndex(
  9733. TTBXComboBoxItem * Sender, const UnicodeString AText, int AIndex,
  9734. int & ImageIndex)
  9735. {
  9736. DoRemotePathComboBoxAdjustImageIndex(Sender, AText, AIndex, ImageIndex);
  9737. }
  9738. //---------------------------------------------------------------------------
  9739. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxDrawItem(
  9740. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, TRect & ARect, int AIndex,
  9741. int /*AHoverIndex*/, bool & /*DrawDefault*/)
  9742. {
  9743. if (!IsLocalBrowserMode())
  9744. {
  9745. ARect.Left += (10 * AIndex);
  9746. }
  9747. }
  9748. //---------------------------------------------------------------------------
  9749. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxMeasureWidth(
  9750. TTBXCustomList * /*Sender*/, TCanvas * /*ACanvas*/, int AIndex, int &AWidth)
  9751. {
  9752. AWidth += (10 * AIndex);
  9753. }
  9754. //---------------------------------------------------------------------------
  9755. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxItemClick(TObject * Sender)
  9756. {
  9757. TTBXComboBoxItem * RemotePathComboBox = dynamic_cast<TTBXComboBoxItem*>(Sender);
  9758. UnicodeString APath = UnixExcludeTrailingBackslash(RemoteDirView->Path);
  9759. int Index = RemotePathComboBox->ItemIndex;
  9760. while (Index < RemotePathComboBox->Strings->Count - 1)
  9761. {
  9762. APath = UnixExtractFileDir(APath);
  9763. Index++;
  9764. }
  9765. // VanDyke style paths
  9766. if (APath.IsEmpty())
  9767. {
  9768. DebugAssert(RemotePathComboBox->ItemIndex == 0);
  9769. APath = ROOTDIRECTORY;
  9770. }
  9771. if (RemoteDirView->Path != APath)
  9772. {
  9773. RemoteDirView->Path = APath;
  9774. }
  9775. }
  9776. //---------------------------------------------------------------------------
  9777. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxItemClick(TObject * Sender)
  9778. {
  9779. DoRemotePathComboBoxItemClick(Sender);
  9780. }
  9781. //---------------------------------------------------------------------------
  9782. void __fastcall TCustomScpExplorerForm::DoRemotePathComboBoxCancel(TObject * Sender)
  9783. {
  9784. DebugAssert(Sender == GetComponent(fcRemotePathComboBox));
  9785. DebugUsedParam(Sender);
  9786. UpdateRemotePathComboBox(true);
  9787. }
  9788. //---------------------------------------------------------------------------
  9789. void __fastcall TCustomScpExplorerForm::RemotePathComboBoxCancel(TObject * Sender)
  9790. {
  9791. DoRemotePathComboBoxCancel(Sender);
  9792. }
  9793. //---------------------------------------------------------------------------
  9794. void __fastcall TCustomScpExplorerForm::DirViewEditing(
  9795. TObject * Sender, TListItem * Item, bool & /*AllowEdit*/)
  9796. {
  9797. ResetIncrementalSearch();
  9798. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  9799. DebugAssert(DirView != NULL);
  9800. if (!WinConfiguration->RenameWholeName && !DirView->ItemIsDirectory(Item))
  9801. {
  9802. HWND Edit = ListView_GetEditControl(DirView->Handle);
  9803. // OnEditing is called also from TCustomListView::CanEdit
  9804. if (Edit != NULL)
  9805. {
  9806. EditSelectBaseName(Edit);
  9807. }
  9808. }
  9809. }
  9810. //---------------------------------------------------------------------------
  9811. //---------------------------------------------------------------------------
  9812. TDragDropFilesEx * __fastcall TCustomScpExplorerForm::CreateDragDropFilesEx()
  9813. {
  9814. TDragDropFilesEx * Result = new TDragDropFilesEx(this);
  9815. Result->AutoDetectDnD = false;
  9816. Result->NeedValid = TFileExMustDnDSet() << nvFilename;
  9817. Result->RenderDataOn = rdoEnterAndDropSync;
  9818. Result->TargetEffects = TDropEffectSet() << deCopy << deMove;
  9819. return Result;
  9820. }
  9821. //---------------------------------------------------------------------------
  9822. void __fastcall TCustomScpExplorerForm::UpdateDarkMode()
  9823. {
  9824. if (IsWin10Build(19041))
  9825. {
  9826. FImmersiveDarkMode = WinConfiguration->UseDarkTheme();
  9827. BOOL DarkMode = FImmersiveDarkMode ? TRUE : FALSE;
  9828. const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
  9829. DwmSetWindowAttribute(Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, &DarkMode, sizeof(DarkMode));
  9830. }
  9831. }
  9832. //---------------------------------------------------------------------------
  9833. void __fastcall TCustomScpExplorerForm::CreateWnd()
  9834. {
  9835. TForm::CreateWnd();
  9836. // win32-darkmode calls AllowDarkModeForWindow(this, true) here, but it does not seem to have any effect
  9837. UpdateDarkMode();
  9838. if (FSessionsDragDropFilesEx == NULL)
  9839. {
  9840. FSessionsDragDropFilesEx = CreateDragDropFilesEx();
  9841. FSessionsDragDropFilesEx->OnDragOver = SessionsDDDragOver;
  9842. FSessionsDragDropFilesEx->OnProcessDropped = SessionsDDProcessDropped;
  9843. FSessionsDragDropFilesEx->OnDragEnter = SessionsDDDragEnter;
  9844. FSessionsDragDropFilesEx->OnDragLeave = SessionsDDDragLeave;
  9845. }
  9846. if (FQueueDragDropFilesEx == NULL)
  9847. {
  9848. FQueueDragDropFilesEx = CreateDragDropFilesEx();
  9849. // No need to set OnDragOver as we do not have any restrictions
  9850. FQueueDragDropFilesEx->OnProcessDropped = QueueDDProcessDropped;
  9851. FQueueDragDropFilesEx->OnDragEnter = QueueDDDragEnter;
  9852. FQueueDragDropFilesEx->OnDragLeave = QueueDDDragLeave;
  9853. }
  9854. }
  9855. //---------------------------------------------------------------------------
  9856. void __fastcall TCustomScpExplorerForm::DestroyWnd()
  9857. {
  9858. TForm::DestroyWnd();
  9859. FSessionsDragDropFilesEx->DragDropControl = NULL;
  9860. FQueueDragDropFilesEx->DragDropControl = NULL;
  9861. }
  9862. //---------------------------------------------------------------------------
  9863. void __fastcall TCustomScpExplorerForm::FormShow(TObject * /*Sender*/)
  9864. {
  9865. SideEnter(FCurrentSide);
  9866. FEverShown = true;
  9867. }
  9868. //---------------------------------------------------------------------------
  9869. void __fastcall TCustomScpExplorerForm::DoFindFiles(
  9870. TTerminal * ATerminal, UnicodeString Directory, const TFileMasks & FileMask,
  9871. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  9872. {
  9873. if (!NonVisualDataModule->Busy)
  9874. {
  9875. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9876. Configuration->Usage->Inc(L"FileFinds");
  9877. LockWindow(true);
  9878. NonVisualDataModule->StartBusy();
  9879. WinConfiguration->LockedInterface = true;
  9880. try
  9881. {
  9882. Terminal->FilesFind(Directory, FileMask, OnFileFound, OnFindingFile);
  9883. }
  9884. __finally
  9885. {
  9886. WinConfiguration->LockedInterface = false;
  9887. NonVisualDataModule->EndBusy();
  9888. UnlockWindow();
  9889. }
  9890. }
  9891. }
  9892. //---------------------------------------------------------------------------
  9893. void __fastcall TCustomScpExplorerForm::DoFocusRemotePath(TTerminal * ATerminal, const UnicodeString & Path)
  9894. {
  9895. if (!NonVisualDataModule->Busy)
  9896. {
  9897. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9898. SetFocus();
  9899. RemoteDirView->Path = UnixExtractFilePath(Path);
  9900. UnicodeString FileName = UnixExtractFileName(Path);
  9901. TListItem * Item = RemoteDirView->FindFileItem(FileName);
  9902. // If not found, it can because we have loaded directory from cache and the file is new, try again after reload.
  9903. // (tbd: we should not even try this, if we have not loaded the directory from the cache)
  9904. if (Item == NULL)
  9905. {
  9906. ReloadDirectory(osRemote);
  9907. Item = RemoteDirView->FindFileItem(FileName);
  9908. }
  9909. if (Item != NULL)
  9910. {
  9911. RemoteDirView->ItemFocused = Item;
  9912. RemoteDirView->ItemFocused->MakeVisible(false);
  9913. RemoteDirView->SetFocus();
  9914. }
  9915. }
  9916. }
  9917. //---------------------------------------------------------------------------
  9918. bool __fastcall TCustomScpExplorerForm::CanOperateOnFoundFiles(TTerminal * ATerminal)
  9919. {
  9920. bool Result = !NonVisualDataModule->Busy;
  9921. if (Result)
  9922. {
  9923. TTerminalManager::Instance()->ActiveSession = DebugNotNull(dynamic_cast<TManagedTerminal *>(ATerminal));
  9924. }
  9925. return Result;
  9926. }
  9927. //---------------------------------------------------------------------------
  9928. void __fastcall TCustomScpExplorerForm::DoOperationOnFoundFiles(
  9929. TFileOperation Operation, TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9930. {
  9931. if (CanOperateOnFoundFiles(ATerminal))
  9932. {
  9933. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished, OnFileOperationFinished);
  9934. ExecuteFileOperation(Operation, osRemote, FileList, false, NULL);
  9935. }
  9936. }
  9937. //---------------------------------------------------------------------------
  9938. void __fastcall TCustomScpExplorerForm::DoDeleteFoundFiles(
  9939. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9940. {
  9941. DoOperationOnFoundFiles(foDelete, ATerminal, FileList, OnFileOperationFinished);
  9942. }
  9943. //---------------------------------------------------------------------------
  9944. void __fastcall TCustomScpExplorerForm::DoDownloadFoundFiles(
  9945. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9946. {
  9947. DoOperationOnFoundFiles(foCopy, ATerminal, FileList, OnFileOperationFinished);
  9948. }
  9949. //---------------------------------------------------------------------------
  9950. void __fastcall TCustomScpExplorerForm::DoEditFoundFiles(
  9951. TTerminal * ATerminal, TStrings * FileList, TFileOperationFinishedEvent OnFileOperationFinished)
  9952. {
  9953. if (CanOperateOnFoundFiles(ATerminal))
  9954. {
  9955. for (int Index = 0; Index < FileList->Count; Index++)
  9956. {
  9957. UnicodeString FileName = FileList->Strings[Index];
  9958. TRemoteFile * File = static_cast<TRemoteFile *>(FileList->Objects[Index]);
  9959. ExecuteRemoteFile(FileName, File, efDefaultEditor);
  9960. OnFileOperationFinished(osRemote, FileName, true);
  9961. }
  9962. }
  9963. }
  9964. //---------------------------------------------------------------------------
  9965. void __fastcall TCustomScpExplorerForm::RemoteFindFiles()
  9966. {
  9967. FFileFindTerminal = Terminal;
  9968. ShowFileFindDialog(
  9969. Terminal, RemoteDirView->Path, DoFindFiles, DoFocusRemotePath, DoDeleteFoundFiles,
  9970. DoDownloadFoundFiles, DoEditFoundFiles);
  9971. }
  9972. //---------------------------------------------------------------------------
  9973. void __fastcall TCustomScpExplorerForm::UpdateTaskbarList(ITaskbarList3 * TaskbarList)
  9974. {
  9975. FTaskbarList = TaskbarList;
  9976. }
  9977. //---------------------------------------------------------------------------
  9978. void __fastcall TCustomScpExplorerForm::SessionsPageControlMouseDown(
  9979. TObject * /*Sender*/, TMouseButton Button, TShiftState /*Shift*/, int X, int Y)
  9980. {
  9981. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  9982. if (Index >= 0)
  9983. {
  9984. if (Button == mbLeft)
  9985. {
  9986. // WORKAROUND: "Mouse down" is raised only after tab is switched.
  9987. // If switching tab (switching session) takes long enough for user
  9988. // to actually release the button, "mouse down" is still raised,
  9989. // but we do not get "mouse up" event, so dragging is not cancelled,
  9990. // prevent that by not beginning dragging in the first place.
  9991. int Key = ((GetSystemMetrics(SM_SWAPBUTTON) == 0) ? VK_LBUTTON : VK_RBUTTON);
  9992. if (IsKeyPressed(Key))
  9993. {
  9994. // when user clicks the "+", we get mouse down only after the session
  9995. // is closed, when new session tab is already on X:Y, so dragging
  9996. // starts, prevent that
  9997. if (MilliSecondsBetween(Now(), FSessionsPageControlNewTabTime) > 500)
  9998. {
  9999. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10000. if (Terminal != NULL)
  10001. {
  10002. SessionsPageControl->BeginDrag(false);
  10003. }
  10004. }
  10005. }
  10006. }
  10007. else if (Button == mbMiddle)
  10008. {
  10009. // ignore middle-click for "New session tab" and the last local-local tab
  10010. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10011. if ((Session != NULL) && CanCloseSession(Session))
  10012. {
  10013. CloseSessionTab(Index);
  10014. }
  10015. }
  10016. }
  10017. }
  10018. //---------------------------------------------------------------------------
  10019. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragDrop(
  10020. TObject * /*Sender*/, TObject * /*Source*/, int X, int Y)
  10021. {
  10022. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10023. // do not allow dropping on the "+" tab
  10024. TTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10025. if ((TargetTerminal != NULL) &&
  10026. (SessionsPageControl->ActivePage->PageIndex != Index))
  10027. {
  10028. Configuration->Usage->Inc(L"SessionTabMoves");
  10029. // this is almost redundant as we would recreate tabs in SessionListChanged,
  10030. // but we want to actually prevent that to avoid flicker
  10031. SessionsPageControl->ActivePage->PageIndex = Index;
  10032. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->ActivePage);
  10033. TTerminalManager::Instance()->Move(Terminal, TargetTerminal);
  10034. }
  10035. }
  10036. //---------------------------------------------------------------------------
  10037. void __fastcall TCustomScpExplorerForm::SessionsPageControlDragOver(
  10038. TObject * Sender, TObject * Source, int X, int Y,
  10039. TDragState /*State*/, bool & Accept)
  10040. {
  10041. Accept = (Sender == Source);
  10042. if (Accept)
  10043. {
  10044. int Index = SessionsPageControl->IndexOfTabAt(X, Y);
  10045. TTerminal * Terminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10046. // do not allow dragging to the "+" tab
  10047. Accept = (Terminal != NULL);
  10048. }
  10049. }
  10050. //---------------------------------------------------------------------------
  10051. void __fastcall TCustomScpExplorerForm::SessionsDDDragOver(
  10052. int DebugUsedArg(KeyState), const TPoint & Point, int & Effect, int DebugUsedArg(PreferredEffect))
  10053. {
  10054. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10055. if (Index < 0)
  10056. {
  10057. Effect = DROPEFFECT_NONE;
  10058. }
  10059. else
  10060. {
  10061. TManagedTerminal * TargetSession = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10062. // do not allow dropping on the "+" tab or on disconnected or local-local tabs
  10063. if (!IsActiveTerminal(TargetSession) || DebugAlwaysFalse(TargetSession->LocalBrowser))
  10064. {
  10065. Effect = DROPEFFECT_NONE;
  10066. }
  10067. else if ((TargetSession != Terminal) && (Effect == DROPEFFECT_MOVE))
  10068. {
  10069. Effect = DROPEFFECT_COPY;
  10070. }
  10071. }
  10072. }
  10073. //---------------------------------------------------------------------------
  10074. void __fastcall TCustomScpExplorerForm::SessionsDDProcessDropped(
  10075. TObject * /*Sender*/, int /*KeyState*/, const TPoint & Point, int Effect)
  10076. {
  10077. int Index = SessionsPageControl->IndexOfTabAt(Point.X, Point.Y);
  10078. // do not allow dropping on local-local, disconnected and the "+" tab
  10079. // (though we do not seem to get here in that case anyway, contrary to RemoteFileControlDDTargetDrop)
  10080. TManagedTerminal * TargetTerminal = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10081. if (DebugAlwaysTrue(IsActiveTerminal(TargetTerminal) && !TargetTerminal->LocalBrowser))
  10082. {
  10083. DebugAssert(!IsFileControl(DropSourceControl, osRemote));
  10084. if (!IsFileControl(DropSourceControl, osRemote))
  10085. {
  10086. TTerminalManager::Instance()->ActiveSession = TargetTerminal;
  10087. RemoteFileControlDragDropFileOperation(SessionsPageControl, Effect,
  10088. // Why don't we use Terminal->CurrentDirectory directly?
  10089. TTerminalManager::Instance()->ActiveTerminal->CurrentDirectory,
  10090. // do not force queue, drag drop
  10091. false, true);
  10092. }
  10093. }
  10094. }
  10095. //---------------------------------------------------------------------------
  10096. void __fastcall TCustomScpExplorerForm::QueueDDProcessDropped(
  10097. TObject * /*Sender*/, int /*KeyState*/, const TPoint & /*Point*/, int Effect)
  10098. {
  10099. // Downloads are handled in RemoteFileControlDDEnd
  10100. if (!IsFileControl(DropSourceControl, osRemote))
  10101. {
  10102. RemoteFileControlDragDropFileOperation(QueueView3, Effect,
  10103. Terminal->CurrentDirectory,
  10104. // force queue, drag drop
  10105. true, true);
  10106. }
  10107. }
  10108. //---------------------------------------------------------------------------
  10109. void __fastcall TCustomScpExplorerForm::FormClose(TObject * /*Sender*/, TCloseAction & /*Action*/)
  10110. {
  10111. FShowing = false;
  10112. // Do not save empty workspace
  10113. if (WinConfiguration->AutoSaveWorkspace && (ManagedSession != NULL))
  10114. {
  10115. std::unique_ptr<TObjectList> DataList(DoCollectWorkspace());
  10116. UnicodeString Name = WorkspaceName();
  10117. DoSaveWorkspace(
  10118. Name, DataList.get(),
  10119. !Configuration->DisablePasswordStoring &&
  10120. WinConfiguration->AutoSaveWorkspacePasswords, false);
  10121. WinConfiguration->LastStoredSession = Name;
  10122. }
  10123. AppLog(L"Closing main window");
  10124. }
  10125. //---------------------------------------------------------------------------
  10126. void __fastcall TCustomScpExplorerForm::RemoteDirViewRead(TObject * /*Sender*/)
  10127. {
  10128. TManagedTerminal * ManagedTerminal =
  10129. dynamic_cast<TManagedTerminal *>(RemoteDirView->Terminal);
  10130. if (ManagedTerminal != NULL)
  10131. {
  10132. ManagedTerminal->DirectoryLoaded = Now();
  10133. }
  10134. }
  10135. //---------------------------------------------------------------------------
  10136. void __fastcall TCustomScpExplorerForm::DirViewSelectItem(TObject * Sender,
  10137. TListItem * /*Item*/, bool /*Selected*/)
  10138. {
  10139. TCustomDirView * DirView = reinterpret_cast<TCustomDirView *>(Sender);
  10140. switch (DirView->LastSelectMethod)
  10141. {
  10142. case smKeyboard:
  10143. Configuration->Usage->Inc(L"KeyboardSelections");
  10144. break;
  10145. case smMouse:
  10146. Configuration->Usage->Inc(L"MouseSelections");
  10147. break;
  10148. }
  10149. }
  10150. //---------------------------------------------------------------------------
  10151. int __fastcall TCustomScpExplorerForm::AddSessionColor(TColor Color)
  10152. {
  10153. if (Color != 0)
  10154. {
  10155. return GetSessionColorImage(FSessionColors, Color, FSessionColorMaskImageIndex);
  10156. }
  10157. else
  10158. {
  10159. return FSessionTabImageIndex;
  10160. }
  10161. }
  10162. //---------------------------------------------------------------------------
  10163. int __fastcall TCustomScpExplorerForm::AddFixedSessionImage(int GlyphsSourceIndex)
  10164. {
  10165. TPngImageCollectionItem * Item =
  10166. GlyphsModule->ExplorerImages->PngImages->Items[GlyphsSourceIndex];
  10167. FSessionColors->AddPng(Item->PngImage);
  10168. return FSessionColors->Count - 1;
  10169. }
  10170. //---------------------------------------------------------------------------
  10171. void __fastcall TCustomScpExplorerForm::AddFixedSessionImages()
  10172. {
  10173. FSessionColors->SetSize(GlyphsModule->ExplorerImages->Width, GlyphsModule->ExplorerImages->Height);
  10174. FNewRemoteTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewRemoteTabAction->ImageIndex);
  10175. FNewLocalTabTabImageIndex = AddFixedSessionImage(NonVisualDataModule->NewLocalTabAction->ImageIndex);
  10176. FSessionTabImageIndex = AddFixedSessionImage(SiteImageIndex);
  10177. FSessionColorMaskImageIndex = AddFixedSessionImage(SiteColorMaskImageIndex);
  10178. FLocalBrowserTabImageIndex = AddFixedSessionImage(LocalBrowserImageIndex);
  10179. }
  10180. //---------------------------------------------------------------------------
  10181. int TCustomScpExplorerForm::GetNewTabActionImageIndex()
  10182. {
  10183. return NonVisualDataModule->NewRemoteTabAction->ImageIndex;
  10184. }
  10185. //---------------------------------------------------------------------------
  10186. int TCustomScpExplorerForm::GetNewTabTabImageIndex(TOperationSide Side)
  10187. {
  10188. switch (Side)
  10189. {
  10190. case osLocal:
  10191. return FNewLocalTabTabImageIndex;
  10192. case osRemote:
  10193. case osCurrent:
  10194. return FNewRemoteTabTabImageIndex;
  10195. default:
  10196. DebugFail();
  10197. return -1;
  10198. }
  10199. }
  10200. //---------------------------------------------------------------------------
  10201. void __fastcall TCustomScpExplorerForm::CollectItemsWithTextDisplayMode(TWinControl * Control)
  10202. {
  10203. for (int Index = 0; Index < Control->ControlCount; Index++)
  10204. {
  10205. TControl * AControl = Control->Controls[Index];
  10206. TWinControl * WinControl = dynamic_cast<TWinControl *>(AControl);
  10207. if (WinControl != NULL)
  10208. {
  10209. CollectItemsWithTextDisplayMode(WinControl);
  10210. }
  10211. TTBCustomToolbar * Toolbar = dynamic_cast<TTBCustomToolbar *>(AControl);
  10212. if (Toolbar != NULL)
  10213. {
  10214. // we care for top-level items only
  10215. TTBCustomItem * Items = Toolbar->Items;
  10216. for (int ItemIndex = 0; ItemIndex < Items->Count; ItemIndex++)
  10217. {
  10218. TTBCustomItem * Item = Items->Items[ItemIndex];
  10219. if (((Item->DisplayMode == nbdmImageAndText) ||
  10220. (dynamic_cast<TTBXLabelItem *>(Item) != NULL)) &&
  10221. EligibleForImageDisplayMode(Item))
  10222. {
  10223. FItemsWithTextDisplayMode.insert(Item);
  10224. }
  10225. }
  10226. }
  10227. }
  10228. }
  10229. //---------------------------------------------------------------------------
  10230. bool __fastcall TCustomScpExplorerForm::EligibleForImageDisplayMode(TTBCustomItem * /*Item*/)
  10231. {
  10232. return true;
  10233. }
  10234. //---------------------------------------------------------------------------
  10235. bool __fastcall TCustomScpExplorerForm::UpdateToolbarDisplayMode()
  10236. {
  10237. bool SelectiveToolbarText = WinConfiguration->SelectiveToolbarText;
  10238. TTBItemDisplayMode DisplayMode = (SelectiveToolbarText ? nbdmImageAndText : nbdmDefault);
  10239. typedef std::set<TTBCustomItem *> TItemsWithTextDisplayMode;
  10240. TItemsWithTextDisplayMode::iterator i = FItemsWithTextDisplayMode.begin();
  10241. bool Result = true;
  10242. while (Result && (i != FItemsWithTextDisplayMode.end()))
  10243. {
  10244. TTBCustomItem * Item = *i;
  10245. TTBXLabelItem * Label = dynamic_cast<TTBXLabelItem *>(Item);
  10246. if (Label != NULL)
  10247. {
  10248. // optimization
  10249. if (Label->Visible == SelectiveToolbarText)
  10250. {
  10251. Result = false;
  10252. }
  10253. else
  10254. {
  10255. Label->Visible = SelectiveToolbarText;
  10256. }
  10257. }
  10258. else
  10259. {
  10260. // optimization
  10261. if (Item->DisplayMode == DisplayMode)
  10262. {
  10263. Result = false;
  10264. }
  10265. else
  10266. {
  10267. Item->DisplayMode = DisplayMode;
  10268. }
  10269. }
  10270. ++i;
  10271. }
  10272. UpdateNewTabTab();
  10273. return Result;
  10274. }
  10275. //---------------------------------------------------------------------------
  10276. void __fastcall TCustomScpExplorerForm::DisplaySystemContextMenu()
  10277. {
  10278. DebugFail();
  10279. }
  10280. //---------------------------------------------------------------------------
  10281. bool __fastcall TCustomScpExplorerForm::IsBusy()
  10282. {
  10283. // Among other, a lock level is non zero, while directory is being loaded,
  10284. // even when it happens as a result of dirview navigation,
  10285. // i.e. when TNonVisualDataModule is NOT FBusy.
  10286. // That's why the TNonVisualDataModule::GetBusy calls this method.
  10287. // Among other this prevents a panel auto update to occur while
  10288. // directory is changing.
  10289. return (FLockLevel > 0) || DirView(osCurrent)->IsEditing();
  10290. }
  10291. //---------------------------------------------------------------------------
  10292. Boolean __fastcall TCustomScpExplorerForm::AllowedAction(TAction * Action, TActionAllowed Allowed)
  10293. {
  10294. // While the window is disabled, we still seem to process menu shortcuts at least,
  10295. // so stop it at least here.
  10296. // See also TCustomScpExplorerForm::RemoteDirViewBusy
  10297. bool Result;
  10298. if (Allowed == aaUpdate)
  10299. {
  10300. Result = true;
  10301. }
  10302. else
  10303. {
  10304. Result = !NonVisualDataModule->Busy;
  10305. if (Result && (Allowed == aaShortCut))
  10306. {
  10307. // Otherwise F5 for local-local will be swallowed by disabled local<>remote actions in TCustomScpExplorerForm::KeyDown
  10308. Action->Update();
  10309. Result = Action->Enabled;
  10310. }
  10311. }
  10312. return Result;
  10313. }
  10314. //---------------------------------------------------------------------------
  10315. void __fastcall TCustomScpExplorerForm::EditMenuItemPopup(TTBCustomItem * Sender, bool FromLink)
  10316. {
  10317. NonVisualDataModule->EditMenuItemPopup(Sender, FromLink);
  10318. }
  10319. //---------------------------------------------------------------------------
  10320. void __fastcall TCustomScpExplorerForm::DirViewBusy(TObject * /*Sender*/, int Busy, bool & State)
  10321. {
  10322. // This is somewhat redundant to LockWindow() call from
  10323. // TTerminalManager::TerminalReadDirectoryProgress.
  10324. // But disabling window is known not to block keyboard shorcuts
  10325. // (see TCustomScpExplorerForm::AllowedAction), this hopefully works.
  10326. if (Busy > 0)
  10327. {
  10328. if (NonVisualDataModule->Busy)
  10329. {
  10330. State = false;
  10331. }
  10332. else
  10333. {
  10334. NonVisualDataModule->StartBusy();
  10335. // Will be countered for TCustomDirView.DoExecute in DoDirViewExecFile
  10336. LockWindow();
  10337. }
  10338. }
  10339. else if (Busy < 0)
  10340. {
  10341. UnlockWindow();
  10342. NonVisualDataModule->EndBusy();
  10343. }
  10344. else
  10345. {
  10346. State = NonVisualDataModule->Busy;
  10347. }
  10348. }
  10349. //---------------------------------------------------------------------------
  10350. void __fastcall TCustomScpExplorerForm::SessionsPageControlContextPopup(TObject * /*Sender*/, TPoint & MousePos, bool & Handled)
  10351. {
  10352. int Index = SessionsPageControl->IndexOfTabAt(MousePos.X, MousePos.Y);
  10353. if (Index >= 0)
  10354. {
  10355. TPopupMenu * PopupMenu = NULL;
  10356. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10357. if (Session != NULL)
  10358. {
  10359. SessionsPageControl->ActivePageIndex = Index;
  10360. if (DebugAlwaysTrue(SessionTabSwitched()))
  10361. {
  10362. // copied from TControl.WMContextMenu
  10363. SendCancelMode(SessionsPageControl);
  10364. // explicit popup instead of using PopupMenu property
  10365. // to avoid menu to popup somewhere within SessionTabSwitched above,
  10366. // while connecting yet not-connected session and hence
  10367. // allowing an access to commands over not-completely connected session
  10368. PopupMenu = Session->LocalBrowser ? NonVisualDataModule->LocalBrowserPopup : NonVisualDataModule->SessionsPopup;
  10369. }
  10370. }
  10371. else
  10372. {
  10373. if (SupportsLocalBrowser())
  10374. {
  10375. PopupMenu = NonVisualDataModule->NewTabPopup;
  10376. }
  10377. }
  10378. if (PopupMenu != NULL)
  10379. {
  10380. TPoint Point = SessionsPageControl->ClientToScreen(MousePos);
  10381. PopupMenu->PopupComponent = SessionsPageControl;
  10382. PopupMenu->Popup(Point.x, Point.y);
  10383. }
  10384. }
  10385. Handled = true;
  10386. }
  10387. //---------------------------------------------------------------------------
  10388. bool __fastcall TCustomScpExplorerForm::CanChangePassword()
  10389. {
  10390. return HasActiveTerminal() && Terminal->IsCapable[fcChangePassword];
  10391. }
  10392. //---------------------------------------------------------------------------
  10393. void __fastcall TCustomScpExplorerForm::ChangePassword()
  10394. {
  10395. Configuration->Usage->Inc(L"PasswordChanges");
  10396. std::unique_ptr<TSessionData> ChangePasswordData(Terminal->SessionData->Clone());
  10397. ChangePasswordData->DisableAuthentationsExceptPassword();
  10398. ChangePasswordData->ChangePassword = true;
  10399. std::unique_ptr<TTerminal> ChangePasswordSession(
  10400. Terminal->CreateSecondarySession(L"ChangePassword", ChangePasswordData.get()));
  10401. ChangePasswordSession->AutoReadDirectory = false;
  10402. if (TTerminalManager::Instance()->ConnectTerminal(ChangePasswordSession.get()))
  10403. {
  10404. MessageDialog(MainInstructions(LoadStr(PASSWORD_CHANGED)), qtInformation, qaOK, HELP_CHANGE_PASSWORD);
  10405. }
  10406. else
  10407. {
  10408. Configuration->Usage->Inc(L"PasswordChangesFailed");
  10409. }
  10410. }
  10411. //---------------------------------------------------------------------------
  10412. bool __fastcall TCustomScpExplorerForm::CanPrivateKeyUpload()
  10413. {
  10414. // No nice way to assert SSH2
  10415. return HasActiveTerminal() && (Terminal->FSProtocol == cfsSFTP);
  10416. }
  10417. //---------------------------------------------------------------------------
  10418. void __fastcall TCustomScpExplorerForm::PrivateKeyUpload()
  10419. {
  10420. TOperationVisualizer OperationVisualizer;
  10421. UnicodeString FileName = Terminal->SessionData->PublicKeyFile;
  10422. TTerminalManager::Instance()->UploadPublicKey(Terminal, NULL, FileName);
  10423. }
  10424. //---------------------------------------------------------------------------
  10425. void __fastcall TCustomScpExplorerForm::ChangeScale(int M, int D)
  10426. {
  10427. TForm::ChangeScale(M, D);
  10428. int APixelsPerInch = GetControlPixelsPerInch(this);
  10429. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  10430. try
  10431. {
  10432. GlyphsModule->SetPixelsPerInch(APixelsPerInch);
  10433. }
  10434. __finally
  10435. {
  10436. GUIConfiguration->ChangeResourceModule(ResourceModule);
  10437. }
  10438. }
  10439. //---------------------------------------------------------------------------
  10440. void __fastcall TCustomScpExplorerForm::DockContextPopup(TObject * Sender, TPoint & MousePos, bool & /*Handled*/)
  10441. {
  10442. NonVisualDataModule->ControlContextPopup(Sender, MousePos);
  10443. }
  10444. //---------------------------------------------------------------------
  10445. class TPublicControl : public TControl
  10446. {
  10447. friend class TCustomScpExplorerForm;
  10448. };
  10449. //---------------------------------------------------------------------------
  10450. void __fastcall TCustomScpExplorerForm::CopyPopup(TControl * DestControl, TControl * SourceControl)
  10451. {
  10452. static_cast<TPublicControl *>(DestControl)->PopupMenu = static_cast<TPublicControl *>(SourceControl)->PopupMenu;
  10453. static_cast<TPublicControl *>(DestControl)->OnContextPopup = static_cast<TPublicControl *>(SourceControl)->OnContextPopup;
  10454. }
  10455. //---------------------------------------------------------------------------
  10456. void __fastcall TCustomScpExplorerForm::DoBookmarkClick(TOperationSide Side, TObject * Sender)
  10457. {
  10458. TBookmark * Bookmark = DebugNotNull(reinterpret_cast<TBookmark *>(dynamic_cast<TTBCustomItem *>(Sender)->Tag));
  10459. OpenBookmark(Side, Bookmark);
  10460. }
  10461. //---------------------------------------------------------------------------
  10462. void __fastcall TCustomScpExplorerForm::LocalBookmarkClick(TObject * Sender)
  10463. {
  10464. DoBookmarkClick(osLocal, Sender);
  10465. }
  10466. //---------------------------------------------------------------------------
  10467. void __fastcall TCustomScpExplorerForm::RemoteBookmarkClick(TObject * Sender)
  10468. {
  10469. DoBookmarkClick(osRemote, Sender);
  10470. }
  10471. //---------------------------------------------------------------------------
  10472. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenuList(
  10473. TTBCustomItem * Menu, TOperationSide Side, TBookmarkList * BookmarkList)
  10474. {
  10475. if (BookmarkList != NULL)
  10476. {
  10477. TNotifyEvent OnBookmarkClick = (Side == osLocal) ? &LocalBookmarkClick : &RemoteBookmarkClick;
  10478. if (IsLocalBrowserMode())
  10479. {
  10480. Side = osLocal;
  10481. }
  10482. if (!WinConfiguration->UseLocationProfiles)
  10483. {
  10484. std::unique_ptr<TStringList> Directories(new TStringList());
  10485. Directories->CaseSensitive = (Side == osRemote);
  10486. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10487. {
  10488. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10489. UnicodeString Directory = Bookmark->GetSideDirectory(Side);
  10490. if (!Directory.IsEmpty() && (Directories->IndexOf(Directory) < 0))
  10491. {
  10492. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10493. Item->Caption = EscapeHotkey(Directory);
  10494. Item->ShortCut = Bookmark->ShortCut;
  10495. Item->OnClick = OnBookmarkClick;
  10496. Item->Tag = reinterpret_cast<int>(Bookmark);
  10497. Directories->Add(Directory);
  10498. Menu->Add(Item.release());
  10499. }
  10500. }
  10501. }
  10502. else
  10503. {
  10504. std::unique_ptr<TStrings> Folders(CreateSortedStringList());
  10505. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10506. {
  10507. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10508. if (!Bookmark->Node.IsEmpty())
  10509. {
  10510. Folders->Add(Bookmark->Node);
  10511. }
  10512. }
  10513. for (int Index = 0; Index < Folders->Count; Index++)
  10514. {
  10515. std::unique_ptr<TTBCustomItem> Item(new TTBXSubmenuItem(Owner));
  10516. Item->Caption = Folders->Strings[Index];
  10517. Item->ImageIndex = NonVisualDataModule->RemoteChangePathAction2->ImageIndex;
  10518. Folders->Objects[Index] = Item.get();
  10519. Menu->Add(Item.release());
  10520. }
  10521. for (int Index = 0; Index < BookmarkList->Count; Index++)
  10522. {
  10523. TBookmark * Bookmark = BookmarkList->Bookmarks[Index];
  10524. TTBCustomItem * Parent;
  10525. if (!Bookmark->Node.IsEmpty())
  10526. {
  10527. DebugAssert(Folders->IndexOf(Bookmark->Node) >= 0);
  10528. Parent = dynamic_cast<TTBCustomItem *>(Folders->Objects[Folders->IndexOf(Bookmark->Node)]);
  10529. }
  10530. else
  10531. {
  10532. Parent = Menu;
  10533. }
  10534. std::unique_ptr<TTBCustomItem> Item(new TTBXItem(Owner));
  10535. Item->Caption = Bookmark->Name;
  10536. Item->ShortCut = Bookmark->ShortCut;
  10537. Item->OnClick = OnBookmarkClick;
  10538. Item->Tag = reinterpret_cast<int>(Bookmark);
  10539. if (((Bookmark->Name == Bookmark->Local) || (Bookmark->Name == Bookmark->Remote)) &&
  10540. (Bookmark->Local.IsEmpty() || Bookmark->Remote.IsEmpty()))
  10541. {
  10542. // No hint for location profiles that are actually mere "bookmarks"
  10543. }
  10544. else
  10545. {
  10546. UnicodeString Hint = FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 1), (Bookmark->Name));
  10547. UnicodeString LongHint;
  10548. if (!Bookmark->Local.IsEmpty())
  10549. {
  10550. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 2), (Bookmark->Local)), L"\n");
  10551. }
  10552. if (!Bookmark->Remote.IsEmpty())
  10553. {
  10554. AddToList(LongHint, FORMAT(LoadStrPart(LOCATION_PROFILE_HINT, 3), (Bookmark->Remote)), L"\n");
  10555. }
  10556. AddToList(Hint, LongHint, L"|");
  10557. Item->Hint = Hint;
  10558. }
  10559. Parent->Add(Item.release());
  10560. }
  10561. }
  10562. AddMenuSeparator(Menu);
  10563. }
  10564. }
  10565. //---------------------------------------------------------------------------
  10566. void __fastcall TCustomScpExplorerForm::CreateOpenDirMenu(TTBCustomItem * Menu, TOperationSide Side)
  10567. {
  10568. Menu->Clear();
  10569. std::unique_ptr<TTBCustomItem> Item;
  10570. Item.reset(new TTBXItem(Owner));
  10571. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalOpenDirAction : NonVisualDataModule->RemoteOpenDirAction;
  10572. Item->Options = Item->Options << tboDefault;
  10573. Menu->Add(Item.release());
  10574. AddMenuSeparator(Menu);
  10575. if (Terminal != NULL)
  10576. {
  10577. CreateOpenDirMenuList(Menu, Side, WinConfiguration->Bookmarks[Terminal->SessionData->SessionKey]);
  10578. }
  10579. CreateOpenDirMenuList(Menu, Side, WinConfiguration->SharedBookmarks);
  10580. Item.reset(new TTBXItem(Owner));
  10581. Item->Action = (Side == osLocal) ? NonVisualDataModule->LocalAddBookmarkAction2 : NonVisualDataModule->RemoteAddBookmarkAction2;
  10582. Menu->Add(Item.release());
  10583. }
  10584. //---------------------------------------------------------------------------
  10585. bool __fastcall TCustomScpExplorerForm::TryOpenDirectory(TOperationSide Side, const UnicodeString & Path)
  10586. {
  10587. bool Result = true;
  10588. bool Remote = !IsSideLocalBrowser(Side);
  10589. try
  10590. {
  10591. UnicodeString APath = Path;
  10592. if (Remote)
  10593. {
  10594. Terminal->ExceptionOnFail = true;
  10595. }
  10596. else
  10597. {
  10598. APath = ExpandEnvironmentVariables(Path);
  10599. }
  10600. try
  10601. {
  10602. DirView(Side)->Path = APath;
  10603. }
  10604. __finally
  10605. {
  10606. if (Remote)
  10607. {
  10608. Terminal->ExceptionOnFail = false;
  10609. }
  10610. }
  10611. }
  10612. catch (Exception & E)
  10613. {
  10614. if (!Remote || Terminal->Active)
  10615. {
  10616. ShowExtendedExceptionEx(Terminal, &E);
  10617. Result = false;
  10618. }
  10619. else
  10620. {
  10621. throw;
  10622. }
  10623. }
  10624. return Result;
  10625. }
  10626. //---------------------------------------------------------------------------
  10627. void __fastcall TCustomScpExplorerForm::ReloadDirectory(TOperationSide Side)
  10628. {
  10629. // Make sure there some feedback even when loading tiny local folders
  10630. TInstantOperationVisualizer Visualizer;
  10631. DirView(Side)->ReloadDirectory();
  10632. }
  10633. //---------------------------------------------------------------------------
  10634. void __fastcall TCustomScpExplorerForm::CloseSessionTab(int Index)
  10635. {
  10636. if (Index == SessionsPageControl->TabIndex)
  10637. {
  10638. CloseTab();
  10639. }
  10640. else
  10641. {
  10642. TTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  10643. TTerminal * Terminal = GetSessionTabSession(TabSheet);
  10644. TTerminalManager * Manager = TTerminalManager::Instance();
  10645. if (!Terminal->Active)
  10646. {
  10647. Manager->FreeTerminal(Terminal);
  10648. }
  10649. else
  10650. {
  10651. TTerminalQueue * Queue = Manager->FindQueueForTerminal(Terminal);
  10652. if (CanCloseQueue(Queue))
  10653. {
  10654. Manager->FreeTerminal(Terminal);
  10655. }
  10656. }
  10657. }
  10658. }
  10659. //---------------------------------------------------------------------------
  10660. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabButtonClick(TPageControl *, int Index)
  10661. {
  10662. TManagedTerminal * Session = GetSessionTabSession(SessionsPageControl->Pages[Index]);
  10663. if (Session == NULL)
  10664. {
  10665. TRect ButtonRect = SessionsPageControl->TabButtonRect(Index);
  10666. ButtonRect = TRect(SessionsPageControl->ClientToScreen(ButtonRect.TopLeft()), SessionsPageControl->ClientToScreen(ButtonRect.BottomRight()));
  10667. //TPoint P = TPoint(ButtonRect.Left, ButtonRect.Bottom);
  10668. //P = SessionsPageControl->ClientToScreen(P);
  10669. MenuPopup(NonVisualDataModule->NewTabPopup, ButtonRect, SessionsPageControl);
  10670. }
  10671. else
  10672. {
  10673. CloseSessionTab(Index);
  10674. }
  10675. }
  10676. //---------------------------------------------------------------------------
  10677. void __fastcall TCustomScpExplorerForm::CopyFilesToClipboard(TOperationSide Side, bool OnFocused)
  10678. {
  10679. if (DebugAlwaysTrue(!IsSideLocalBrowser(Side)))
  10680. {
  10681. TInstantOperationVisualizer Visualizer;
  10682. // To trigger ClipboardDataObjectRelease (in case the clipboard already contains our data)
  10683. // before we create a new data object
  10684. ClipboardClear();
  10685. DebugAssert(FClipboardFakeDirectory.IsEmpty());
  10686. DebugAssert(FClipboardFakeMonitors.get() == NULL);
  10687. FClipboardFakeDirectory = CreateFakeTransferDirectory();
  10688. // Intermediate variable to WORKAROUND a crash in compiler
  10689. TObjectList * ClipboardFakeMonitors =
  10690. StartCreationDirectoryMonitorsOnEachDrive(FILE_NOTIFY_CHANGE_DIR_NAME, ClipboardFakeCreated);
  10691. FClipboardFakeMonitors.reset(ClipboardFakeMonitors);
  10692. if (FClipboardDragDropFilesEx.get() == NULL)
  10693. {
  10694. FClipboardDragDropFilesEx.reset(new TDragDropFilesEx(this));
  10695. FClipboardDragDropFilesEx->OnDataObjectRelease = ClipboardDataObjectRelease;
  10696. }
  10697. FClipboardDragDropFilesEx->FileList->Clear();
  10698. FClipboardDragDropFilesEx->FileList->AddItem(NULL, FClipboardFakeDirectory);
  10699. FClipboardDragDropFilesEx->CopyToClipboard();
  10700. FClipboardTerminal = Terminal;
  10701. // Need full paths, as cwd can be different once files are pasted
  10702. FClipboardFileList.reset(TRemoteFileList::CloneStrings(RemoteDirView->CreateFileList(OnFocused, true)));
  10703. for (int Index = 0; Index < FClipboardFileList->Count; Index++)
  10704. {
  10705. FClipboardFileList->Strings[Index] = UnixExcludeTrailingBackslash(FClipboardFileList->Strings[Index]);
  10706. }
  10707. AppLogFmt(L"Created fake clipboard directory \"%s\" and started drive monitors", (FClipboardFakeDirectory));
  10708. }
  10709. }
  10710. //---------------------------------------------------------------------------
  10711. void __fastcall TCustomScpExplorerForm::ClipboardClear()
  10712. {
  10713. if (OpenClipboard(0))
  10714. {
  10715. AppLog(L"Clearing clipboard");
  10716. EmptyClipboard(); // Calls ClipboardDataObjectRelease, if clipboard contains our data
  10717. CloseClipboard();
  10718. }
  10719. }
  10720. //---------------------------------------------------------------------------
  10721. bool __fastcall TCustomScpExplorerForm::DoesClipboardContainOurFiles()
  10722. {
  10723. return !FClipboardFakeDirectory.IsEmpty();
  10724. }
  10725. //---------------------------------------------------------------------------
  10726. void __fastcall TCustomScpExplorerForm::ClipboardStop()
  10727. {
  10728. bool Deleted = RemoveDir(ApiPath(FClipboardFakeDirectory));
  10729. AppLogFmt(L"Clearing clipboard, deleted clipboard temporary folder \"%s\" - %d", (FClipboardFakeDirectory, int(Deleted)));
  10730. FClipboardFakeDirectory = UnicodeString();
  10731. FClipboardTerminal = NULL;
  10732. if (FDownloadingFromClipboard)
  10733. {
  10734. // We are called by the monitor, so attempt to release it would deadlock
  10735. FClipboardFakeMonitorsPendingReset = true;
  10736. }
  10737. else
  10738. {
  10739. FClipboardFakeMonitors.reset(NULL);
  10740. }
  10741. }
  10742. //---------------------------------------------------------------------------
  10743. void __fastcall TCustomScpExplorerForm::ClipboardDataObjectRelease(TObject * /*Sender*/)
  10744. {
  10745. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()))
  10746. {
  10747. ClipboardStop();
  10748. }
  10749. }
  10750. //---------------------------------------------------------------------------
  10751. void __fastcall TCustomScpExplorerForm::ClipboardDownload(const UnicodeString & TargetDirectory, bool NoConfirmation, bool DragDrop)
  10752. {
  10753. TTerminalManager * Manager = TTerminalManager::Instance();
  10754. Manager->ActiveSession = FClipboardTerminal;
  10755. TTransferOperationParam Params;
  10756. Params.TargetDirectory = TargetDirectory;
  10757. Params.DragDrop = DragDrop;
  10758. ExecuteFileOperation(foCopy, osRemote, FClipboardFileList.get(), NoConfirmation, &Params);
  10759. }
  10760. //---------------------------------------------------------------------------
  10761. void TCustomScpExplorerForm::PasteFiles()
  10762. {
  10763. // Guard against possible race conditions
  10764. if (!FClipboardPasteTarget.IsEmpty())
  10765. {
  10766. // ClipboardFakeCreated might be called while we are here, so make sure we finish operating on the same path we started with
  10767. UnicodeString Target = FClipboardPasteTarget;
  10768. FClipboardPasteTarget = EmptyStr;
  10769. // Can fail as it can be e.g. locked by AV, so we retry that later
  10770. bool Removed = RemoveDir(ApiPath(Target));
  10771. AppLogFmt(L"First attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10772. try
  10773. {
  10774. if (NonVisualDataModule->Busy)
  10775. {
  10776. AppLog(L"Is busy, cannot paste");
  10777. }
  10778. else
  10779. {
  10780. DebugAssert(!FClipboardFakeMonitorsPendingReset);
  10781. FClipboardFakeMonitorsPendingReset = false;
  10782. bool NoConfirmation = (WinConfiguration->DDTransferConfirmation == asOff);
  10783. TAutoFlag Flag(FDownloadingFromClipboard);
  10784. AppLog(L"Downloading to paste target...");
  10785. ClipboardDownload(ExtractFilePath(Target), NoConfirmation, true);
  10786. AppLog(L"Downloaded to paste target...");
  10787. }
  10788. }
  10789. __finally
  10790. {
  10791. if (!Removed)
  10792. {
  10793. Removed = RemoveDir(ApiPath(Target));
  10794. AppLogFmt(L"Second attempt to delete pasted fake clipboard directory \"%s\" - %d", (Target, int(Removed)));
  10795. }
  10796. }
  10797. }
  10798. }
  10799. //---------------------------------------------------------------------------
  10800. void __fastcall TCustomScpExplorerForm::ClipboardFakeCreated(TObject * /*Sender*/, const UnicodeString FileName)
  10801. {
  10802. // It can actually rarelly happen that some random file is created, while we are shutting down the monitor
  10803. // (as it pumps a Windows message queue while being shutted down)
  10804. if (DebugAlwaysTrue(!FClipboardFakeDirectory.IsEmpty()) &&
  10805. // Is can happen that creation of our temporary directory is detected (even though we are creating it before starting the monitors).
  10806. // It tent do happen with later copy-pastes, probably because everything is cached already and monitors start quickly.
  10807. !IsPathToSameFile(FClipboardFakeDirectory, FileName) &&
  10808. SameText(ExtractFileName(FileName), ExtractFileName(FClipboardFakeDirectory)))
  10809. {
  10810. AppLogFmt(L"Fake clipboard directory pasted to \"%s\"", (FileName));
  10811. FClipboardPasteTarget = FileName;
  10812. // Particularly when pasting to external HDD, the fake directory is strangely recreated if removed here in the monitor callback.
  10813. // Postponing removing (or actually whole pasting operation) seems to help.
  10814. PostMessage(Handle, WM_PASTE_FILES, 0, 0);
  10815. }
  10816. }
  10817. //---------------------------------------------------------------------------
  10818. void __fastcall TCustomScpExplorerForm::DirViewGetItemColor(
  10819. TObject * Sender, UnicodeString FileName, bool Directory, __int64 Size, TDateTime Modification, TColor & Color)
  10820. {
  10821. TFileMasks::TParams MaskParams;
  10822. MaskParams.Size = Size;
  10823. MaskParams.Modification = Modification;
  10824. TCustomDirView * DirView = DebugNotNull(dynamic_cast<TCustomDirView *>(Sender));
  10825. bool Local = (dynamic_cast<TUnixDirView *>(DirView) == NULL);
  10826. // TUnixDirView::ItemFullFileName returns trailing backslash for directories, what filemask cannot deal with
  10827. if (!Local && Directory)
  10828. {
  10829. FileName = UnixExcludeTrailingBackslash(FileName);
  10830. }
  10831. for (TFileColorData::TList::const_iterator Iter = FFileColors.begin(); Iter != FFileColors.end(); Iter++)
  10832. {
  10833. bool ImplicitMatch;
  10834. if (Iter->FileMask.Matches(FileName, Local, Directory, &MaskParams, false, ImplicitMatch) &&
  10835. !ImplicitMatch)
  10836. {
  10837. Color = Iter->Color;
  10838. break;
  10839. }
  10840. }
  10841. }
  10842. //---------------------------------------------------------------------------
  10843. void __fastcall TCustomScpExplorerForm::DirViewKeyDown(TObject * Sender, WORD & Key, TShiftState)
  10844. {
  10845. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10846. if (!DirView->IsEditing())
  10847. {
  10848. // Handled here, instead of RemoteDirViewKeyPress (as on Login dialog),
  10849. // as VK_BACK is handled by TCustomDirView.KeyDown and we can swallow it here,
  10850. // while searching
  10851. if (Key == VK_BACK)
  10852. {
  10853. if (!FIncrementalSearch.IsEmpty())
  10854. {
  10855. if (FIncrementalSearch.Length() == 1)
  10856. {
  10857. ResetIncrementalSearch();
  10858. }
  10859. else
  10860. {
  10861. UnicodeString NewText = FIncrementalSearch.SubString(1, FIncrementalSearch.Length() - 1);
  10862. IncrementalSearch(NewText, false, false);
  10863. }
  10864. Key = 0;
  10865. }
  10866. }
  10867. }
  10868. }
  10869. //---------------------------------------------------------------------------
  10870. void __fastcall TCustomScpExplorerForm::DirViewKeyPress(TObject * Sender, wchar_t & Key)
  10871. {
  10872. TCustomDirView * DirView = dynamic_cast<TCustomDirView *>(Sender);
  10873. if (!DirView->IsEditing() && (WinConfiguration->PanelSearch != isOff))
  10874. {
  10875. // Filter control sequences.
  10876. // When not searching yet, prefer use of the space for toggling file selection
  10877. // (so we cannot incrementally search for a string starting with a space).
  10878. if ((Key > VK_SPACE) ||
  10879. ((Key == VK_SPACE) && (GetKeyState(VK_CONTROL) >= 0) && !FIncrementalSearch.IsEmpty()))
  10880. {
  10881. IncrementalSearch(FIncrementalSearch + Key, false, false);
  10882. Key = 0;
  10883. }
  10884. }
  10885. }
  10886. //---------------------------------------------------------------------------
  10887. void __fastcall TCustomScpExplorerForm::ResetIncrementalSearch()
  10888. {
  10889. if (!FIncrementalSearch.IsEmpty())
  10890. {
  10891. FIncrementalSearch = L"";
  10892. DirView(osCurrent)->UpdateStatusBar();
  10893. }
  10894. }
  10895. //---------------------------------------------------------------------------
  10896. void __fastcall TCustomScpExplorerForm::IncrementalSearch(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10897. {
  10898. TListItem * Item = SearchFile(Text, SkipCurrent, Reverse);
  10899. if (Item == NULL)
  10900. {
  10901. MessageBeep(MB_ICONHAND);
  10902. }
  10903. else
  10904. {
  10905. TCustomDirView * ADirView = DirView(osCurrent);
  10906. {
  10907. TAutoNestingCounter Guard(FIncrementalSearching);
  10908. ADirView->FocusItem(Item);
  10909. if (ADirView->NortonLike == nlOff)
  10910. {
  10911. if ((ADirView->Selected != Item) ||
  10912. (ADirView->SelCount > 1))
  10913. {
  10914. ADirView->ClearSelection();
  10915. ADirView->Selected = Item;
  10916. }
  10917. }
  10918. }
  10919. FIncrementalSearch = Text;
  10920. Item->MakeVisible(false);
  10921. TListItem * NextItem = SearchFile(Text, true, Reverse);
  10922. FIncrementalSearchHaveNext = (NextItem != NULL) && (NextItem != Item);
  10923. ADirView->UpdateStatusBar();
  10924. }
  10925. }
  10926. //---------------------------------------------------------------------------
  10927. TListItem * __fastcall TCustomScpExplorerForm::GetNextFile(TListItem * Item, bool Reverse)
  10928. {
  10929. int Index = Item->Index;
  10930. if (!Reverse)
  10931. {
  10932. Index++;
  10933. if (Index >= Item->Owner->Count)
  10934. {
  10935. Index = 0;
  10936. }
  10937. }
  10938. else
  10939. {
  10940. Index--;
  10941. if (Index < 0)
  10942. {
  10943. Index = Item->Owner->Count - 1;
  10944. }
  10945. }
  10946. return Item->Owner->Item[Index];
  10947. }
  10948. //---------------------------------------------------------------------------
  10949. TListItem * __fastcall TCustomScpExplorerForm::SearchFile(const UnicodeString & Text, bool SkipCurrent, bool Reverse)
  10950. {
  10951. TCustomDirView * ADirView = DirView(osCurrent);
  10952. if (ADirView->Items->Count == 0)
  10953. {
  10954. return NULL;
  10955. }
  10956. else
  10957. {
  10958. TListItem * CurrentItem = (ADirView->ItemFocused != NULL) ? ADirView->ItemFocused : ADirView->Items->Item[0];
  10959. TListItem * Item = CurrentItem;
  10960. if (SkipCurrent)
  10961. {
  10962. Item = DebugNotNull(GetNextFile(Item, Reverse));
  10963. }
  10964. while (true)
  10965. {
  10966. bool Matches = false;
  10967. switch (WinConfiguration->PanelSearch)
  10968. {
  10969. case isNameStartOnly:
  10970. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item).SubString(1, Text.Length()), Text);
  10971. break;
  10972. case isName:
  10973. Matches = ContainsTextSemiCaseSensitive(ADirView->ItemFileName(Item), Text);
  10974. break;
  10975. case isAll:
  10976. int ColCount = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Count : 1;
  10977. int Index = 0;
  10978. while ((Index < ColCount) && !Matches)
  10979. {
  10980. bool Visible = (ADirView->ViewStyle == vsReport) ? ADirView->ColProperties->Visible[Index] : true;
  10981. if (Visible)
  10982. {
  10983. Matches = ContainsTextSemiCaseSensitive(ADirView->GetColumnText(Item, Index), Text);
  10984. }
  10985. Index++;
  10986. }
  10987. break;
  10988. }
  10989. if (Matches)
  10990. {
  10991. return Item;
  10992. }
  10993. Item = GetNextFile(Item, Reverse);
  10994. if (Item == CurrentItem)
  10995. {
  10996. return NULL;
  10997. }
  10998. }
  10999. }
  11000. }
  11001. //---------------------------------------------------------------------------
  11002. void __fastcall TCustomScpExplorerForm::DirViewExit(TObject *)
  11003. {
  11004. ResetIncrementalSearch();
  11005. }
  11006. //---------------------------------------------------------------------------
  11007. void __fastcall TCustomScpExplorerForm::CMDialogKey(TWMKeyDown & Message)
  11008. {
  11009. if (Message.CharCode == VK_TAB)
  11010. {
  11011. if (!FIncrementalSearch.IsEmpty())
  11012. {
  11013. TShiftState Shift = KeyDataToShiftState(Message.KeyData);
  11014. bool Reverse = Shift.Contains(ssShift);
  11015. IncrementalSearch(FIncrementalSearch, true, Reverse);
  11016. Message.Result = 1;
  11017. return;
  11018. }
  11019. }
  11020. else if (Message.CharCode == VK_ESCAPE)
  11021. {
  11022. if (!FIncrementalSearch.IsEmpty())
  11023. {
  11024. ResetIncrementalSearch();
  11025. Message.Result = 1;
  11026. return;
  11027. }
  11028. }
  11029. TForm::Dispatch(&Message);
  11030. }
  11031. //---------------------------------------------------------------------------
  11032. void __fastcall TCustomScpExplorerForm::Deactivate()
  11033. {
  11034. TForm::Deactivate();
  11035. // E.g. when switching to an internal editor window
  11036. ResetIncrementalSearch();
  11037. }
  11038. //---------------------------------------------------------------------------
  11039. void __fastcall TCustomScpExplorerForm::ApplicationEventsDeactivate(TObject *)
  11040. {
  11041. // When switching to another application
  11042. ResetIncrementalSearch();
  11043. }
  11044. //---------------------------------------------------------------------------
  11045. void __fastcall TCustomScpExplorerForm::ApplicationEventsModalBegin(TObject *)
  11046. {
  11047. ResetIncrementalSearch();
  11048. }
  11049. //---------------------------------------------------------------------------
  11050. void __fastcall TCustomScpExplorerForm::DirViewChangeFocus(TObject *, TListItem *)
  11051. {
  11052. if (FIncrementalSearching <= 0)
  11053. {
  11054. ResetIncrementalSearch();
  11055. }
  11056. }
  11057. //---------------------------------------------------------------------------
  11058. void __fastcall TCustomScpExplorerForm::RemoteStatusBarMouseDown(TObject *, TMouseButton, TShiftState, int, int)
  11059. {
  11060. CountClicksForWindowPrint(this);
  11061. }
  11062. //---------------------------------------------------------------------------
  11063. void __fastcall TCustomScpExplorerForm::RemoteDirViewResize(TObject *)
  11064. {
  11065. CenterReconnectToolbar();
  11066. }
  11067. //---------------------------------------------------------------------------
  11068. void TCustomScpExplorerForm::DoBrowseFile(TCustomDirView * DirView, const UnicodeString & FileName)
  11069. {
  11070. if (!FileName.IsEmpty())
  11071. {
  11072. DirView->RestoreFocus(FileName);
  11073. if (DirView->ItemFocused != NULL)
  11074. {
  11075. DirView->ItemFocused->Selected = true;
  11076. }
  11077. }
  11078. }
  11079. //---------------------------------------------------------------------------
  11080. void __fastcall TCustomScpExplorerForm::BrowseFile(const UnicodeString & FileName)
  11081. {
  11082. DoBrowseFile(RemoteDirView, FileName);
  11083. }
  11084. //---------------------------------------------------------------------------
  11085. void __fastcall TCustomScpExplorerForm::UpdateQueueFileList()
  11086. {
  11087. if (!FQueueStatusUpdating)
  11088. {
  11089. bool Refresh;
  11090. if ((FQueueStatus != NULL) && QueueFileList->Visible)
  11091. {
  11092. Refresh = FQueueStatus->UpdateFileList(FQueueController->GetFocusedPrimaryItem(), FQueueFileList.get());
  11093. }
  11094. else
  11095. {
  11096. if (FQueueFileList->GetCount() > 0)
  11097. {
  11098. FQueueFileList->Clear();
  11099. Refresh = true;
  11100. }
  11101. }
  11102. int Count = FQueueFileList->GetCount();
  11103. if (QueueFileList->Items->Count != Count)
  11104. {
  11105. DebugAssert(Refresh);
  11106. QueueFileList->Items->Count = Count;
  11107. }
  11108. if (Refresh)
  11109. {
  11110. QueueFileList->Invalidate();
  11111. }
  11112. DebugAssert(QueueFileList->Items->Count == FQueueFileList->GetCount());
  11113. }
  11114. }
  11115. //---------------------------------------------------------------------------
  11116. void __fastcall TCustomScpExplorerForm::QueueFileListData(TObject *, TListItem * Item)
  11117. {
  11118. Item->Caption = FQueueFileList->GetFileName(Item->Index);
  11119. }
  11120. //---------------------------------------------------------------------------
  11121. void __fastcall TCustomScpExplorerForm::QueueView3Change(TObject *, TListItem *, TItemChange)
  11122. {
  11123. // Should be improved, once we do not refresh the list when switching between details of the same batch.
  11124. // See TSynchronizeChecklistDialog::UpdateTimer
  11125. if (QueueFileList->Items->Count > 0)
  11126. {
  11127. QueueFileList->Items->Item[0]->MakeVisible(false);
  11128. }
  11129. UpdateQueueFileList();
  11130. }
  11131. //---------------------------------------------------------------------------
  11132. void __fastcall TCustomScpExplorerForm::QueueLabelGetStatus(TCustomPathLabel *, bool & Active)
  11133. {
  11134. Active = QueueView3->Focused() || QueueFileList->Focused();
  11135. }
  11136. //---------------------------------------------------------------------------
  11137. void __fastcall TCustomScpExplorerForm::QueueFileListEnterExit(TObject *)
  11138. {
  11139. QueueLabelUpdateStatus();
  11140. }
  11141. //---------------------------------------------------------------------------
  11142. void __fastcall TCustomScpExplorerForm::QueueFileListCustomDrawItem(
  11143. TCustomListView * Sender, TListItem * Item, TCustomDrawState, bool & DebugUsedArg(DefaultDraw))
  11144. {
  11145. int State = FQueueFileList->GetState(Item->Index);
  11146. if (State == qfsProcessed)
  11147. {
  11148. Sender->Canvas->Font->Color = clGrayText;
  11149. }
  11150. }
  11151. //---------------------------------------------------------------------------
  11152. void __fastcall TCustomScpExplorerForm::QueueFileListColumnAutoSize()
  11153. {
  11154. // We do not really need whole width, so we always preemptivelly keep free space for the vertical scrollbar
  11155. QueueFileList->Column[0]->Width =
  11156. QueueFileList->ClientWidth - GetSystemMetricsForControl(QueueFileList, SM_CXVSCROLL) - ScaleByTextHeight(QueueFileList, 8);
  11157. }
  11158. //---------------------------------------------------------------------------
  11159. void __fastcall TCustomScpExplorerForm::QueueFileListResize(TObject *)
  11160. {
  11161. QueueFileListColumnAutoSize();
  11162. }
  11163. //---------------------------------------------------------------------------
  11164. void __fastcall TCustomScpExplorerForm::CloseApp()
  11165. {
  11166. // Called from TNonVisualDataModule::ExplorerActionsExecute, which sets busy flag.
  11167. // FormCloseQuery must check busy state, so that the application cannot be closed while busy by Alt+F4 and X button.
  11168. // So we clear the flag here.
  11169. DebugAssert(NonVisualDataModule->Busy);
  11170. NonVisualDataModule->EndBusy();
  11171. try
  11172. {
  11173. Close();
  11174. }
  11175. __finally
  11176. {
  11177. NonVisualDataModule->StartBusy();
  11178. }
  11179. }
  11180. //---------------------------------------------------------------------------
  11181. bool __fastcall TCustomScpExplorerForm::IsActiveTerminal(TTerminal * Terminal)
  11182. {
  11183. return (Terminal != NULL) && Terminal->Active;
  11184. }
  11185. //---------------------------------------------------------------------------
  11186. bool __fastcall TCustomScpExplorerForm::HasManagedSession()
  11187. {
  11188. return (ManagedSession != NULL);
  11189. }
  11190. //---------------------------------------------------------------------------
  11191. bool __fastcall TCustomScpExplorerForm::HasActiveTerminal()
  11192. {
  11193. return IsActiveTerminal(Terminal);
  11194. }
  11195. //---------------------------------------------------------------------------
  11196. void TCustomScpExplorerForm::LocalLocalCopy(
  11197. TFileOperation, TOperationSide, bool DebugUsedArg(OnFocused), bool DebugUsedArg(NoConfirmation),
  11198. bool DebugUsedArg(DragDrop), unsigned int DebugUsedArg(Flags))
  11199. {
  11200. DebugFail();
  11201. }
  11202. //---------------------------------------------------------------------------
  11203. void TCustomScpExplorerForm::LocalLocalCopyCommand(TFileOperation Operation, TOperationSide Side, bool OnFocused, unsigned int Flags)
  11204. {
  11205. LocalLocalCopy(Operation, Side, OnFocused, !WinConfiguration->ConfirmTransferring, false, Flags);
  11206. }
  11207. //---------------------------------------------------------------------------
  11208. void __fastcall TCustomScpExplorerForm::SessionsPageControlResize(TObject *)
  11209. {
  11210. // 1) Changing tab list triggers the OnResize.
  11211. // 2) Is called in TForm constructor, when we are not ready to call SessionListChanged (particularly when starting with colored session)
  11212. if (!FUpdatingSessionTabs && (FSessionColors != NULL))
  11213. {
  11214. // UpdateTabsCaptionTruncation should be enough
  11215. SessionListChanged(true);
  11216. }
  11217. }
  11218. //---------------------------------------------------------------------------
  11219. UnicodeString TCustomScpExplorerForm::GetSessionPath(TManagedTerminal * ASession, TOperationSide Side)
  11220. {
  11221. if (ASession == ManagedSession)
  11222. {
  11223. UpdateSession(ASession);
  11224. }
  11225. TSessionData * Data = ASession->StateData;
  11226. UnicodeString Result;
  11227. if (Side == osLocal)
  11228. {
  11229. Result = Data->LocalDirectory;
  11230. }
  11231. else if (DebugAlwaysTrue(Side == osOther))
  11232. {
  11233. Result = ASession->LocalBrowser ? Data->OtherLocalDirectory : Data->RemoteDirectory;
  11234. }
  11235. return Result;
  11236. }
  11237. //---------------------------------------------------------------------------
  11238. UnicodeString TCustomScpExplorerForm::GetTabHintSessionDetails(TManagedTerminal * ASession)
  11239. {
  11240. UnicodeString Title = TTerminalManager::Instance()->GetSessionTitle(ASession, false);
  11241. UnicodeString Result = ASession->SessionData->DefaultSessionName;
  11242. if (Title == Result)
  11243. {
  11244. Result = EmptyStr;
  11245. }
  11246. else
  11247. {
  11248. Result += L"\n";
  11249. }
  11250. return Result;
  11251. }
  11252. //---------------------------------------------------------------------------
  11253. UnicodeString TCustomScpExplorerForm::GetTabHintDetails(TManagedTerminal * ASession)
  11254. {
  11255. UnicodeString Result = GetTabHintSessionDetails(ASession);
  11256. if (!ASession->Active)
  11257. {
  11258. Result += LoadStr(STATUS_NOT_CONNECTED2);
  11259. }
  11260. else
  11261. {
  11262. Result += GetSessionPath(ASession, osRemote);
  11263. }
  11264. return Result;
  11265. }
  11266. //---------------------------------------------------------------------------
  11267. UnicodeString TCustomScpExplorerForm::GetNewTabHintDetails()
  11268. {
  11269. return LoadStr(NEW_REMOTE_TAB_HINT);
  11270. }
  11271. //---------------------------------------------------------------------------
  11272. void __fastcall TCustomScpExplorerForm::SessionsPageControlTabHint(TPageControl *, int Index, UnicodeString & Hint)
  11273. {
  11274. if (Index >= 0)
  11275. {
  11276. TThemeTabSheet * TabSheet = SessionsPageControl->Pages[Index];
  11277. TManagedTerminal * TabSession = GetSessionTabSession(TabSheet);
  11278. if (TabSession == NULL)
  11279. {
  11280. UnicodeString NewTabTabCaption = GetNewTabTabCaption();
  11281. if (NewTabTabCaption != TabSheet->Caption)
  11282. {
  11283. Hint = NewTabTabCaption + L"|" + GetNewTabHintDetails();
  11284. }
  11285. }
  11286. else
  11287. {
  11288. TTerminalManager * Manager = TTerminalManager::Instance();
  11289. UnicodeString TabCaption = Manager->GetSessionTitle(TabSession, true);
  11290. Hint = TabCaption + L"|" + GetTabHintDetails(TabSession);
  11291. }
  11292. }
  11293. }
  11294. //---------------------------------------------------------------------------
  11295. typedef std::vector<TListItem *> TListItemsVector;
  11296. struct TCalculateSizeOperation
  11297. {
  11298. TCalculateSizeStats Stats;
  11299. TListItemsVector ListItems;
  11300. size_t Index;
  11301. };
  11302. //---------------------------------------------------------------------------
  11303. void TCustomScpExplorerForm::CalculateDirectorySizes(TOperationSide Side)
  11304. {
  11305. TCalculateSizeOperation CalculateSizeOperation;
  11306. Side = GetSide(Side);
  11307. TCustomDirView * ADirView = DirView(Side);
  11308. bool LocalSide = IsSideLocalBrowser(Side);
  11309. std::unique_ptr<TStrings> AllFileList(ADirView->CreateFileList(false, LocalSide, NULL, true));
  11310. std::unique_ptr<TStrings> FileList(new TStringList());
  11311. for (int Index = 0; Index < AllFileList->Count; Index++)
  11312. {
  11313. TListItem * Item = DebugNotNull(dynamic_cast<TListItem *>(AllFileList->Objects[Index]));
  11314. if (ADirView->ItemIsDirectory(Item))
  11315. {
  11316. FileList->AddObject(AllFileList->Strings[Index], ADirView->ItemData(Item));
  11317. CalculateSizeOperation.ListItems.push_back(Item);
  11318. }
  11319. }
  11320. CalculateSizeOperation.Index = 0;
  11321. __int64 Size = 0;
  11322. TValueRestorer<TCalculateSizeOperation *> DirectorySizeOperationRestorer(FCalculateSizeOperation, &CalculateSizeOperation);
  11323. TValueRestorer<TFileOperationFinishedEvent> OnFileOperationFinishedRestorer(FOnFileOperationFinished);
  11324. FOnFileOperationFinished = DirectorySizeCalculated;
  11325. TValueRestorer<TFileOperation> PrimaryOperationRestorer(FPrimaryOperation, foCalculateSize);
  11326. TCalculatedSizes CalculatedSizes;
  11327. CalculateSizeOperation.Stats.CalculatedSizes = &CalculatedSizes;
  11328. if (LocalSide)
  11329. {
  11330. TValueRestorer<TOperationSide> ProgressSideRestorer(FProgressSide, Side);
  11331. ManagedSession->CalculateLocalFilesSize(FileList.get(), Size, NULL, true, NULL, &CalculatedSizes);
  11332. }
  11333. else
  11334. {
  11335. TCalculateSizeParams Params;
  11336. Params.Stats = &CalculateSizeOperation.Stats;
  11337. Params.UseCache = true;
  11338. Terminal->CalculateFilesSize(FileList.get(), Size, Params);
  11339. }
  11340. }
  11341. //---------------------------------------------------------------------------
  11342. void __fastcall TCustomScpExplorerForm::DirectorySizeCalculated(TOperationSide Side, const UnicodeString & FileName, bool Success)
  11343. {
  11344. DebugAlwaysTrue(FCalculateSizeOperation != NULL);
  11345. TListItem * Item = VisualiseOperationFinished(Side, FileName, false);
  11346. TCustomDirView * ADirView = dynamic_cast<TCustomDirView *>(Item->Owner->Owner);
  11347. // optimization
  11348. bool GotExpectedItem =
  11349. (FCalculateSizeOperation->Index < FCalculateSizeOperation->ListItems.size()) &&
  11350. (FCalculateSizeOperation->ListItems[FCalculateSizeOperation->Index] == Item);
  11351. int Index = -1;
  11352. if (DebugAlwaysTrue(GotExpectedItem))
  11353. {
  11354. Index = FCalculateSizeOperation->Index;
  11355. FCalculateSizeOperation->Index++;
  11356. }
  11357. else
  11358. {
  11359. TListItemsVector::iterator I =
  11360. std::find(FCalculateSizeOperation->ListItems.begin(), FCalculateSizeOperation->ListItems.end(), Item);
  11361. if (DebugAlwaysTrue(I != FCalculateSizeOperation->ListItems.end()))
  11362. {
  11363. Index = I - FCalculateSizeOperation->ListItems.begin();
  11364. }
  11365. }
  11366. if (DebugAlwaysTrue(Index >= 0) && Success)
  11367. {
  11368. __int64 Size = (*FCalculateSizeOperation->Stats.CalculatedSizes)[Index];
  11369. ADirView->SetItemCalculatedSize(Item, Size);
  11370. }
  11371. }
  11372. //---------------------------------------------------------------------------
  11373. void __fastcall TCustomScpExplorerForm::MessageDockRequestDock(TObject *, TTBCustomDockableWindow *, bool & Accept)
  11374. {
  11375. Accept = false;
  11376. }
  11377. //---------------------------------------------------------------------------
  11378. void TCustomScpExplorerForm::AutoSizeColumns(TOperationSide Side)
  11379. {
  11380. // Send Ctrl+Gray+ to the list view
  11381. TKeyboardState KeyState;
  11382. GetKeyboardState(KeyState);
  11383. TKeyboardState NewKeyState;
  11384. memset(NewKeyState, 0, sizeof(NewKeyState));
  11385. NewKeyState[VK_CONTROL] = 0x81;
  11386. SetKeyboardState(NewKeyState);
  11387. SendMessage(DirView(Side)->Handle, WM_KEYDOWN, VK_ADD, 0);
  11388. SetKeyboardState(KeyState);
  11389. }
  11390. //---------------------------------------------------------------------------
  11391. void TCustomScpExplorerForm::QueueResetLayoutColumns()
  11392. {
  11393. LoadListViewStr(QueueView3, QueueViewLayoutDefault);
  11394. }
  11395. //---------------------------------------------------------------------------
  11396. void * TCustomScpExplorerForm::SaveFocus()
  11397. {
  11398. return NULL;
  11399. }
  11400. //---------------------------------------------------------------------------
  11401. void TCustomScpExplorerForm::RestoreFocus(void * Focus)
  11402. {
  11403. DebugUsedParam(Focus);
  11404. DebugAssert(Focus == NULL);
  11405. }